package thyyxxk.webserver.service.medicaladvice.nursing;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.medicaladvice.common.DictDataDao;
import thyyxxk.webserver.dao.his.medicaladvice.nursing.NursingManagementDao;
import thyyxxk.webserver.dao.his.medicaladvice.nursing.YzHlMbDao;
import thyyxxk.webserver.dao.his.medicaladvice.nursing.YzTemperatureMapper;
import thyyxxk.webserver.dao.his.medicalinsurance.UpIdCollectionDao;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.YiZhuPublicDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.YzTemperature;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.inpatient.patient.Patient;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.GraphicsDataVO;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.GraphicsParam;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.PsInfoVO;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.ScdBaseInfo;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.ScdRow;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.YzHlMb;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.YzTemperatureGm;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.YzTemperatureSum;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.YzTemperatureVO;
import thyyxxk.webserver.service.hutoolcache.DeptCache;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.CommonUtil;
import thyyxxk.webserver.utils.EntityStringTrim;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Description:护理管理
 * @Author:lihong
 * @Date: 2023/4/21
 */
@Slf4j
@Service
public class NursingManagementService {
    private final NursingManagementDao dao;
    private final SqlSessionFactory sqlSessionFactory;
    private final YzTemperatureMapper yzTemperatureMapper;
    private final YzHlMbDao yzHlMbDao;
    private final YiZhuPublicDao yiZhuPublicDao;
    private final UpIdCollectionDao upIdCollectionDao;
    private final DictDataDao dictDataDao;
    private final UserCache userCache;
    private final DeptCache deptCache;

    private static  final String separator = "_";
    private static  final Map<String,String> recTimeMap = new HashMap<>();
    //替代 1901-01-01  这里 1901-01-01 08:00:00 转date 有5分钟误差 用以下先代替(兼容老系统)
    private static final String XIU_ZHEN_DATE = "1991-01-01";


    // 已屏蔽，保留以备后用
    // static {
    //     recTimeMap.put("3", "03:00");
    //     recTimeMap.put("7", "07:00");
    //     recTimeMap.put("11", "11:00");
    //     recTimeMap.put("15", "15:00");
    //     recTimeMap.put("19", "19:00");
    //     recTimeMap.put("23", "23:00");
    //
    //     recTimeMap.put("03:00", "3");
    //     recTimeMap.put("07:00", "7");
    //     recTimeMap.put("11:00", "11");
    //     recTimeMap.put("15:00", "15");
    //     recTimeMap.put("19:00", "19");
    //     recTimeMap.put("23:00", "23");
    // }

    static {
        // 新的映射关系（前端显示值 -> 后端时间）
        recTimeMap.put("2", "02:00");
        recTimeMap.put("6", "06:00");
        recTimeMap.put("10", "10:00");
        recTimeMap.put("14", "14:00");
        recTimeMap.put("18", "18:00");
        recTimeMap.put("22", "22:00");

        // 新的反向映射（后端时间 -> 前端显示值）
        recTimeMap.put("02:00", "2");
        recTimeMap.put("06:00", "6");
        recTimeMap.put("10:00", "10");
        recTimeMap.put("14:00", "14");
        recTimeMap.put("18:00", "18");
        recTimeMap.put("22:00", "22");

        // 兼容旧数据的映射（保持向后兼容）
        recTimeMap.put("3", "03:00");
        recTimeMap.put("7", "07:00");
        recTimeMap.put("11", "11:00");
        recTimeMap.put("15", "15:00");
        recTimeMap.put("19", "19:00");
        recTimeMap.put("23", "23:00");

        // 旧数据的反向映射
        recTimeMap.put("03:00", "3");
        recTimeMap.put("07:00", "7");
        recTimeMap.put("11:00", "11");
        recTimeMap.put("15:00", "15");
        recTimeMap.put("19:00", "19");
        recTimeMap.put("23:00", "23");
    }

    @Autowired
    public NursingManagementService(NursingManagementDao dao, SqlSessionFactory sqlSessionFactory, YzTemperatureMapper yzTemperatureMapper, YzHlMbDao yzHlMbDao, YiZhuPublicDao yiZhuPublicDao, UpIdCollectionDao upIdCollectionDao, DictDataDao dictDataDao, UserCache userCache, DeptCache deptCache) {
        this.dao = dao;
        this.sqlSessionFactory = sqlSessionFactory;
        this.yzTemperatureMapper = yzTemperatureMapper;
        this.yzHlMbDao = yzHlMbDao;
        this.yiZhuPublicDao = yiZhuPublicDao;
        this.upIdCollectionDao = upIdCollectionDao;
        this.dictDataDao = dictDataDao;
        this.userCache = userCache;
        this.deptCache = deptCache;
    }

