package com.xinelu.applet.controller.appletscreeningrecord;

import com.alibaba.fastjson2.JSONObject;
import com.xinelu.manage.service.messagepush.MessagePushService;
import com.xinelu.common.annotation.RepeatSubmit;
import com.xinelu.common.config.XinELuConfig;
import com.xinelu.common.constant.ScreeningProjectConstants;
import com.xinelu.common.core.controller.BaseController;
import com.xinelu.common.core.domain.R;
import com.xinelu.common.core.page.TableDataInfo;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.DateUtils;
import com.xinelu.common.utils.StringUtils;
import com.xinelu.common.utils.file.FileUploadUtils;
import com.xinelu.common.utils.file.FileUtils;
import com.xinelu.manage.dto.screeningrecord.ScreeningApplyDTO;
import com.xinelu.manage.dto.screeningrecord.ScreeningRecordDTO;
import com.xinelu.manage.service.screeningrecord.IScreeningRecordService;
import com.xinelu.manage.vo.screeningrecord.ScreeningRecordVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author mengkuiliang
 * @Description 筛查预约控制器
 * @Date 2023-01-29 13:57
 * @Param
 * @return
 **/
@RestController
@RequestMapping("/nurseApplet/screening/record")
@Api(tags = "筛查预约控制器-小程序")
public class AppletScreeningRecordController extends BaseController {

    @Resource
    private IScreeningRecordService screeningRecordService;

    @Resource
    private MessagePushService messagePushService;

    @GetMapping("/record")
    @ApiOperation(value = "获取筛查结果记录")
    public TableDataInfo record(ScreeningRecordDTO query) {
        startPage();
	    query.setScreeningType("1");
	    query.setScreeningStatus("4");
        return getDataTable(screeningRecordService.record(query));
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取列表")
    public TableDataInfo list(ScreeningRecordDTO query) {
        startPage();
	    query.setScreeningType("1");
	    List<ScreeningRecordVo> list = screeningRecordService.list(query);
		// 二维码返回
	    list.forEach(record -> {
		    if (StringUtils.isNotEmpty(record.getApplyBarcode())) {
			    File file = new File(record.getApplyBarcode());
			    if (file.exists() && file.isFile()) {
				    record.setApplyBarcode(FileUtils.PicToBase64(record.getApplyBarcode()));
			    }
		    }
	    });
        return getDataTable(list);
    }

    @PostMapping("/save")
    @ApiOperation(value = "预约")
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    public R<String> save(@RequestBody ScreeningApplyDTO body) {
        if(org.apache.commons.lang3.StringUtils.isBlank(body.getIdentity())) {
            return R.fail("居民身份证号不能为空");
        }
        try {
            if(!DateUtils.formatDate(body.getApplyStartTime(), "yyyy-MM-dd").equals(DateUtils.formatDate(body.getApplyEndTime(), "yyyy-MM-dd"))) {
                return R.fail("预约日期请选择在同一天");
            }
            JSONObject result = screeningRecordService.save(body);
            if(result != null && result.containsKey("openid")) {
                messagePushService.fdApprovePush(result);
            }
            return R.ok(result.getString("patientId"));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @GetMapping("/cancel/{screeningId}")
    @ApiOperation(value = "取消预约")
    public R<String> cancel(@PathVariable String screeningId) {
		// 判断是否已登记
	    ScreeningRecordVo screeningRecordVo = screeningRecordService.detail(screeningId);
		if (StringUtils.equals(screeningRecordVo.getScreeningStatus(), "3") || StringUtils.equals(screeningRecordVo.getScreeningStatus(), "4")) {
			return R.fail("该预约已登记，不能取消");
		}
        screeningRecordService.cancel(screeningId);
        return R.ok();
    }

    @GetMapping("/detail/{screeningId}")
    @ApiOperation(value = "获取预约详情")
    public R<ScreeningRecordVo> detail(@PathVariable String screeningId) {
        ScreeningRecordVo screeningRecordVo = screeningRecordService.detail(screeningId);
		if (screeningRecordVo != null) {
			if (StringUtils.isNotBlank(screeningRecordVo.getAttachment())){
				String fileDir = XinELuConfig.getProfile() + screeningRecordVo.getAttachment().replaceAll("/profile", "");
				File file = new File(fileDir);
				if (file.exists() && file.isFile()) {
					String fileName = file.getName();
					screeningRecordVo.setFileType(fileName.substring(fileName.lastIndexOf(".") + 1));
				}
			}

			if (!StringUtils.contains(screeningRecordVo.getProjectName(), ScreeningProjectConstants.ALZHEIMER)) {
				screeningRecordService.getRecordDetail(screeningRecordVo);
			}
		}
        return R.ok(screeningRecordVo);
    }

    @GetMapping("/getScreening/{patientId}")
    @ApiOperation(value = "获取当前预约信息")
    public R<ScreeningRecordVo> getScreeningByPatientId(@PathVariable String patientId) {
        return R.ok(screeningRecordService.getScreeningByPatientId(patientId));
    }

    @GetMapping("/last/{patientId}/{projectId}")
    @ApiOperation(value = "获取最新一次筛查结果")
    public R<ScreeningRecordVo> last(@PathVariable String patientId, @PathVariable String projectId) {
        ScreeningRecordVo screeningRecordVo = screeningRecordService.last(patientId, projectId);
        return R.ok(screeningRecordVo);
    }

	@GetMapping("/getInfo/{assessRecordId}")
	@ApiOperation(value = "推送筛查项目跳转查询推荐详情")
	public R<JSONObject> getInfo(@PathVariable("assessRecordId") String assessRecordId) {
		JSONObject jsonObject = screeningRecordService.getInfo(assessRecordId);
		return R.ok(jsonObject);
	}

	@ApiOperation("阿尔兹海默症结果预览")
	@GetMapping("/fileview")
	public void fileview(@RequestParam("filePath") String filePath, HttpServletResponse response) {
		if (StringUtils.isNotEmpty(filePath)) {
			String fileDir = XinELuConfig.getProfile() + filePath.replaceAll("/profile", "");
			File file = new File(fileDir);
			if (file.exists() && file.isFile()) {
				FileUploadUtils.read(fileDir, response);
			} else {
				throw new ServiceException("未找到文件");
			}
		}
	}
}
