package thyyxxk.webserver.service.chronicDisease;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.YbTjConstant;
import thyyxxk.webserver.dao.his.chronicDisease.ChronicDiseaseDao;
import thyyxxk.webserver.dao.his.chronicDisease.CrmPatientMiDao;
import thyyxxk.webserver.dao.his.chronicDisease.CrmPatientTzxxDao;
import thyyxxk.webserver.dao.his.chronicDisease.CrmVisitRecordDao;
import thyyxxk.webserver.dao.his.inpatient.casefrontsheet.SheetCreatedDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.chronicDisease.CrmPatientMi;
import thyyxxk.webserver.entity.chronicDisease.CrmPatientTzxx;
import thyyxxk.webserver.entity.chronicDisease.CrmPatientVo;
import thyyxxk.webserver.entity.chronicDisease.CrmVisitRecord;
import thyyxxk.webserver.entity.chronicDisease.CrmVisitRecordVo;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.service.externalhttp.emr.EmrEditor;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.YbReportUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassName ChronicDiseaseService
 * @Author Administrator
 * @Date 2023/11/23 14:37
 * @Version 1.0
 * @Description 慢特病管理
 **/
@Service
@Slf4j
public class ChronicDiseaseService {

    private final ChronicDiseaseDao dao;
    private final CrmPatientMiDao cpmDao;
    private final SheetCreatedDao createdDao;
    private final CrmPatientTzxxDao tzxxDao;
    private final EmrEditor emr;
    private final CrmVisitRecordDao crmEmrDao;
    private final UserCache userCache;

    public ChronicDiseaseService(ChronicDiseaseDao dao, CrmPatientMiDao cpmDao, SheetCreatedDao createdDao, CrmPatientTzxxDao tzxxDao, EmrEditor emr, CrmVisitRecordDao crmEmrDao, UserCache userCache) {
        this.dao = dao;
        this.cpmDao = cpmDao;
        this.createdDao = createdDao;
        this.tzxxDao = tzxxDao;
        this.emr = emr;
        this.crmEmrDao = crmEmrDao;
        this.userCache = userCache;
    }