    public void batchSaveData(List list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        NursingManagementDao mapper = sqlSession.getMapper(NursingManagementDao.class);
        try {
            for(Object t: list){
                if(t instanceof YzTemperatureVO){
                    YzTemperatureVO yzTemperatureVO = (YzTemperatureVO)t;
                    YzTemperature yzTemperature = new YzTemperature();
                    BeanUtil.copyProperties(yzTemperatureVO,yzTemperature);
                    yzTemperature.setDetailNo(null);
                    yzTemperatureMapper.insert(yzTemperature);
                }else if (t instanceof YzTemperatureSum){
                    mapper.insertYzTemperatureSum((YzTemperatureSum)t);
                }else if (t instanceof YzTemperatureGm){
                    mapper.insertYzTemperatureGm((YzTemperatureGm)t);
                }
            }
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }
    public List<Map<String,String>> getrecTimeSelect() {
        List<Map<String,String>> result = new ArrayList<>();
        List<String> select = dao.getrecTimeSelect();
        select.forEach(item -> {
            Map<String,String> codes = new HashMap<>(select.size());
            if(item.equals("全部")){
                codes.put("code","0");
                codes.put("name",item);
            }else {
                codes.put("code", item) ;
                codes.put("name", item) ;
            }
            result.add(codes);
        });
        return result;
    }

    /**
     * @description:查询三测单所有 列表数据  图表 总量
     * @author: lihong
     * @date: 2023/4/23 16:03
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String,Object> queryThreeTestList(YzTemperatureVO yzTemperature) {
        AssertUtil.isnotBlank(yzTemperature.getVisitIds(),"住院号不能为空");
        Map<String,Object> result = new HashMap<>(3);
        List<YzTemperatureVO> yzTemperatureVOS = getYzTemperatureVOS(yzTemperature);
        List<YzTemperatureSum> yzTemperatureSums = getYzTemperatureSums(yzTemperature);
        EntityStringTrim.beanAttributeValueTrimList(yzTemperatureSums);
        result.put("yzTemperatureVOS", yzTemperatureVOS);
        result.put("yzTemperatureSums", yzTemperatureSums);
        return result;
    }


    public List<String> queyGm(YzTemperatureVO yzTemperature){
        yzTemperature.setInpatientNo(StrUtil.isBlank(yzTemperature.getInpatientNo()) ? yzTemperature.getVisitIds().get(0).split(separator)[0]:yzTemperature.getInpatientNo());
        yzTemperature.setAdmissTimes(yzTemperature.getAdmissTimes()==null ? Convert.toInt(yzTemperature.getVisitIds().get(0).split(separator)[1]):yzTemperature.getAdmissTimes());
        if(CollUtil.isEmpty(yzTemperature.getVisitIds())){
            List<String> visitIds = new ArrayList<>();
            visitIds.add(yzTemperature.getInpatientNo()+separator+yzTemperature.getAdmissTimes());
            yzTemperature.setVisitIds(visitIds);
        }
        List<YzTemperatureGm> yzTemperatureGms = dao.listYzTemperatureGm(yzTemperature);
        if(CollUtil.isEmpty(yzTemperatureGms)){
            return  new ArrayList<>(1);
        }
        List<String> gmItems = yzTemperatureGms.stream().map(YzTemperatureGm::getGmxm).collect(Collectors.toList());
        return gmItems;
    }


    public ResultVo<String> saveGm(YzTemperatureVO yzTemperature){
        List<String> gmItems = yzTemperature.getGmItems();
        List<String> exist = queyGm(yzTemperature);
       if(CollUtil.isNotEmpty(gmItems)){
           List<String> collect = gmItems.stream().filter(item -> StrUtil.isNotBlank(item)).collect(Collectors.toList());
           if(CollUtil.isEmpty(collect)){
               throw new BizException(ExceptionEnum.LOGICAL_ERROR, "保存的过敏药物不能为空");
           }
           List<String> notExist = collect.stream().filter(item -> !exist.contains(item)).collect(Collectors.toList());
           if(CollUtil.isNotEmpty(notExist)){
               Date now = new Date();
               int i = 1;
               List<YzTemperatureGm> data = new ArrayList<>();
               for(String gm:notExist){
                   YzTemperatureGm yzTemperatureGm = new YzTemperatureGm();
                   yzTemperatureGm.setInpatientNo(yzTemperature.getVisitIds().get(0).split(separator)[0]);
                   yzTemperatureGm.setAdmissTimes(Convert.toInt(yzTemperature.getVisitIds().get(0).split(separator)[1]));
                   yzTemperatureGm.setGmxm(gm);
                   yzTemperatureGm.setOrderTime(now);
                   yzTemperatureGm.setPsTime(now);
                   yzTemperatureGm.setResultTime(now);
                   yzTemperatureGm.setActOrderNo(new BigDecimal(DateUtil.format(new Date(), "HHmmss")+i));
                   data.add(yzTemperatureGm);
                   ++i;
               }
               batchSaveData(data);
           }
       }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"保存过敏药物信息成功");
    }

    public List<YzTemperatureSum> getYzTemperatureSums(YzTemperatureVO yzTemperature) {
        List<YzTemperatureSum> result = new ArrayList<>();
        List<YzTemperatureSum> yzTemperatureSums = dao.listYzTemperatureSum(getQueryWrapper(yzTemperature, false), yzTemperature.getRecDateStr());

        for (Patient patient : yzTemperature.getPatientInfoList()) {
            boolean flag = yzTemperatureSums.stream().anyMatch(item -> patient.getInpatientNo().equals(item.getInpatientNo()));
            if(flag){
                List<YzTemperatureSum> collect = yzTemperatureSums.stream().filter(item -> patient.getInpatientNo().equals(item.getInpatientNo())).collect(Collectors.toList());
                result.add(collect.get(0));
            }else {
                YzTemperatureSum temp = new YzTemperatureSum();
                temp.setInpatientNo(patient.getInpatientNo());
                temp.setBedNo(patient.getBedNo());
                temp.setName(patient.getName());
                temp.setAdmissTimes(patient.getAdmissTimes());
                temp.setSex(patient.getSexName());
                temp.setRecDateStr(yzTemperature.getRecDateStr());
                temp.setRecDate(DateUtil.parseDate(yzTemperature.getRecDateStr()));
                result.add(temp);
            }
        }
        return result;
    }

    public List<YzTemperatureVO> getYzTemperatureVOS(YzTemperatureVO yzTemperature) {

        List<YzTemperatureVO> yzTemperatureVOS = dao.listYzTemperature(getQueryWrapper(yzTemperature, true),yzTemperature.getRecDateStr());
        if("0".equals(yzTemperature.getRecTimeStr())){
            yzTemperatureVOS.forEach(temp ->{
                formatTime(temp);
            });
            return yzTemperatureVOS;
        }
        List<YzTemperatureVO> result = new ArrayList<>();
        for (Patient patient : yzTemperature.getPatientInfoList()) {
            boolean flag = yzTemperatureVOS.stream().anyMatch(item -> patient.getInpatientNo().equals(item.getInpatientNo()));
            if(flag){
                List<YzTemperatureVO> collect = yzTemperatureVOS.stream().filter(item -> patient.getInpatientNo().equals(item.getInpatientNo())).collect(Collectors.toList());
                YzTemperatureVO temp = collect.get(0);
                formatTime(temp);
                temp.setRecDateStr(yzTemperature.getRecDateStr());
                result.add(temp);
            }else {
                YzTemperatureVO temp = new YzTemperatureVO();
                temp.setInpatientNo(patient.getInpatientNo());
                temp.setAdmissTimes(patient.getAdmissTimes());
                temp.setSex(patient.getSexName());
                temp.setBedNo(patient.getBedNo());
                temp.setName(patient.getName());
                temp.setTemperatureType("2");
                temp.setSpecialtextTimeStr(recTimeMap.get(yzTemperature.getRecTimeStr()));
                temp.setPainLvl("");
                temp.setRecDateStr(yzTemperature.getRecDateStr());
                temp.setToStringRecTime(recTimeMap.get(yzTemperature.getRecTimeStr()));
                temp.setWard(patient.getWard());
                //去查询是否有护理信息
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq( "inpatient_no",patient.getInpatientNo());
                queryWrapper.eq( "admiss_times",patient.getAdmissTimes());
                queryWrapper.ne("scd_flag","1");
                queryWrapper.eq("cast(DATEPART(hh,rec_time)as varchar)", yzTemperature.getRecTimeStr());
                queryWrapper.eq("convert(char(11),rec_date,121)",yzTemperature.getRecDateStr());
                queryWrapper.orderByAsc("detail_no");
                List<YzTemperature> tempList = yzTemperatureMapper.selectList(queryWrapper);
                if(CollUtil.isNotEmpty(tempList)){
                    temp.setHeart(tempList.get(0).getHeart());
                    temp.setPulse(tempList.get(0).getPulse1());
                    temp.setBreathe(tempList.get(0).getBreathe1());
                    temp.setTemperature(tempList.get(0).getTemperature1());
                }
                result.add(temp);
            }
        }
        return result;
    }

    public void formatTime(YzTemperatureVO temp) {
        if (temp.getRecTime() != null) {
            temp.setToStringRecTime(DateUtil.format(temp.getRecTime(), "HH:mm"));
        }
        if (temp.getSpecialtextTime() != null) {
            temp.setSpecialtextTimeStr(DateUtil.format(temp.getSpecialtextTime(), "HH:mm"));
        }
    }




    public QueryWrapper<?> getQueryWrapper(YzTemperatureVO yzTemperature,boolean type){
       QueryWrapper<?> qw = new QueryWrapper<>();
       qw.inSql("rtrim(b.inpatient_no) + '_' + cast(b.admiss_times as varchar)", CommonUtil.toInStringSql(yzTemperature.getVisitIds()));
       qw.eq(StrUtil.isNotBlank(yzTemperature.getRecDateStr()),"convert(char(11),b.rec_date,121)",yzTemperature.getRecDateStr());
       if(type){
           qw.eq(StrUtil.isNotBlank(yzTemperature.getRecTimeStr()) && !"0".equals(yzTemperature.getRecTimeStr()),"cast(DATEPART(hh,b.rec_time)as varchar)",yzTemperature.getRecTimeStr());
           qw.eq(StrUtil.isNotBlank(yzTemperature.getRecTimeStr()),"b.temperature_type",yzTemperature.getTemperatureType());
       }
       return qw;
   }
    /**
     * @description;查询皮试信息
     * @author: lihong
     * @date: 2023/4/24 8:51
     * @param: psInfoVO
     * @return: java.util.List<thyyxxk.webserver.entity.medicaladvice.medicamanage.PsInfoVO>
     **/
   public List<PsInfoVO> queryPsInfo(PsInfoVO psInfoVO){
       String psOperCondition = "";
        if(psInfoVO.getConfirmFlag() == 0){
            psOperCondition = "isnull(ps_oper,'') ='' ";
        }else {
            psOperCondition = " isnull(ps_oper,'') <>''";
        }
       List<PsInfoVO> psInfoVOS = dao.listPsInfo(psInfoVO.getStartBedNo(), psInfoVO.getEndBedNo(),psInfoVO.getCurWard(), psOperCondition);
       if(CollUtil.isNotEmpty(psInfoVOS)){
           psInfoVOS.forEach(item->{
               if(StrUtil.isBlank(item.getPsOper())){
                   UserInfo userInfo = userCache.getUserInfoByToken();
                   item.setPsOper(userInfo.getCode());
                   item.setPsOperName(userInfo.getName());
               }
           });
       }
        return psInfoVOS;
   }

    public ResultVo<String> updatePsInfo(List<PsInfoVO> psInfos) {
        if(CollUtil.isNotEmpty(psInfos)){
            List<PsInfoVO> collect = psInfos.stream().filter(obj -> !(StrUtil.isBlank(obj.getPsStatus())  && obj.getPsResultTime() == null)).collect(Collectors.toList());
            for (PsInfoVO item : collect) {
                if ( item.getPsResultTime() == null || StrUtil.isBlank(item.getPsStatus())) {
                    throw new BizException(ExceptionEnum.LOGICAL_ERROR, "医嘱号:" + item.getActOrderNo().longValue() + "皮试结果,皮试结果时间有一个不为空,其他必填");
                }
                if (item.getPsResultTime().before(item.getOrderTime())){
                    throw new BizException(ExceptionEnum.LOGICAL_ERROR,"医嘱号:"+item.getActOrderNo().longValue()+"皮试结果时间不能小于医嘱时间");
                }
            }
            dao.updatePsInfo(collect);
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"皮试信息保存成功");
    }

    public List<Map<String,Object>> selectEmpInfo(String keyWard){
       AssertUtil.isnotBlank(keyWard,"请输入查询的内容");
        QueryWrapper<?> query = new QueryWrapper<>();
        query.likeRight("py_code",keyWard);
        query.or();
        query.like("name", keyWard);
        List<Map<String, Object>> emp = dao.selectEmpInfo(query);
        return emp;
    }

    public ResultVo<String> saveThreeTest(YzTemperatureVO saveData) {
       if(CollUtil.isNotEmpty(saveData.getYzTemperatureVOS())){
//           checkTwMbRange(saveData);
           List<YzTemperatureVO> yzTemperatureVOS = dealYzTemperatureVOS(saveData);
           log.info("yzTemperatureVOS", JSON.toJSONString(yzTemperatureVOS));
           List<YzTemperatureVO> exist = yzTemperatureVOS.stream().filter(item -> item.getDetailNo() != null).collect(Collectors.toList());
           if(CollUtil.isNotEmpty(exist)){
               yzTemperatureMapper.deleteBatchIds(exist.stream().map(item -> item.getDetailNo()).collect(Collectors.toList()));
           }
           batchSaveData(yzTemperatureVOS);
       }
       if(CollUtil.isNotEmpty(saveData.getYzTemperatureSums())){
           List<YzTemperatureSum> yzTemperatureSums = dealYzTemperatureSums(saveData);
           log.info("yzTemperatureSums", JSON.toJSONString(yzTemperatureSums));
           List<String> uuid = yzTemperatureSums.stream().map(item -> {
               return getStringUuid(item);
           }).collect(Collectors.toList());
           List<String> uuids = dao.existYzTemperatureSum(CommonUtil.toInStringSql(uuid));
           List<YzTemperatureSum> exist = yzTemperatureSums.stream().filter(item -> uuids.contains(getStringUuid(item))).collect(Collectors.toList());
           if(CollUtil.isNotEmpty(exist)){
               exist.forEach(item->{
                   dao.deleteYzTemperatureSum(item);
               });
           }
           batchSaveData(yzTemperatureSums);
       }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"保存成功");
    }