    /**
     *  根据关键字查询慢特病基本信息
     * @param keyCode 关键字
     * @return 慢特病基本信息
     */
    public ResultVo<CrmPatientMi> selectCrmPatientMiByCode(String keyCode) {
        if (StringUtil.isBlank(keyCode)) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "查询的慢特病基本信息关键字不存在");
        }
        CrmPatientMi mi = cpmDao.selectCrmPatientMiByCode(keyCode);
        if (null == mi) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, keyCode + "查询的慢特病基本信息不存在");
        }

        if (StringUtil.notBlank(mi.getChronicDiseaseType())) {
            mi.setChronicDiseaseTypeArr(Arrays.asList(mi.getChronicDiseaseType().split(",")));
        }
        return ResultVoUtil.success(mi);
    }

    /**
     *  更新慢特病基本信息
     * @param crmMi 慢特病基本信息
     * @return map
     */
    public ResultVo<Map<String, Object>> updateCrmPatientMi(CrmPatientMi crmMi) {

        String msg = callCheckParamForCrm(crmMi);
        if (StringUtil.notBlank(msg)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, msg);
        }

        CrmPatientMi mi = cpmDao.selectCrmPatientMiByPId(crmMi.getPId());
        if (null == mi) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, crmMi.getSocialNo() + "慢特病基本信息不存在，更新失败!");
        }
        CrmPatientTzxx crmTzXx = tzxxDao.selectCrmTzxxByPid(crmMi.getPId(), crmMi.getVisitTimes());
        Map<String, Object> resultMap = new HashMap<>();
        try {
            cpmDao.deleteCrmPatientMiByPId(crmMi.getPId());
            tzxxDao.deleteCrmTzxxByPid(crmMi.getPId(), crmMi.getVisitTimes());
            int num = cpmDao.insert(crmMi);
            CrmPatientTzxx tzXx = getCrmPatientTzxx(crmMi);
            int nom = tzxxDao.insert(tzXx);
            if (num == 0) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "更新慢特病基本信息失败！");
            }
            resultMap.put("cg", "更新慢特病基本信息成功！");
            return ResultVoUtil.success(resultMap);
        } catch (Exception e) {
            log.info("更新慢特病基本信息失败:" + e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "更新慢特病基本信息失败！");
        }

    }

    /**
     *  新增慢特病基本信息
     * @param crmMi 慢特病基本信息
     * @return map
     */
    public ResultVo<Map<String, Object>> saveCrmPatientMi(CrmPatientMi crmMi) {

        String msg = callCheckParamForCrm(crmMi);

        if (StringUtil.notBlank(msg)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, msg);
        }

        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtil.notBlank(crmMi.getPId())) {
                CrmPatientMi mi = cpmDao.selectCrmPatientMiByPId(crmMi.getPId());
                if (null != mi) {
                    cpmDao.deleteCrmPatientMiByPId(crmMi.getPId());
                }
            } else {
                // 填写身份证件判断是否已存在信息
                CrmPatientMi mi1 = cpmDao.selectCrmPatientMiBySocialNo(crmMi.getSocialNo());
                if (null != mi1) {
                    return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, crmMi.getSocialNo().substring(crmMi.getSocialNo().length() - 4) + "已存在首次慢病信息，无需重新登记!");
                }
                // 新增的时候添加pId
                String pId = YbTjConstant.CRM_YY_TH + YbReportUtil.generateUkStr(1, 8);
                crmMi.setPId(pId);
                //补充登记时间
                if (StringUtil.isBlank(crmMi.getCreateDate())) {
                    crmMi.setCreateDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }
            }

            // 根据证件号补充基本信息
            CrmVisitRecordVo data = crmEmrDao.selectCrmEmrPatientVoByMzCode(crmMi.getSocialNo());
            if (null != data && StringUtil.isBlank(crmMi.getHisMzNo())) {
                crmMi.setHisMzNo(data.getHisMzNo());
            }
            data = crmEmrDao.selectCrmEmrPatientVoByZyCode(crmMi.getSocialNo());
            if (null != data && StringUtil.isBlank(crmMi.getHisZyNo())) {
                crmMi.setHisZyNo(data.getHisZyNo());
            }
            if (crmMi.getBirthDate() != null) {
                crmMi.setBirthDate(DateUtil.format(DateUtil.parse(crmMi.getBirthDate(), "yyyy-MM-dd"), "yyyy-MM-dd"));
            }
            int num = cpmDao.insert(crmMi);
            if (num == 0) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存慢特病基本信息失败！");
            }
            CrmPatientTzxx crmTzXx = tzxxDao.selectCrmTzxxByPid(crmMi.getPId(), crmMi.getVisitTimes());
            if (null != crmTzXx) {
                tzxxDao.deleteCrmTzxxByPid(crmMi.getPId(), crmMi.getVisitTimes());
            }
            CrmPatientTzxx tzXx = getCrmPatientTzxx(crmMi);
            int nom = tzxxDao.insert(tzXx);
            resultMap.put("cg", "保存慢特病基本信息成功！");
            return ResultVoUtil.success(resultMap);
        } catch (Exception e) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存慢特病基本信息失败！" + e.getMessage());
        }

    }

    @NotNull
    private static CrmPatientTzxx getCrmPatientTzxx(CrmPatientMi crmMi) {
        CrmPatientTzxx tzXx = new CrmPatientTzxx();
        tzXx.setPId(crmMi.getPId());
        tzXx.setVisitTimes(crmMi.getVisitTimes());
        tzXx.setVisitDate(crmMi.getVisitDate());
        tzXx.setInputId(crmMi.getCreatId());
        tzXx.setHeight(crmMi.getHeight());
        tzXx.setWeight(crmMi.getWeight());
        tzXx.setTemperature(crmMi.getTemperature());
        tzXx.setHeartRate(crmMi.getHeartRate());
        tzXx.setBloodPressureLow(crmMi.getBloodPressureLow());
        tzXx.setBloodPressureHigh(crmMi.getBloodPressureHigh());
        tzXx.setBloodSugar(crmMi.getBloodSugar());
        tzXx.setBloodOxygen(crmMi.getBloodOxygen());
        tzXx.setRespiratoryRate(crmMi.getRespiratoryRate());
        return tzXx;
    }

    public ResultVo<Map<String, List<CodeName>>> getCrmDictionary() {
        Map<String, List<CodeName>> crmDictionary = new HashMap<>();
        // 性别字典
        crmDictionary.put("getSexCode", createdDao.getSexCode());
        // 婚姻状况字典
        crmDictionary.put("getMarriageCode", createdDao.getMarriageCode());
        // 联系人关系字典
        crmDictionary.put("getRelations", createdDao.getRelations());
        // 职业字典
        crmDictionary.put("getOccupation", createdDao.getOccupation());
        // 国家字典
        crmDictionary.put("getCountry", createdDao.getCountry());
        // 民族字典
        crmDictionary.put("getNation", createdDao.getNation());
        // 慢特病类型字典
        crmDictionary.put("getCrmClass", dao.getCrmClass());
//            // 省
//            crmDictionary.put("getProvince", dao.getProvince());
//            // 市
//            crmDictionary.put("getCity", dao.getCity(""));
//            // 区
//            crmDictionary.put("getArea", dao.getArea(""));
        // 证件类型字典
        crmDictionary.put("getPsnCertType", dao.getPsnCertType());
        // 来源途径
        crmDictionary.put("getAdmissWay", dao.getAdmissWay());
        return ResultVoUtil.success(crmDictionary);
    }

    /**
     * 根据code查询市信息
     * @param code 编码
     * @return CodeName 市信息
     */
    public ResultVo<List<CodeName>> getCrmCityByCode(String code) {
        return ResultVoUtil.success(dao.getCity(code));
    }

    /**
     * 根据code查询区信息
     * @param code 编码
     * @return CodeName 区信息
     */
    public ResultVo<List<CodeName>> getCrmAreaByCode(String code) {
        return ResultVoUtil.success(dao.getArea(code));
    }

    private String callCheckParamForCrm(@NotNull CrmPatientMi crmMi) {
        String msg = "";
        String s = "^\\d+$";
        String s1 = "^\\d+(\\.\\d+)?$";
        String sfz15 = "^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$";
        String sfz18 = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
        if (StringUtil.isBlank(crmMi.getSocialNo())) {
            msg = "保存慢特病基本信息失败，证件号为空，请检查！";
        } else if (StringUtil.isBlank(crmMi.getPName())) {
            msg = "保存慢特病基本信息失败，用户名称为空，请检查！";
        } else if (StringUtil.isBlank(crmMi.getPType())) {
            msg = "保存慢特病基本信息失败，病人来源为空，请检查！";
        }
        if (null != crmMi.getHeight()) {
            if (!crmMi.getHeight().toString().matches(s1)) {
                msg = "保存慢特病基本信息失败，病人身高填写不符合(仅限纯数字以及小数点)，请检查！";
            } else if (crmMi.getHeight().toString().length() > 10) {
                msg = "保存慢特病基本信息失败，病人身高填写不符合(数据超长，不能超过10个字符)，请检查！";
            }
        }
        if (null != crmMi.getWeight()) {
            if (!String.valueOf(crmMi.getWeight()).matches(s1)) {
                msg = "保存慢特病基本信息失败，病人体重填写不符合(仅限纯数字以及小数点)，请检查！";
            } else if (crmMi.getWeight().toString().length() > 10) {
                msg = "保存慢特病基本信息失败，病人体重填写不符合(数据超长，不能超过10个字符)，请检查！";
            }
        }
        if (null != crmMi.getTemperature()) {
            if (!String.valueOf(crmMi.getTemperature()).matches(s1)) {
                msg = "保存慢特病基本信息失败，病人体温填写不符合(仅限纯数字以及小数点)，请检查！";
            } else if (crmMi.getTemperature().toString().length() > 10) {
                msg = "保存慢特病基本信息失败，病人体温填写不符合(数据超长，不能超过10个字符)，请检查！";
            }
        }
        if (null != crmMi.getHeartRate()) {
            if (!String.valueOf(crmMi.getHeartRate()).matches(s)) {
                msg = "保存慢特病基本信息失败，病人心率填写不符合(仅限纯数字)，请检查！";
            }
        }
        if (null != crmMi.getBloodSugar()) {
            if (!String.valueOf(crmMi.getBloodSugar()).matches(s1)) {
                msg = "保存慢特病基本信息失败，病人血糖填写不符合(仅限纯数字以及小数点)，请检查！";
            } else if (crmMi.getBloodSugar().toString().length() > 10) {
                msg = "保存慢特病基本信息失败，病人血糖填写不符合(数据超长，不能超过10个字符)，请检查！";
            }
        }
        if (null != crmMi.getBloodPressureLow()) {
            if (!String.valueOf(crmMi.getBloodPressureLow()).matches(s)) {
                msg = "保存慢特病基本信息失败，病人舒张血压填写不符合(仅限纯数字)，请检查！";
            }
        }
        if (null != crmMi.getBloodPressureHigh()) {
            if (!String.valueOf(crmMi.getBloodPressureHigh()).matches(s)) {
                msg = "保存慢特病基本信息失败，病人收缩血压填写不符合(仅限纯数字)，请检查！";
            }
        }
        if (StringUtil.notBlank(crmMi.getBloodOxygen())) {
            if (crmMi.getBloodOxygen().length() > 10) {
                msg = "保存慢特病基本信息失败，病人血氧饱和度填写不符合(数据超长，不能超过10个字符)，请检查！";
            }
        }
        if ("1".equals(crmMi.getCertificateType())) {
            if (crmMi.getSocialNo().length() == 15) {
                if (!crmMi.getSocialNo().matches(sfz15)) {
                    msg = "保存慢特病基本信息失败，病人身份证号码(15位)填写不符合，请检查！";
                }
            } else if (crmMi.getSocialNo().length() == 18) {
                if (!crmMi.getSocialNo().matches(sfz18)) {
                    msg = "保存慢特病基本信息失败，病人身份证号码(18位)填写不符合，请检查！";
                }
            } else {
                msg = "保存慢特病基本信息失败，病人身份证号码填写不符合(不是15或18位数)，请检查！";
            }
        }

        return msg;
    }

    /**
     * 查询所有慢特病模板
     * @return 返回模板
     */
    public JSONArray getCrmEmrModel() {
        return emr.getDeptList(YbTjConstant.CRM_DEPT_CODE);
    }

    /**
     * @Description 查询慢病模板记录
     * @Author hsh
     * @param param 查询条件
     * @return CrmVisitRecord 慢病模板记录
     * @Date 2023/12/9 9:55
     */
    public List<CrmVisitRecord> queryCrmEmrTree(CrmVisitRecord param) {
        List<CrmVisitRecord> result;
        QueryWrapper<CrmVisitRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", param.getPId());
        List<CrmVisitRecord> list;
        if (param.getType() == 2) {
            if (null != param.getVisitTimes()) {
                queryWrapper.eq("visit_times", param.getVisitTimes());
            }
            list = crmEmrDao.selectList(queryWrapper);
            return list;
        } else {
            String strTemplate = "第{}次慢病回访记录";
            queryWrapper.ne("visit_times", param.getVisitTimes());
            list = crmEmrDao.selectList(queryWrapper);
            result = getTree(list, strTemplate);
        }
        return result;
    }

    private List<CrmVisitRecord> getTree(List<CrmVisitRecord> list, String strTemplate) {
        if (CollUtil.isEmpty(list)) {
            return list;
        }
        List<CrmVisitRecord> result = new ArrayList<>();
        Map<Integer, List<CrmVisitRecord>> collect = list.stream().collect(Collectors.groupingBy(CrmVisitRecord::getVisitTimes));
        Integer index = 1;
        for (Integer key : collect.keySet()) {
            CrmVisitRecord tem = new CrmVisitRecord();
            tem.setId(index);
            tem.setName(StrUtil.format(strTemplate, key));
            tem.setChildren(collect.get(key));
            result.add(tem);
            index++;
        }
        return result;
    }

    /**
     * @Description 查询慢特病登记信息
     * @Author hsh
     * @param keyCode 关键字
     * @return CrmPatientMi
     * @Date 2023/12/9 9:47
     */
    public ResultVo<CrmPatientMi> queryCrmPatientInfoByCode(String keyCode) {
        AssertUtil.isnotBlank(keyCode, "关键字不能为空");

        //查询慢特病登记记录
        CrmPatientMi mi = cpmDao.selectCrmPatientMiByCode(keyCode);
        if (null == mi) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询病人慢特病登记记录, 请先登记或检查关键字是否正确!");
        }

        Integer times = crmEmrDao.selectCrmEmrPatientMaxById(mi.getPId());
        if (null != times && times > 0) {
            mi.setVisitTimes(times + 1);
        } else {
            mi.setVisitTimes(1);
        }

        // 获取登录人信息
        UserInfo user = userCache.getUserInfoByToken();
        mi.setUserIdCode(user.getCode());
        mi.setUserName(user.getName().trim());
        mi.setDeptCode(user.getDeptCode());
        mi.setDeptName(user.getDeptName());

        List<CodeName> sex = createdDao.getSexCode();
        Optional<CodeName> s = sex.stream().filter(codeName -> codeName.getCode().equals(mi.getSex())).findFirst();
        s.ifPresent(codeName -> mi.setSexValue(codeName.getName()));
        List<CodeName> way = dao.getAdmissWay();
        Optional<CodeName> w = way.stream().filter(codeName -> codeName.getCode().equals(mi.getPType())).findFirst();
        w.ifPresent(codeName -> mi.setPtName(codeName.getName()));
        List<CodeName> disease = dao.getCrmClass();
        callDiseaseTypeName(disease, mi);

        return ResultVoUtil.success(mi);
    }

    /**
     * @Description 保存慢特病电子模板信息
     * @Author hsh
     * @param param 保存信息
     * @return String
     * @Date 2023/12/9 9:42
     */
    public ResultVo<String> saveCrmEmrModel(CrmVisitRecord param) {
        AssertUtil.isnotBlank(param.getPId(), "用户ID不能为空");
        AssertUtil.isnotBlank(param.getVisitTimes(), "用户慢病回访次数不能为空");
        AssertUtil.isnotBlank(param.getEmrDocumentId(), "文档id不能为空");
        JSONObject saveJson = new JSONObject();
        saveJson.put("document", param.getDocumentData());
        try {
            emr.saveDocument(saveJson);
        } catch (Exception e) {
            return ResultVoUtil.fail(ExceptionEnum.EMR_SAVE, "病历保存错误，请重试！" + e.getMessage());
        }
        QueryWrapper<CrmVisitRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("emr_document_id", param.getEmrDocumentId());
        CrmVisitRecord crmRecord = crmEmrDao.selectOne(queryWrapper);
        if (crmRecord == null) {
            param.setVisitDate(new Date());
            crmEmrDao.insert(param);
        } else {
            param.setModifyId(param.getUserIdCode());
            param.setModifyDate(new Date());
            UpdateWrapper<CrmVisitRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("emr_document_id", param.getEmrDocumentId());
            crmEmrDao.update(param, updateWrapper);
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, "保存慢病电子病历成功!");
    }

    /**
     * @Description 根据code查询病人的基本信息
     * @Author hsh
     * @param code 关键字
     * @return CrmPatientMi等
     * @Date 2023/12/18 9:33
     */
    public ResultVo<Map<String, Object>> selectBrInfoByCode(String code) {
        CrmPatientMi mi;
        mi = cpmDao.selectCrmPatientMiMzByCode(code);
        CrmPatientMi mi1 = cpmDao.selectCrmPatientMiZyByCode(code);
        if (null != mi) {
            mi.setPType("1");
            if (null != mi1) {
                mi.setHisZyNo(mi1.getHisZyNo());
            }
        } else {
            if (null != mi1) {
                mi1.setPType("2");
                if (mi1.getAge() == null) {
                    if (mi1.getBirthDate() != null) {
                        mi1.setAge(String.valueOf(DateUtil.age(DateUtil.parse(mi1.getBirthDate(), "yyyy-MM-dd"), null)));
                    } else {
                        mi1.setAge(String.valueOf(DateUtil.age(IdcardUtil.getBirthDate(mi1.getSocialNo()), null)));
                    }
                }
                mi = mi1;
            }
        }

        if (null == mi) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有病人的基本信息");
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("mi", mi);
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 根据关键字查询慢病首次登记信息
     * @Author hsh
     * @param vo 查询条件
     * @return CrmPatientMi 慢病首次登记信息
     * @Date 2024/1/10 16:19
     */
    public ResultVo<List<CrmPatientMi>> selectChronicDisease(CrmPatientVo vo) {
        List<CrmPatientMi> miList = cpmDao.selectChronicDisease(vo);
        callCrmPatientMiFormat(miList);
        return ResultVoUtil.success(miList);
    }

    /**
     * @Description 格式化慢病首次登记信息
     * @Author hsh
     * @param miList 慢病首次登记信息
     * @Date 2024/1/10 16:20
     */
    private void callCrmPatientMiFormat(List<CrmPatientMi> miList) {
        if (null != miList && !miList.isEmpty()) {
            List<CodeName> sex = createdDao.getSexCode();
            List<CodeName> way = dao.getAdmissWay();
            List<CodeName> disease = dao.getCrmClass();
            // 省
            List<CodeName> pr = dao.getProvince();
            // 市
            List<CodeName> ct = dao.getCity("");
            // 区
            List<CodeName> ar = dao.getArea("");
            for (CrmPatientMi mi : miList) {
                Optional<CodeName> s = sex.stream().filter(codeName -> codeName.getCode().equals(mi.getSex())).findFirst();
                s.ifPresent(codeName -> mi.setSexValue(codeName.getName()));
                Optional<CodeName> w = way.stream().filter(codeName -> codeName.getCode().equals(mi.getPType())).findFirst();
                w.ifPresent(codeName -> mi.setPtName(codeName.getName()));
                Optional<CodeName> p = pr.stream().filter(codeName -> codeName.getCode().equals(mi.getProvinceCode())).findFirst();
                p.ifPresent(codeName -> mi.setProvinceName(codeName.getName()));
                Optional<CodeName> c = ct.stream().filter(codeName -> codeName.getCode().equals(mi.getCityCode())).findFirst();
                c.ifPresent(codeName -> mi.setCityName(codeName.getName()));
                Optional<CodeName> a = ar.stream().filter(codeName -> codeName.getCode().equals(mi.getAreaCode())).findFirst();
                a.ifPresent(codeName -> mi.setAreaName(codeName.getName()));
                callDiseaseTypeName(disease, mi);

                // 时间优化
                if (StringUtil.notBlank(mi.getLastDate())) {
                    mi.setLastDate(DateUtil.format(DateUtil.parseDate(mi.getLastDate()), "yyyy-MM-dd"));
                }
                if (StringUtil.notBlank(mi.getBirthDate())) {
                    mi.setBirthDate(DateUtil.format(DateUtil.parseDate(mi.getBirthDate()), "yyyy-MM-dd"));
                }
                if (StringUtil.notBlank(mi.getVisitDate())) {
                    mi.setVisitDate(DateUtil.format(DateUtil.parseDate(mi.getVisitDate()), "yyyy-MM-dd"));
                }
                // 血压拼接(格式：收缩压/舒张压)
                mi.setBloodPressure((mi.getBloodPressureHigh() == null ? "--" : mi.getBloodPressureHigh() + "")
                        + "/" + (mi.getBloodPressureLow() == null ? "--" : mi.getBloodPressureLow() + ""));
                // 计算距离下次随访时间天数
                if (StringUtil.notBlank(mi.getVisitDate())) {
                    // 判断两个日期相差的天数
                    /*
                     * 最后一个参数isReset: false 表示不包含时分秒的计算
                     * 比如：2016-02-01 23:59:59和2016-02-02 00:00:00相差一秒
                     * 如果isReset为{@code false}相差天数为0。
                     * 如果isReset为{@code true}相差天数将被计算为1
                     */
                    long days = DateUtil.betweenDay(DateUtil.parseDate(mi.getVisitDate()), new Date(), false);
                    if (DateUtil.date().before(DateUtil.parseDate(mi.getVisitDate()))) {
                        mi.setDays(days);
                    } else {
                        mi.setDays(-days);
                    }
                }

            }
        }

    }

    /**
     * 格式化慢病类型
     */
    private void callDiseaseTypeName(List<CodeName> disease, CrmPatientMi mi) {
        if (StringUtil.notBlank(mi.getChronicDiseaseType())) {
            String[] dType = mi.getChronicDiseaseType().split(",");
            for (String diseaseType : dType) {
                Optional<CodeName> c = disease.stream().filter(codeName -> codeName.getCode().equals(diseaseType)).findFirst();
                c.ifPresent(codeName -> mi.setChronicDiseaseName(codeName.getName()));
            }
        }
    }

    /**
     * @Description 查询慢病作废权限
     * @Author hsh
     * @return map
     * @Date 2024/3/28 10:18
     */
    public ResultVo<Map<String, Object>> selectMbDelPermissions() {
        UserInfo user = userCache.getUserInfoByToken();
        Map<String, Object> map = new HashMap<>();
        String f = cpmDao.selectMbDelPermissions();
        if (f.contains(user.getCode())) {
            map.put("qx", "0");
        } else {
            map.put("qx", "1");
        }
        return ResultVoUtil.success(map);
    }

    /**
     * @Description 根据id作废慢病登记信息
     * @Author hsh
     * @param pId 慢病登记id
     * @return map
     * @Date 2024/3/28 10:30
     */
    public ResultVo<Map<String, Object>> delChronicDiseaseById(String pId) {
        Map<String, Object> map = new HashMap<>();
        int f = cpmDao.delChronicDiseaseById(pId);
        if (f > 0) {
            map.put("cg", "慢病登记作废成功!");
        }
        return ResultVoUtil.success(map);
    }

    public ResultVo<Map<String, Object>> hfChronicDiseaseById(String pId) {
        Map<String, Object> map = new HashMap<>();
        int f = cpmDao.hfChronicDiseaseById(pId);
        if (f > 0) {
            map.put("cg", "慢病登记恢复成功!");
        }
        return ResultVoUtil.success(map);
    }

}