    private void checkTwMbRange(YzTemperatureVO data){
       if(CollUtil.isNotEmpty(data.getYzTemperatureVOS())){
           String twRange = dictDataDao.getDictValueByDictName("2.2", "tw_range");
           String mbRange = dictDataDao.getDictValueByDictName("2.3", "mb_range");
           int index = 1;
           for(YzTemperatureVO item : data.getYzTemperatureVOS()){
               if(item.getTemperature() ==null || Convert.toBigDecimal(twRange.split(",")[0]).compareTo(item.getTemperature()) > 0 || Convert.toBigDecimal(twRange.split(",")[1]).compareTo(item.getTemperature()) < 0){
                   throw new BizException(ExceptionEnum.LOGICAL_ERROR, StrUtil.format("第{}条体温要在{}至{}范围内",index, twRange.split(",")[0], twRange.split(",")[1]));
               }
               if(item.getPulse() ==null || Convert.toBigDecimal(mbRange.split(",")[0]).compareTo(item.getPulse()) > 0 || Convert.toBigDecimal(mbRange.split(",")[1]).compareTo(item.getPulse()) < 0){
                   throw new BizException(ExceptionEnum.LOGICAL_ERROR, StrUtil.format("第{}条脉搏要在{}至{}范围内",index, mbRange.split(",")[0], mbRange.split(",")[1]));
               }
               ++index;
           }
       }
    }


    public List<YzTemperatureSum> dealYzTemperatureSums(YzTemperatureVO saveData) {
        List<YzTemperatureSum> yzTemperatureSums = saveData.getYzTemperatureSums();
        Date now = new Date();
        String code = userCache.getUserInfoByToken().getCode();
        for(YzTemperatureSum item : yzTemperatureSums){
            if(StrUtil.isBlank(item.getUserid())){
                item.setUserid(code);
            }
            if(item.getInputTime() == null){
                item.setInputTime(now);
            }
            item.setModifyUserid(code);
            item.setModifyTime(now);
        }
        return yzTemperatureSums;
    }

    @NotNull
    public String getStringUuid(YzTemperatureSum item) {
        return item.getInpatientNo() + separator + item.getAdmissTimes() + separator + item.getRecDateStr();
    }

    public List<YzTemperatureVO> dealYzTemperatureVOS(YzTemperatureVO saveData) {
        List<YzTemperatureVO> yzTemperatureVOS = saveData.getYzTemperatureVOS();
        Date now = new Date();
        yzTemperatureVOS.forEach(item -> {
            if(item.getRecTime() == null){
                item.setRecTime(DateUtil.parseDateTime("1900-01-01 "+item.getToStringRecTime() + ":00"));
            }
            if(StrUtil.isNotBlank(item.getSpecialtextTimeStr())){
                item.setSpecialtextTime(DateUtil.parseDateTime("1900-01-01 "+item.getSpecialtextTimeStr() + ":00"));
            }
            if(StrUtil.isBlank(item.getRecTimeStr())){
                item.setRecTimeStr(recTimeMap.get(item.getToStringRecTime()));
            }
            if(item.getUserid() == null){
                item.setUserid(userCache.getUserInfoByToken().getCode());
            }
            item.setModifyUserid(userCache.getUserInfoByToken().getCode());
            item.setModifyTime(now);
            if(item.getInputTime() == null){
                item.setInputTime(now);
            }
            if(item.getScdFlag() == null){
                item.setScdFlag(1);
            }
            if(item.getRecDate() == null){
                item.setRecDate(DateUtil.parseDate(item.getRecDateStr()));
            }
        });
        return yzTemperatureVOS;
    }

    @NotNull
    public String getUuid(YzTemperatureVO item) {
        return item.getInpatientNo() + separator + item.getAdmissTimes().toString() + separator + recTimeMap.get(item.getToStringRecTime());
    }

    public ResultVo<String> deleteYzTemperature(YzTemperatureVO data) {
       if( data.getDetailNo() != null){
           if(data.getScdFlag() ==1 ){
               dao.deleteYzTemperature(data.getDetailNo());
           }else {
               List<Integer> detailNo = yzTemperatureMapper.exists(data);
               batchDel(detailNo);
           }
       }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"删除成功");
    }

    public ResultVo<String> deleteYzTemperatureSum(YzTemperatureSum data) {
       dao.deleteYzTemperatureSum(data);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"删除成功");
    }
    /**
     * @description:查询护理记录单
     * @author: lihong
     * @date: 2023/4/27 16:56
     * @return: java.util.List<thyyxxk.webserver.entity.datamodify.YzTemperature>
     **/
   public IPage<YzTemperature> queryNursingRecord(YzTemperatureVO yzTemperature){
       IPage<YzTemperature> page = new Page();
       StringBuilder condition = new StringBuilder();
       condition.append("1=1");
       if("1".equals(yzTemperature.getTypeFlag())){
           if(yzTemperature.getStartRecTime() != null){
               condition.append(StrUtil.format(" and convert(char(11),rec_date,121)+CONVERT(char(8), rec_time, 108) >='{}' ", DateUtil.formatDateTime(yzTemperature.getStartRecTime())));
           }
           if(yzTemperature.getEndRecTime() != null){
               condition.append(StrUtil.format(" and convert(char(11),rec_date,121)+CONVERT(char(8), rec_time, 108) <='{}' ", DateUtil.formatDateTime(yzTemperature.getEndRecTime())));
           }
       }
       if(StrUtil.isNotBlank(yzTemperature.getWard())){
           condition.append(StrUtil.format(" and ward = '{}'",yzTemperature.getWard()));
       }
       yzTemperature.setDateTimeCondition(condition.toString());
       List<YzTemperature> yzTemperatures = yzTemperatureMapper.listYzTemperature(yzTemperature);
       CommonUtil.BeanTrim(yzTemperatures);
       if(CollUtil.isNotEmpty(yzTemperatures)){
           Map<String, List<YzTemperature>> groupMap = yzTemperatures.stream().collect(Collectors.groupingBy(item -> {
               return item.getInpatientNo() + item.getAdmissTimes() + DateUtil.format(item.getRecDate(), "yyyy-MM-dd") + item.getToStringRecTime();
           }));
           List<YzTemperature> temp = new ArrayList<>();
           for (String key : groupMap.keySet()) {
               YzTemperature yzTemperature1 = groupMap.get(key).get(0);
               List<String> otherInfos = groupMap.get(key).stream().map(item -> item.getOtherInfo()).collect(Collectors.toList());
               String join = CollUtil.join(otherInfos, "");
               yzTemperature1.setOtherInfo(join);
               yzTemperature1.setRecTime(DateUtil.parseDateTime(XIU_ZHEN_DATE+" "+yzTemperature1.getToStringRecTime()));
               yzTemperature1.setToStringRecDate(DateUtil.format(yzTemperature1.getRecDate(),"yyyy-MM-dd"));
               yzTemperature1.setRecDateStr(DateUtil.format(yzTemperature1.getRecDate(),"MM-dd"));
               yzTemperature1.setRecTimeStr(yzTemperature1.getToStringRecTime().substring(0,5));
               yzTemperature1.setPressureAmPm(yzTemperature1.getPressure1AmAndPm());
               yzTemperature1.setUseridName(userCache.getEmployeeName(yzTemperature1.getUserid()));
               temp.add(yzTemperature1);
           }
           List<YzTemperature> collect = temp.stream().sorted(Comparator.comparing(item ->DateUtil.parseDateTime(DateUtil.formatDate(item.getRecDate()) + " "+ item.getToStringRecTime()))).collect(Collectors.toList());
           if(yzTemperature.getPrintFlag() !=null && yzTemperature.getPrintFlag()){
               List<YzTemperature> result = new ArrayList<>();
               int subLength= getSubLength(yzTemperature.getHldType());
               for (YzTemperature item : collect) {
                   if (item.getOtherInfo() != null && calcuLength(item.getOtherInfo()) > subLength) {
                       List<String> infos = subStringBytes(item.getOtherInfo(), subLength);
                       item.setOtherInfo(infos.get(0));
                       result.add(item);
                       for (int i = 1; i < infos.size(); i++) {
                           YzTemperature tempTemperature = new YzTemperature();
                           tempTemperature.setOtherInfo(infos.get(i));
                           result.add(tempTemperature);
                       }
                   } else {
                       result.add(item);
                   }
               }
               page.setRecords(result);
               return page;
           }
           page.setTotal(collect.size());
           List<YzTemperature> pageDate = collect.stream().skip((yzTemperature.getCurrentPage() - 1) * yzTemperature.getPageSize()).limit(yzTemperature.getPageSize()).collect(Collectors.toList());
           page.setRecords(pageDate);
           return page;
       }
       page.setRecords(new ArrayList<>());
        return page;
   }
    /**
     * @description:获取分段
     * @author: lihong
     * @date: 2023/9/1 9:14
     * @param: hldType
     * @return: int
     **/
    private int getSubLength(String hldType) {
        String hldTypeLen = upIdCollectionDao.getDictValueByDictName("1.7", "hld_type_len");
        String[] resultArr;
        try {
            if(StrUtil.isNotBlank(hldTypeLen)){
                resultArr = hldTypeLen.split(",");
            }else {
                resultArr = new String[]{"36","32","36","36","36","30"};
            }
            for (int i = 0; i <resultArr.length ; i++) {
                if (Convert.toInt(hldType) == (i + 1)) {
                    return Convert.toInt(resultArr[i]);
                }
            }
        }catch (Exception e){
            log.error("[getSubLength]报错:",e);
            return 36;
        }
        return 36;
    }

    /**
     * @description:获取医嘱 转科 出院 下拉框
     * @author: lihong
     * @date: 2023/4/28 11:05
     * @param: patient
     * @return: java.lang.Object
     **/
    public List<Map<String,Object>> getOrderTime(Patient patient) {
      return  dao.listOrderTime(patient.getInpatientNo(),patient.getAdmissTimes());
    }

    private void checkHlTwMb(BigDecimal pulse1,BigDecimal temperature1){
        String twRange = dictDataDao.getDictValueByDictName("2.2", "tw_range");
        String mbRange = dictDataDao.getDictValueByDictName("2.3", "mb_range");
        if(temperature1 == null || Convert.toBigDecimal(twRange.split(",")[0]).compareTo(temperature1) > 0 || Convert.toBigDecimal(twRange.split(",")[1]).compareTo(temperature1) < 0){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, StrUtil.format("体温要在{}至{}范围内",twRange.split(",")[0],twRange.split(",")[1]));
        }
        if(pulse1 == null || Convert.toBigDecimal(mbRange.split(",")[0]).compareTo(pulse1) > 0 || Convert.toBigDecimal(mbRange.split(",")[1]).compareTo(pulse1) < 0){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, StrUtil.format("脉搏要在{}至{}范围内",mbRange.split(",")[0],mbRange.split(",")[1]));
        }
    }

    public ResultVo<String> saveYzTemperature(YzTemperatureVO query) {
        AssertUtil.isnotBlank(query.getRecTime(),"时间不能为空!");
        if(!"死亡".equals(query.getScdSpecialtext())){
//            checkHlTwMb(query.getPulse1(), query.getTemperature1());
        }

        //先查询是否存在
        query.setRecTimeStr(DateUtil.format(query.getRecTime(),"HH:mm:ss"));
        query.setToStringRecTime(query.getRecTimeStr());
        //query.setRecTime(DateUtil.parseDateTime(XIU_ZHEN_DATE +" "+query.getRecTimeStr()));
        query.setRecDate(DateUtil.parseDate(query.getToStringRecDate()));
        query.setScdFlag(0);
        String code = userCache.getUserInfoByToken().getCode();
        Date now = new Date();
        List<Integer> detailNo = yzTemperatureMapper.exists(query);
        if(CollUtil.isNotEmpty(detailNo)) {
            batchDel(detailNo);
        }else {
            query.setUserid(code);
            query.setInputTime(now);
        }
        query.setModifyUserid(code);
        query.setModifyTime(now);
        YzTemperature yzTemperature = new YzTemperature();
        BeanUtil.copyProperties(query,yzTemperature);
        //兼容老系统 将措施 字符大于36个分成几条
        if(StrUtil.isNotBlank(yzTemperature.getOtherInfo()) && calcuLength(yzTemperature.getOtherInfo()) >36){
            List<String> strList = subStringBytes(yzTemperature.getOtherInfo(),36);
            for (int i = 0; i < strList.size(); i++) {
                YzTemperature temp = new YzTemperature();
                if(i == 0){
                    BeanUtil.copyProperties(yzTemperature,temp);
                }else {
                    temp.setUserid(yzTemperature.getUserid());
                    temp.setInputTime(yzTemperature.getInputTime());
                    temp.setInpatientNo(yzTemperature.getInpatientNo());
                    temp.setAdmissTimes(yzTemperature.getAdmissTimes());
                    temp.setWard( userCache.get(code).getDeptCode());
                    temp.setRecDate(yzTemperature.getRecDate());
                    temp.setRecTime(yzTemperature.getRecTime());
                }
                temp.setScdFlag(0);
                temp.setOtherInfo(strList.get(i));
                yzTemperatureMapper.insert(temp);
            }
        }else {
            yzTemperatureMapper.insert(yzTemperature);
        }
        //修正时间 1900-01-01 08:00:00 转date 有五分钟误差 修改下
        yzTemperatureMapper.updateRecTime(query,StrUtil.format("1900-01-01 {}",query.getToStringRecTime()));
        //保存过敏信息
        saveGm(query);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"保存成功");
    }

    public void batchDel(List<Integer> detailNo){
        if(CollUtil.isNotEmpty(detailNo)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("detail_no", detailNo);
            yzTemperatureMapper.delete(queryWrapper);
        }
    }


    private  List<String> usingSubstringMethod(String text, int n) {
        List<String> results = new ArrayList<>();
        int length = text.length();
        for (int i = 0; i < length; i += n) {
            results.add(text.substring(i, Math.min(length, i + n)));
        }
        return results;
    }

    private int  calcuLength(String text){
        int sum = 0;
        for (int i = 0; i < text.length(); i++){
            int tempLen = String.valueOf(text.charAt(i)).getBytes().length;
            int temp = tempLen == 3 ? 2 : tempLen;
            sum += temp;
        }
        return sum;
    }

    private List<String> subStringBytes(String text,int bytesLen){
        List<String> results = new ArrayList<>();
        int length = text.length();
        int len = 0;
        String str = "" ;
        for (int i = 0; i < length; i++) {
            int tempLen = String.valueOf(text.charAt(i)).getBytes().length;
            int temp = tempLen == 3 ? 2 : tempLen;
            String tempStr = text.charAt(i) + "";
            if(len >= bytesLen){
                results.add(str);
                len = temp;
                str = tempStr;
            }else {
                len += temp;
                str += tempStr;
            }
            if(i == length-1){
                results.add(str);
            }
        }
        return results;
    }

    /**
     * 自定义数字转中文方法，确保转换准确性
     * @param number 数字
     * @return 中文数字
     */
    private String numberToChinese(int number) {
        if (number == 0) return "零";
        if (number == 1) return "一";
        if (number == 2) return "二";
        if (number == 3) return "三";
        if (number == 4) return "四";
        if (number == 5) return "五";
        if (number == 6) return "六";
        if (number == 7) return "七";
        if (number == 8) return "八";
        if (number == 9) return "九";
        if (number == 10) return "十";
        if (number == 11) return "十一";
        if (number == 12) return "十二";
        if (number == 13) return "十三";
        if (number == 14) return "十四";
        if (number == 15) return "十五";
        if (number == 16) return "十六";
        if (number == 17) return "十七";
        if (number == 18) return "十八";
        if (number == 19) return "十九";
        if (number == 20) return "二十";
        if (number == 21) return "二十一";
        if (number == 22) return "二十二";
        if (number == 23) return "二十三";
        if (number == 24) return "二十四";
        if (number == 25) return "二十五";
        if (number == 26) return "二十六";
        if (number == 27) return "二十七";
        if (number == 28) return "二十八";
        if (number == 29) return "二十九";
        if (number == 30) return "三十";
        if (number == 31) return "三十一";
        if (number == 32) return "三十二";
        if (number == 33) return "三十三";
        if (number == 34) return "三十四";
        if (number == 35) return "三十五";
        if (number == 36) return "三十六";
        if (number == 37) return "三十七";
        if (number == 38) return "三十八";
        if (number == 39) return "三十九";
        if (number == 40) return "四十";
        if (number == 41) return "四十一";
        if (number == 42) return "四十二";
        if (number == 43) return "四十三";
        if (number == 44) return "四十四";
        if (number == 45) return "四十五";
        if (number == 46) return "四十六";
        if (number == 47) return "四十七";
        if (number == 48) return "四十八";
        if (number == 49) return "四十九";
        if (number == 50) return "五十";
        if (number == 51) return "五十一";
        if (number == 52) return "五十二";
        if (number == 53) return "五十三";
        if (number == 54) return "五十四";
        if (number == 55) return "五十五";
        if (number == 56) return "五十六";
        if (number == 57) return "五十七";
        if (number == 58) return "五十八";
        if (number == 59) return "五十九";
        
        // 对于其他数字，使用通用的转换逻辑
        if (number < 10) {
            return numberToChinese(number);
        } else if (number < 20) {
            return "十" + (number == 10 ? "" : numberToChinese(number - 10));
        } else if (number < 60) {
            int tens = number / 10;
            int ones = number % 10;
            String tensStr = "";
            switch (tens) {
                case 2: tensStr = "二十"; break;
                case 3: tensStr = "三十"; break;
                case 4: tensStr = "四十"; break;
                case 5: tensStr = "五十"; break;
            }
            return tensStr + (ones == 0 ? "" : numberToChinese(ones));
        }
        
        return String.valueOf(number);
    }


    public ResultVo<YzTemperature> queryScdYzTemperature(YzTemperatureVO query) {
        AssertUtil.isnotBlank(query.getRecTime(),"时间不能为空!");
        QueryWrapper queryWrapper = getQueryWrapper(query);
        queryWrapper.eq("scd_flag",1);
        List<YzTemperature> list = yzTemperatureMapper.selectList(queryWrapper);
        YzTemperatureSum sum = dao.queryPressureAmAndPm(query.getInpatientNo(),query.getAdmissTimes(),query.getToStringRecDate());
        YzTemperature yzTemperature = new YzTemperature();
         if(CollUtil.isNotEmpty(list)){
             yzTemperature.setTemperature1(list.get(0).getTemperature());
             yzTemperature.setBreathe1(list.get(0).getBreathe());
             yzTemperature.setPulse1(list.get(0).getPulse());
             yzTemperature.setHeart(list.get(0).getHeart());
         }
         if(sum != null && StringUtil.notBlank(sum.getPressureAm())){
             yzTemperature.setPressure1Am(Convert.convert(BigDecimal.class,sum.getPressureAm().split("/")[0],null));
             yzTemperature.setPressure1Pm(Convert.convert(BigDecimal.class,sum.getPressureAm().split("/")[1],null));
         }
        return ResultVoUtil.success(yzTemperature);
    }

    @NotNull
    public QueryWrapper getQueryWrapper(YzTemperatureVO query) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("inpatient_no",query.getInpatientNo());
        queryWrapper.eq("admiss_times", query.getAdmissTimes());
        queryWrapper.eq("convert(char(11),rec_date,121)", query.getToStringRecDate());
        queryWrapper.eq("CONVERT(char(5), rec_time, 8)", DateUtil.format(query.getRecTime(),"HH:mm"));
        return queryWrapper;
    }

    public ResultVo<YzTemperature> calInputOutSum(YzTemperatureVO query) {
        //计算往前24小时之内
        AssertUtil.isnotBlank(query.getRecTime(),"时段不能为空");
        YzTemperature sum ;
        String nowDateTimeStr = query.getToStringRecDate()+" "+DateUtil.format(query.getRecTime(),"HH:mm")+":00";
        String dateTimeCondition ;
        if(query.getRecTime().getHours() <= 7){
            DateTime beforDateTime = DateUtil.offsetDay(DateUtil.parseDateTime(nowDateTimeStr), -1);
            dateTimeCondition =  StrUtil.format("  ( rec_date = '{} 00:00:00' AND rec_time > '1900-01-01 07:00:00' ) OR ( rec_date = '{} 00:00:00' AND rec_time <= '1900-01-01 07:00:00' )   ",DateUtil.formatDate(beforDateTime), query.getToStringRecDate());
        }else {
            dateTimeCondition =  StrUtil.format("   ( rec_date ='{} 00:00:00' and rec_time > '1900-01-01 07:00:00' ) and ( rec_date ='{} 00:00:00' and rec_time <= '1900-01-01 {}:00' )   ",query.getToStringRecDate(), query.getToStringRecDate(),DateUtil.format(query.getRecTime(),"HH:mm"));
        }
        query.setDateTimeCondition(dateTimeCondition);
        if(query.getInputOutSum() == 1){
          sum = yzTemperatureMapper.queryInputSum(query);
        }
        else {
            sum = yzTemperatureMapper.queryOutSum(query);
        }
        return ResultVoUtil.success(sum);
    }


    public ResultVo<List<YzHlMb>> queryyzHlMb(YzHlMb query) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ne("a.hl_name","");
        queryWrapper.eq(StrUtil.isNotBlank(query.getDeptCode()),"a.dept_code",query.getDeptCode());
        queryWrapper.eq(query.getHlNo() != null,"a.hl_no",query.getHlNo());
        List<YzHlMb> list = yzHlMbDao.listHlmb(queryWrapper);
       return ResultVoUtil.success(list);
    }

    public ResultVo<String> saveHlMb(YzHlMb query) {
        AssertUtil.isnotBlank(query.getHlName(),"模板名称不能为空");
        AssertUtil.isnotBlank(query.getHlText(),"模板内容不能为空");
        query.setOpId(userCache.getUserInfoByToken().getCode());
        yzHlMbDao.insert(query);
       return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"保存模板成功");
    }


    public ResultVo<String> delHlMb(List<YzHlMb> param) {
        List<Integer> ids = param.stream().map(item -> item.getHlNo()).collect(Collectors.toList());
        yzHlMbDao.deleteBatchIds(ids);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"删除模板成功");
    }

    public ResultVo<GraphicsDataVO> getChartData(GraphicsParam query) {
        QueryWrapper<YzTemperature> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inpatient_no",query.getInpatientNo());
        queryWrapper.eq("admiss_times", query.getAdmissTimes());
        queryWrapper.eq("scd_flag", 1);
        queryWrapper.ge("rec_date",query.getStartRecTime());
        queryWrapper.le("rec_date",query.getEndRecTime());
        queryWrapper.orderByAsc("rec_date, rec_time");
        List<YzTemperature> yzTemperatures = yzTemperatureMapper.selectList(queryWrapper);
        List<YzTemperatureSum> yzTemperatureSums = dao.selectYzTemperatureSum(query);
        CommonUtil.BeanTrim(yzTemperatures);
        CommonUtil.BeanTrim(yzTemperatureSums);
        YzTemperatureVO yzTemperatureVO = new YzTemperatureVO();
        yzTemperatureVO.setInpatientNo(query.getInpatientNo());
        yzTemperatureVO.setAdmissTimes(query.getAdmissTimes());
        List<YzTemperatureGm> yzTemperatureGms = dao.listYzTemperatureGm(yzTemperatureVO);
        CommonUtil.BeanTrim(yzTemperatureGms);
        GraphicsDataVO graphicsDataVO =createGraphicsDataVO(yzTemperatures,yzTemperatureSums,yzTemperatureGms,query);
        return ResultVoUtil.success(graphicsDataVO);
    }

    public GraphicsDataVO createGraphicsDataVO(List<YzTemperature> yzTemperatures, List<YzTemperatureSum> yzTemperatureSums, List<YzTemperatureGm> yzTemperatureGms, GraphicsParam query) {
        GraphicsDataVO graphicsDataVO = new GraphicsDataVO();
        List<String> operDays = getOperDays(query);
        graphicsDataVO.setOperaDays(operDays);
        List<String> dateList = createDateList(query);
        // 已屏蔽，保留以备后用
        // String[]  timeList = {"03:00:00", "07:00:00", "11:00:00", "15:00:00", "19:00:00", "23:00:00"};
        String[]  timeList = {"02:00:00", "06:00:00", "10:00:00", "14:00:00", "18:00:00", "22:00:00"};
        List<ScdRow> rows = getRows(query,yzTemperatures, dateList, timeList);
        graphicsDataVO.setRows(rows);
        List<ScdBaseInfo> types = new ArrayList<>();
        //呼吸和疼痛
        setBreatheAndPain(query,types,yzTemperatures,dateList,timeList);
        //其他
        setOtherTypes(query,types,yzTemperatureGms,yzTemperatureSums,dateList);
        graphicsDataVO.setTypes(types);
        return graphicsDataVO;
    }

    private void setOtherTypes(GraphicsParam query,List<ScdBaseInfo> types, List<YzTemperatureGm> yzTemperatureGms, List<YzTemperatureSum> yzTemperatureSums,List<String> dateList) {
        //过敏药物 010 过敏药物
        setGmYw(types, yzTemperatureGms, dateList);
        //005 大便
        //004 小便
        //008 血压
        //030 身高
        //009 体重
        //006 入量
        //011 出量
        String[] typeCodes = {"005","004","008","030","009","006","011"};
        String[] fieldNames = {"shitOther","urineQuanInfo","pressureAm","bodyLength","bodyWeightInfo","intake","outputOther"};
        for (int i = 0; i < typeCodes.length; i++) {
            setPublicOtherTypes(query,types,yzTemperatureSums,dateList,typeCodes[i],fieldNames[i]);
        }
    }

    private void setPublicOtherTypes(GraphicsParam query,List<ScdBaseInfo> types, List<YzTemperatureSum> yzTemperatureSums, List<String> dateList, String typeCode, String fieldName) {
        //005 大便
        //004 小便
        //008 血压
        //030 身高
        //009 体重
        //006 入量
        //011 出量
        for (String itemDate : dateList) {
             YzTemperatureSum yzTemperatureSum = yzTemperatureSums.stream().filter(equalsDate(itemDate)).findFirst().orElse(new YzTemperatureSum());
            ScdBaseInfo scdBaseInfo = new ScdBaseInfo();
            scdBaseInfo.setDate(itemDate);
            scdBaseInfo.setTypeCode(typeCode);
            //是需要的话 拼接
            if ("008".equals(typeCode)) {
                if(query.getXyFlag()){
                    String pressure = "";
                    pressure = yzTemperatureSum.getPressureAm() == null ? "" : yzTemperatureSum.getPressureAm();
                    if(StrUtil.isNotBlank(yzTemperatureSum.getPressurePm())){
                        if(StrUtil.isNotBlank(yzTemperatureSum.getPressureAm())){
                            pressure += ";";
                        }
                        pressure += yzTemperatureSum.getPressurePm();
                    }
                        scdBaseInfo.setTypeValue(pressure);
                }
            }
            else if("004".equals(typeCode)) {
                scdBaseInfo.setTypeValue(Convert.toStr(yzTemperatureSum.getUrineInfo(),"")+Convert.toStr(yzTemperatureSum.getUrineQuanInfo(),""));
            }
            else if("006".equals(typeCode)) {
                scdBaseInfo.setTypeValue(Convert.toStr(yzTemperatureSum.getIntakeInfo(),"")+Convert.toStr(yzTemperatureSum.getIntake(),""));
            }
            else if("011".equals(typeCode)) {
                scdBaseInfo.setTypeValue(Convert.toStr(yzTemperatureSum.getOutputInfo(),"")+Convert.toStr(yzTemperatureSum.getOutputOther(),""));
            }
            else if("009".equals(typeCode)) {
                if(StrUtil.isNotBlank(yzTemperatureSum.getBodyWeightInfo())){
                    scdBaseInfo.setTypeValue(yzTemperatureSum.getBodyWeightInfo());
                }else {
                    scdBaseInfo.setTypeValue(Convert.toStr(yzTemperatureSum.getBodyWeight(),null));
                }
            }
            else {
                scdBaseInfo.setTypeValue(Convert.toStr(ReflectUtil.getFieldValue(yzTemperatureSum, fieldName), null));
            }
            types.add(scdBaseInfo);
        }
    }

    @NotNull
    private Predicate<YzTemperatureSum> equalsDate(String itemDate) {
        return o -> itemDate.equals(DateUtil.formatDate(o.getRecDate()));
    }

    private void setGmYw(List<ScdBaseInfo> types, List<YzTemperatureGm> yzTemperatureGms, List<String> dateList) {
        List<String> gmyws = new ArrayList<>();
        if(CollUtil.isNotEmpty(yzTemperatureGms)){
            gmyws = yzTemperatureGms.stream().map(o -> o.getGmxm()).collect(Collectors.toList());
        }
        for (int i = 0; i < dateList.size() ; i++) {
            ScdBaseInfo scdBaseInfo = new ScdBaseInfo();
             if(i < gmyws.size()){
                 scdBaseInfo.setDate(dateList.get(i));
                 scdBaseInfo.setTypeCode("010");
                 scdBaseInfo.setTypeValue(gmyws.get(i));
             }else {
                 scdBaseInfo.setDate(dateList.get(i));
                 scdBaseInfo.setTypeCode("010");
             }
            types.add(scdBaseInfo);
         }
    }

    private void setBreatheAndPain(GraphicsParam query,List<ScdBaseInfo> types,List<YzTemperature> yzTemperatures, List<String> dateList, String[] timeList) {
        // 新旧时间映射关系
        Map<String, String> newToOldTimeMap = new HashMap<>();
        newToOldTimeMap.put("02:00:00", "03:00:00");
        newToOldTimeMap.put("06:00:00", "07:00:00");
        newToOldTimeMap.put("10:00:00", "11:00:00");
        newToOldTimeMap.put("14:00:00", "15:00:00");
        newToOldTimeMap.put("18:00:00", "19:00:00");
        newToOldTimeMap.put("22:00:00", "23:00:00");
        
        for(String itemDate : dateList){
            for(String newTime : timeList){
                // 先尝试用新时间格式查找数据
                YzTemperature yzTemperature = filterYzTemperature(yzTemperatures, itemDate, newTime);
                
                // 如果没找到数据，尝试用旧时间格式查找
                if (yzTemperature.getRecTime() == null) {
                    String oldTime = newToOldTimeMap.get(newTime);
                    if (oldTime != null) {
                        yzTemperature = filterYzTemperature(yzTemperatures, itemDate, oldTime);
                    }
                }
                
                //098 呼吸
                //099 疼痛强度
                for (int i = 0; i < 2 ; i++) {
                    ScdBaseInfo scdBaseInfo = new ScdBaseInfo();
                    scdBaseInfo.setDate(itemDate);
                    scdBaseInfo.setTimes(newTime); // 始终使用新时间格式显示
                    if(i == 0){
                        scdBaseInfo.setTypeCode("098");
                        if(query.getHxFlag()){
                            scdBaseInfo.setTypeValue(Convert.toStr(yzTemperature.getBreathe(),""));
                        }else {
                            scdBaseInfo.setTypeValue("");
                        }
                    }else {
                        scdBaseInfo.setTypeCode("099");
                        scdBaseInfo.setTypeValue(yzTemperature.getPainLvl());
                    }
                    types.add(scdBaseInfo);
                }
            }
        }
    }

    @NotNull
    private YzTemperature filterYzTemperature(List<YzTemperature> yzTemperatures, String itemDate, String time) {
        YzTemperature yzTemperature = yzTemperatures.stream().filter(equalsDateTime(itemDate, time)).findFirst().orElse(new YzTemperature());
        return yzTemperature;
    }

    @NotNull
    private Predicate<YzTemperature> equalsDateTime(String itemDate, String time) {
        return o -> (itemDate + time).equals(DateUtil.formatDate(o.getRecDate()) + DateUtil.formatTime(o.getRecTime()));
    }

    public List<ScdRow> getRows(GraphicsParam query,List<YzTemperature> yzTemperatures, List<String> dateList, String[] timeList) {
        List<ScdRow> rows = new ArrayList<>();
        
        // 新旧时间映射关系
        Map<String, String> newToOldTimeMap = new HashMap<>();
        newToOldTimeMap.put("02:00:00", "03:00:00");
        newToOldTimeMap.put("06:00:00", "07:00:00");
        newToOldTimeMap.put("10:00:00", "11:00:00");
        newToOldTimeMap.put("14:00:00", "15:00:00");
        newToOldTimeMap.put("18:00:00", "19:00:00");
        newToOldTimeMap.put("22:00:00", "23:00:00");
        
        for(String itemDate : dateList){
            for(String newTime : timeList){
                ScdRow scdRow = new ScdRow();
                List<ScdBaseInfo> scdBaseInfos = new ArrayList<>();
                
                // 先尝试用新时间格式查找数据
                YzTemperature yzTemperature = filterYzTemperature(yzTemperatures, itemDate, newTime);
                
                // 如果没找到数据，尝试用旧时间格式查找
                if (yzTemperature.getRecTime() == null) {
                    String oldTime = newToOldTimeMap.get(newTime);
                    if (oldTime != null) {
                        yzTemperature = filterYzTemperature(yzTemperatures, itemDate, oldTime);
                    }
                }
                
                //003 腋表
                //015 肛表
                //014 心率
                //002 脉搏
                //012 特殊标记
                //001 口表
                for (int i = 0; i < 6; i++) {
                    ScdBaseInfo scdBaseInfo = new ScdBaseInfo();
                    scdBaseInfo.setDate(itemDate);
                    scdBaseInfo.setTimes(newTime); // 始终使用新时间格式显示
                    switch (i){
                        case 0:
                            scdBaseInfo.setTypeCode("003");
                            scdBaseInfo.setTypeValue("2".equals(yzTemperature.getTemperatureType()) ? Convert.toStr(yzTemperature.getTemperature(),null) : null);
                            break;
                        case 1:
                            scdBaseInfo.setTypeCode("015");
                            scdBaseInfo.setTypeValue("3".equals(yzTemperature.getTemperatureType()) ? Convert.toStr(yzTemperature.getTemperature(),null) : null);
                            break;
                        case 2:
                            scdBaseInfo.setTypeCode("001");
                            scdBaseInfo.setTypeValue("1".equals(yzTemperature.getTemperatureType()) ? Convert.toStr(yzTemperature.getTemperature(),null) : null);
                            break;
                        case 3:
                            scdBaseInfo.setTypeCode("014");
                            scdBaseInfo.setTypeValue(Convert.toStr(yzTemperature.getHeart(),null));
                            break;
                        case 4:
                            scdBaseInfo.setTypeCode("002");
                            if(query.getMbFlag()){
                                scdBaseInfo.setTypeValue(Convert.toStr(yzTemperature.getPulse(),null));
                            }
                            break;
                        case 5:
                            scdBaseInfo.setTypeCode("012");
                            String str ="";
                            if(yzTemperature.getSpecialtextTime() != null){
                                String format = DateUtil.format(yzTemperature.getSpecialtextTime(), "HH:mm");
                                // 使用自定义的数字转中文方法，确保转换准确性
                                str = StrUtil.format("{}时{}分",numberToChinese(Convert.toInt(format.split(":")[0])),numberToChinese(Convert.toInt(format.split(":")[1])));
                            }
                            // scdBaseInfo.setTypeValue(StrUtil.isBlank(yzTemperature.getScdSpecialtext()) ? "" : "手术".equals(yzTemperature.getScdSpecialtext()) ? "手术" : yzTemperature.getScdSpecialtext()+str);
                            scdBaseInfo.setTypeValue(StrUtil.isBlank(yzTemperature.getScdSpecialtext()) ? "" : yzTemperature.getScdSpecialtext()+str);
                            break;
                        default:
                            break;
                    }
                    scdBaseInfos.add(scdBaseInfo);
                }
                scdRow.setRowBOS(scdBaseInfos);
                rows.add(scdRow);
            }
        }
        return rows;
    }


    private List<String> createDateList(GraphicsParam query) {
        List<String> dateList = new ArrayList<>(7);
        for (int i = 0; i < 7 ; i++) {
            Date date =  DateUtil.offsetDay(DateUtil.parseDate(query.getStartRecTime()),i);
            dateList.add(DateUtil.formatDate(date));
        }
        return dateList;
    }

    public List<String> getOperDays(GraphicsParam query) {
        List<String> operaDays = new ArrayList<>(8);
        Date operDay = dao.selectOperaDay(query);
        if(operDay == null) return operaDays;
        Date startRecTime = DateUtil.parseDate(query.getStartRecTime());
        operaDays.add("");
            for (int i = 0; i <7 ; i++) {
                DateTime dateTime = DateUtil.offsetDay(startRecTime, i);
                int diff = (int)DateUtil.between(operDay, dateTime, DateUnit.DAY, false);
                if( diff > 0){
                    operaDays.add(Convert.toStr(diff));
                }else {
                    operaDays.add("");
                }
            }
        return operaDays;
    }

    public ResultVo<Map<Object, Object>> getWeek(YzTemperatureVO query) {
        Map<Object, Object> map = new HashMap<>();
        Map<String, Object> startAndEndTime = yzTemperatureMapper.getStartAndEndTime(query);
        if(MapUtil.isEmpty(startAndEndTime)){
            throw  new BizException(ExceptionEnum.INTERNAL_SERVER_ERROR,"没有查询到数据");
        }
        Date start = (Date) startAndEndTime.get("rec_start_date");
        Date end   = (Date)startAndEndTime.get("rec_end_date");
        //计算有几周
        long diffDay = DateUtil.betweenDay(start, end, true)+1;
        long totalWeek = diffDay % 7 == 0 ? diffDay / 7 : diffDay / 7 + 1;
        map.put("totalWeek",totalWeek);
        //计算每周的起始 结束日期  key 为第几周ons
        Date  dateTime = start;
        for (int i = 1; i <= totalWeek; i++) {
            Map<String, String> temp = new HashMap<>();
            temp.put("startDate",DateUtil.formatDate(dateTime));
            dateTime = DateUtil.offsetDay(dateTime, 6);
            temp.put("endDate",DateUtil.formatDate(dateTime));
            dateTime =DateUtil.offsetDay(dateTime, 1);
            map.put("ev_"+i,temp);
            }
        return ResultVoUtil.success(map);
    }

    public ResultVo<Patient> getAllPatintInfo(YzTemperatureVO query) {
        Patient patient = dao.getAllPatintInfo(query);
        try {
            patient.setAge(DateUtil.age(DateUtil.parseDate(patient.getBirthDate()),patient.getAdmissDate()));
        }catch (Exception e){

        }
        patient.setAdmissWardName(deptCache.getDeptName(patient.getAdmissWard()));
      return ResultVoUtil.success(patient);
    }


    public ResultVo<List<CodeName>> getAllWards() {
        return ResultVoUtil.success(yiZhuPublicDao.getAllWards());
    }

    public ResultVo<Map<String, Object>> queryTwMbRange() {
        Map<String, Object>  result = new HashMap<>(10);
        String twRange = dictDataDao.getDictValueByDictName("2.2", "tw_range");
        String mbRange = dictDataDao.getDictValueByDictName("2.3", "mb_range");
        try {
            result.put("twStart", twRange.split(",")[0]);
            result.put("twEnd", twRange.split(",")[1]);
            result.put("mbStart", mbRange.split(",")[0]);
            result.put("mbEnd", mbRange.split(",")[1]);
        }catch (Exception e){

        }
        return ResultVoUtil.success(result);
    }

    public ResultVo<Patient> saveTwMbRange(Map<String, Object> param) {
       String twStart = Convert.toStr(param.get("twStart"));
       String twEnd = Convert.toStr(param.get("twEnd"));
       String mbStart = Convert.toStr(param.get("mbStart"));
       String mbEnd = Convert.toStr(param.get("mbEnd"));
       AssertUtil.isnotBlank(twStart,"体温开始值不能为空");
       AssertUtil.isnotBlank(twEnd,"体温结束值不能为空");
       AssertUtil.isnotBlank(mbStart,"脉搏开始值不能为空");
       AssertUtil.isnotBlank(mbEnd,"脉搏结束值不能为空");
       if(!NumberUtil.isNumber(twStart) ||!NumberUtil.isNumber(twEnd) ||!NumberUtil.isNumber(mbStart) || !NumberUtil.isNumber(mbEnd)){
           throw new BizException(ExceptionEnum.LOGICAL_ERROR, "体温或脉搏值要为数字");
       }
       if(Convert.toBigDecimal(twStart).compareTo(Convert.toBigDecimal(twEnd)) > 0){
           throw new BizException(ExceptionEnum.LOGICAL_ERROR, "体温开始值不能大于结束值");
       }
        if(Convert.toBigDecimal(mbStart).compareTo(Convert.toBigDecimal(mbEnd)) > 0){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "脉搏开始值不能大于结束值");
        }
        dictDataDao.updateDictValue(twStart + "," + twEnd, "2.2", "tw_range");
        dictDataDao.updateDictValue(mbStart + "," + mbEnd, "2.3", "mb_range");
       return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }
}
