/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 15:39
 * Description:患者住院信息主索引管理
 */
package com.emr.service.ipml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emr.dao.*;
import com.emr.service.Emr_DictionaryService;
import com.emr.util.*;
import com.emr.vo.GetTime;
import com.emr.vo.Power_User_Dto;
import com.emr.entity.*;
import com.emr.service.Archive_MasterService;
import com.emr.service.PowerUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class Archive_MasterServiceImpl implements Archive_MasterService {
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${returnParam}")
    private String returnParam;
    @Value("${POWER_JSP}")
    private String POWER_JSP;
    @Autowired
    private Archive_MasterMapper archiveMasterMapper;

    @Autowired
    private PowerUserService powerUserService;

    @Autowired
    private MedicalRecordHomepageCacheMapper medicalRecordHomepageCacheMapper;

    @Autowired
    private ArchivePrintinfoMapper archivePrintinfoMapper;

    @Value("${observationRecordRequestUrl}")
    private String observationRecordRequestUrl;

    @Autowired
    private DocusRequestInfoMapper docusRequestInfoMapper;

    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;

    @Autowired
    private Emr_Fault_DetailMapper emrFaultDetailMapper;

    @Autowired
    private Archive_Master_FollowingMapper archiveMasterFollowingMapper;
    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @Override
    public Archive_Master selectById(String id) {
        return archiveMasterMapper.selectById(id);
    }

    @Override
    public List<Archive_Master> selectCommonlyUsed(String id) {
        return archiveMasterMapper.selectCommonlyUsed(id);
    }

    @Override
    public int insertCommonlyUsed(CommomVo commomVo) {
        return archiveMasterMapper.insertCommonlyUsed(commomVo);
    }

    @Override
    public List<Archive_Master> selByCol(Archive_Master archiveMaster) {
        return archiveMasterMapper.selByCol(archiveMaster);
    }


    @Override
    public OffsetLimitPage selectByCol(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master> list= selectByCol(archiveMasterVo);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master> selectByCol(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master> list=archiveMasterMapper.selectByCol(archiveMasterVo);
        if(list!=null && list.size()>0) {
            Emr_Dictionary dic = new Emr_Dictionary();
            dic.setEffective(1);
            dic.setTypecode("dept_code");
            //科室列表
            List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
            if (powerUserList != null) {
                Map<String, JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject, String>() {
                    @Override
                    public String apply(JSONObject temp) {
                        return temp.getString("userName");
                    }
                });
                for (Archive_Master archiveMaster : list) {
                    JSONObject userInfo = mappedMovies.get(archiveMaster.getDoctorName());
                    if (userInfo == null) {
                        archiveMaster.setDoctorName(archiveMaster.getDoctorName());
                    } else {
                        archiveMaster.setDoctorName(userInfo.getString("name"));
                    }

                    userInfo = mappedMovies.get(archiveMaster.getNurseName());
                    if (userInfo == null) {
                        archiveMaster.setNurseName(archiveMaster.getNurseName());
                    } else {
                        archiveMaster.setNurseName(userInfo.getString("name"));
                    }

                    //替换科室
                    for (int k = 0; k < dicList.size(); k++) {
                        String deptName = archiveMaster.getDeptName();
                        //入院科室dept_admission_to
                        String dept2 = archiveMaster.getDeptAdmissionTo();

                        if ((deptName != null && deptName.equals(dicList.get(k).getCode()))) {
                            //出院科室
                            deptName = deptName.replace(deptName, dicList.get(k).getName());
                            archiveMaster.setDeptName(deptName);
                        }
                        if (dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                            //入院科室
                            dept2 = dept2.replace(dept2, dicList.get(k).getName());
                            archiveMaster.setDeptAdmissionTo(dept2);
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Archive_Master> selectByInpAndVisitId(Archive_Master_Vo archiveMasterVo) {
        return archiveMasterMapper.selectByInpAndVisitId(archiveMasterVo);
    }

    @Override
    public List<Archive_Master_Vo> selectByColumn(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> list=archiveMasterMapper.selectByColumn(archiveMasterVo);
        setDoctorAndNurseName(list);
        return list;
    }

   /*   @Override
    public List<Archive_Master> selectByUnfile2(Archive_Master_Vo archiveMasterVo) {
        return archiveMasterMapper.selectByUnfile2(archiveMasterVo);
    }*/

   /* @Override
    public List<Archive_Master> sel7DayByCol(Archive_Master_Vo archiveMasterVo) {
        return archiveMasterMapper.sel7DayByCol(archiveMasterVo);
    }*/

    @Override
    public List<Archive_Master_Vo> selectByLastByColumn(Archive_Master_Vo archiveMasterVo,Integer offset, Integer limit) {
        //根据条件查询记录
        if(null != offset && null != limit) {
            PageHelper.offsetPage(offset, limit);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectByLast(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //科室列表
            Emr_Dictionary dic = new Emr_Dictionary();
            dic.setEffective(1);
            dic.setTypecode("dept_code");
            setNameAndPrintFlagNew(archiveMasterVo, list);
            List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
            //转换科室
            Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
            Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                String deptCode = p.getDeptName();
                if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                    String deptName = codeMap.get(deptCode).getName();
                    p.setDeptName(deptName);
                }
            });
            //masterIds集合
            List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getId);
            //分批次
            List<List<String>> newList = ListUtils.partition(masterIds, 1000);
            for (List<String> messageList : newList) {
                //转成逗号拼接
                String ids = String.join(",", messageList);
                //获取医生缺陷数量
                List<Archive_Master_Vo> doctorDefectNum = archiveMasterMapper.getDoctorDefectNum(ids);
                //医生是否有缺陷
                Map<String, Archive_Master_Vo> doctorMap = ListUtil.toMap(doctorDefectNum, Archive_Master_Vo::getArchiveDetailId);
                Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                    String doctorId = p.getId();
                    if (doctorMap.containsKey(doctorId)){
                        String faultDoctorNum = doctorMap.get(doctorId).getFaultDoctorNum();
                        p.setFaultDoctorNum(faultDoctorNum);
                        p.setNumb(1);
                    }
                });
                //获取护士缺陷数量
                List<Archive_Master_Vo> nurseDefectNum = archiveMasterMapper.getNurseDefectNum(ids);
                //护士是否有缺陷
                Map<String, Archive_Master_Vo> nurseMap = ListUtil.toMap(nurseDefectNum, Archive_Master_Vo::getArchiveDetailId);
                //判断是否有缺陷就填入
                Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                    String nurseId = p.getId();
                    if (nurseMap.containsKey(nurseId)){
                        String faultNurseNum = nurseMap.get(nurseId).getFaultNurseNum();
                        p.setFaultNurseNum(faultNurseNum);
                        p.setNumb(1);
                    }
                });
                //是否有退回
                setFollowingTypeNew(ids,list);
            }

        }
        return list;
    }

    @Override
    public OffsetLimitPage selectByColumn(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        List<Archive_Master_Vo> list = selectBeHospitalByColumn(archiveMasterVo,offset,limit);
        return new OffsetLimitPage((Page) list);
    }

    /**
     * 判断并设置查询是否打印权限
     * @param archiveMasterVo
     */
    private void setIdByPrintNum(Archive_Master_Vo archiveMasterVo){
        //是否查询打印情况
        if(StringUtils.isNotBlank(archiveMasterVo.getPrintNum())){
            List<ArchivePrintinfo> archivePrintinfos = archivePrintinfoMapper.selectPrintCountByMasterId(null);
            //定义masterIds
            StringBuilder masterIds = new StringBuilder();
            if(!CollectionUtils.isEmpty(archivePrintinfos)){
                for(ArchivePrintinfo archivePrintinfo : archivePrintinfos){
                    if(StringUtils.isNotBlank(masterIds)){
                        masterIds.append(",");
                    }
                    masterIds.append(archivePrintinfo.getMasterid());
                }
            }else{
                masterIds = new StringBuilder("notAll");
            }
            archiveMasterVo.setId(masterIds.toString());
        }
    }

    @Override
    public List<Archive_Master_Vo> selectBeHospitalByColumn(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        //根据条件查询记录
        if(null != offset && null != limit) {
            PageHelper.offsetPage(offset, limit);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectByColumn(archiveMasterVo);
        //获取科室列表
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String deptCode = p.getDeptName();
            String deptAdmissionCode = p.getDeptAdmissionTo();
            if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                String deptName = codeMap.get(deptCode).getName();
                p.setDeptName(deptName);
            }
            if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                p.setDeptAdmissionTo(deptAdmissionTo);
            }
        });
        //masterIds集合
        List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getId);
        //转成逗号拼接
        String ids = String.join(",", masterIds);
        //获取医生缺陷数量
        List<Archive_Master_Vo> doctorDefectNum = archiveMasterMapper.getDoctorDefectNum(ids);
        //医生是否有缺陷
        Map<String, Archive_Master_Vo> doctorMap = ListUtil.toMap(doctorDefectNum, Archive_Master_Vo::getArchiveDetailId);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String doctorId = p.getId();
            if (doctorMap.containsKey(doctorId)){
                String faultDoctorNum = doctorMap.get(doctorId).getFaultDoctorNum();
                p.setFaultDoctorNum(faultDoctorNum);
                p.setNumb(1);
            }
        });
        //获取护士缺陷数量
        List<Archive_Master_Vo> nurseDefectNum = archiveMasterMapper.getNurseDefectNum(ids);
        //护士是否有缺陷
        Map<String, Archive_Master_Vo> nurseMap = ListUtil.toMap(nurseDefectNum, Archive_Master_Vo::getArchiveDetailId);
        //判断是否有缺陷就填入
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String nurseId = p.getId();
            if (nurseMap.containsKey(nurseId)){
                String faultNurseNum = nurseMap.get(nurseId).getFaultNurseNum();
                p.setFaultNurseNum(faultNurseNum);
                p.setNumb(1);
            }
        });
        //设置医生、护士名称和打印标识、科室、是否退回医生、是否退回护士
        setNameAndPrintFlagNew(archiveMasterVo, list);
        if(list!=null && list.size()>0) {
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
            if (powerUserList != null){
                Map<String,JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject,String>() {
                    @Override
                    public String apply(JSONObject temp) {
                        return temp.getString("userName");
                    }});

                for (Archive_Master_Vo emr_fault_vo : list) {
                    //  emr_fault_vo.setBackFee(priceVal);
                    //主管医生
                    JSONObject userInfo = mappedMovies.get(emr_fault_vo.getDoctorInCharge());
                    if (userInfo == null) {
                        emr_fault_vo.setDoctorInCharge(emr_fault_vo.getDoctorInCharge());
                    } else {
                        emr_fault_vo.setDoctorInCharge(userInfo.getString("name"));
                    }
                    //退回人
                    userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                    if (userInfo == null) {
                        emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                    } else {
                        emr_fault_vo.setCreater(userInfo.getString("name"));
                    }
                }

            }
        }
        return list;
    }

    //设置科室名称
    private void setDeptName(Archive_Master_Vo archiveMasterVo,List<Emr_Dictionary> dictionaryList){
        if(!CollectionUtils.isEmpty(dictionaryList)){
            String deptAdmissionTo = archiveMasterVo.getDeptAdmissionTo();
            String deptName = archiveMasterVo.getDeptName();
            for(Emr_Dictionary dictionary : dictionaryList){
                if(StringUtils.isNotBlank(deptAdmissionTo) && dictionary.getCode().equals(deptAdmissionTo)){
                    archiveMasterVo.setDeptAdmissionTo(dictionary.getName());
                }
                if(StringUtils.isNotBlank(deptName) && dictionary.getCode().equals(deptName)){
                    archiveMasterVo.setDeptName(dictionary.getName());
                }
            }
        }

    }

    //设置退回医生数量
    private void setDoctorFaultNum(String masterIds,List<Archive_Master_Vo> list){
        String backFlags = "1" + "," + "5";
        List<Emr_Fault_Detail> emrFaultDetails = emrFaultDetailMapper.faultBackMasterIdListByBackFlag(backFlags, masterIds);
        if(!CollectionUtils.isEmpty(emrFaultDetails)){
            for(Archive_Master_Vo archiveMasterVo : list) {
                for (Emr_Fault_Detail detail : emrFaultDetails) {
                    if (detail.getArchiveDetailId().equals(archiveMasterVo.getId())){
                        archiveMasterVo.setDoctorNum(detail.getId().toString());
                        break;
                    }
                }
            }
        }
    }
    //设置退回护士数量
    private void setNurseFaultNum(String masterIds,List<Archive_Master_Vo> list){
        String backFlags = "2" + "," + "6";
        List<Emr_Fault_Detail> emrFaultDetails = emrFaultDetailMapper.faultBackMasterIdListByBackFlag(backFlags, masterIds);
        if(!CollectionUtils.isEmpty(emrFaultDetails)){
            for(Archive_Master_Vo archiveMasterVo : list) {
                for (Emr_Fault_Detail detail : emrFaultDetails) {
                    if (detail.getArchiveDetailId().equals(archiveMasterVo.getId())){
                        archiveMasterVo.setNurseNum(detail.getId().toString());
                        break;
                    }
                }
            }
        }
    }

    //设置followingType=9
    private void setFollowingType(String masterIds, List<Archive_Master_Vo> list) {
        List<Archive_Master_Following> archiveMasterFollowings = archiveMasterFollowingMapper.selectFollowingByFollowingType("9", masterIds);
        if(!CollectionUtils.isEmpty(archiveMasterFollowings)){
            for(Archive_Master_Vo archiveMasterVo : list) {
                for (Archive_Master_Following following : archiveMasterFollowings) {
                    if (following.getMasterId().equals(archiveMasterVo.getId())){
                        archiveMasterVo.setFollowingType("9");
                        break;
                    }
                }
            }
        }
    }


    private void setFollowingTypeNew(String masterIds, List<Archive_Master_Vo> list) {
        List<Archive_Master_Following> archiveMasterFollowings = archiveMasterFollowingMapper.selectFollowingByFollowingTypeNew("9", masterIds);
        if(!CollectionUtils.isEmpty(archiveMasterFollowings)){
            for(Archive_Master_Vo archiveMasterVo : list) {
                for (Archive_Master_Following following : archiveMasterFollowings) {
                    if (following.getMasterId().equals(archiveMasterVo.getId())){
                        archiveMasterVo.setFollowingType("9");
                        break;
                    }
                }
            }
        }
    }
    /**
     * 设置医生、护士名称和打印标识、科室名称、是否退回医生、是否退回护士,是否followType=9
     * @param archiveMasterVo
     * @param list
     */
    private void setNameAndPrintFlag(Archive_Master_Vo archiveMasterVo, List<Archive_Master_Vo> list) {
        if(!CollectionUtils.isEmpty(list)) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if(!CollectionUtils.isEmpty(powerUsers)) {
                 //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //查询科室字典
            Emr_Dictionary dictionary = new Emr_Dictionary();
            dictionary.setTypecode("dept_code");
            List<Emr_Dictionary> dictionaryList = dictionaryMapper.dicByTypeCode(dictionary);
            //定义查询的masterId集合
            StringBuilder masterIds = new StringBuilder();
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if(null != powerUserList) {
                    //获取医生工号
                    String doctorName = archiveMaster.getDoctorName();
                    //获取护士工号
                    String nurseName = archiveMaster.getNurseName();
                    //获取初审人工号
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for(Power_User_Dto powerUserDto : powerUserList){
                        String name = powerUserDto.getName();
                        if(StringUtils.isNotBlank(doctorName) && powerUserDto.getUserName().equals(doctorName)){
                            archiveMaster.setDoctorName(name);
                        }
                        if(StringUtils.isNotBlank(nurseName) && powerUserDto.getUserName().equals(nurseName)){
                            archiveMaster.setNurseName(name);
                        }
                        if(StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)){
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
                String printNum = archiveMaster.getPrintNum();
                if(StringUtils.isNotBlank(printNum) && !"0".equals(printNum)){
                    archiveMaster.setPrintNum("已打印");
                }else{
                    archiveMaster.setPrintNum("未打印");
                }
                //是否打印条件不为空，直接赋值打印标识
                if(StringUtils.isNotBlank(archiveMasterVo.getPrintNum())){
                    String printFlag = "未打印";
                    if("1".equals(archiveMasterVo.getPrintNum())){
                        printFlag = "已打印";
                    }
                    archiveMaster.setPrintNum(printFlag);
                }
                if(StringUtils.isNotBlank(masterIds)){
                    masterIds.append(",");
                }
                masterIds.append("'").append(archiveMaster.getId()).append("'");
//                //设置科室名称
//                setDeptName(archiveMaster,dictionaryList);
                archiveMaster.setDoctorNum("0");
                archiveMaster.setNurseNum("0");
            }

            //设置退回医生数量
            setDoctorFaultNum(masterIds.toString(),list);
            //设置退回护士数量
            setNurseFaultNum(masterIds.toString(),list);
            //设置followingType=9
            setFollowingType(masterIds.toString(),list);
        }
    }


    /**
     * 设置医生、护士名称和打印标识、科室名称、是否退回医生、是否退回护士,是否followType=9
     * @param archiveMasterVo
     * @param list
     */
    private void setNameAndPrintFlagNew(Archive_Master_Vo archiveMasterVo, List<Archive_Master_Vo> list) {
        if(!CollectionUtils.isEmpty(list)) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if(!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //定义查询的masterId集合
            StringBuilder masterIds = new StringBuilder();
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if(null != powerUserList) {
                    //获取医生工号
                    String doctorName = archiveMaster.getDoctorName();
                    //获取护士工号
                    String nurseName = archiveMaster.getNurseName();
                    //获取初审人工号
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for(Power_User_Dto powerUserDto : powerUserList){
                        String name = powerUserDto.getName();
                        if(StringUtils.isNotBlank(doctorName) && powerUserDto.getUserName().equals(doctorName)){
                            archiveMaster.setDoctorName(name);
                        }
                        if(StringUtils.isNotBlank(nurseName) && powerUserDto.getUserName().equals(nurseName)){
                            archiveMaster.setNurseName(name);
                        }
                        if(StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)){
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
                String printNum = archiveMaster.getPrintNum();
                if(StringUtils.isNotBlank(printNum) && !"0".equals(printNum)){
                    archiveMaster.setPrintNum("已打印");
                }else{
                    archiveMaster.setPrintNum("未打印");
                }
                //是否打印条件不为空，直接赋值打印标识
                if(StringUtils.isNotBlank(archiveMasterVo.getPrintNum())){
                    String printFlag = "未打印";
                    if("1".equals(archiveMasterVo.getPrintNum())){
                        printFlag = "已打印";
                    }
                    archiveMaster.setPrintNum(printFlag);
                }
                if(StringUtils.isNotBlank(masterIds)){
                    masterIds.append(",");
                }
                masterIds.append("'").append(archiveMaster.getId()).append("'");
                archiveMaster.setDoctorNum("0");
                archiveMaster.setNurseNum("0");
            }
        }
    }

    /**
     * 设置医生和护士姓名
     * @param list
     */
    private void setDoctorAndNurseName(List<Archive_Master_Vo> list){
        if(!CollectionUtils.isEmpty(list)) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取医生工号
                    String doctorName = archiveMaster.getDoctorName();
                    //获取护士工号
                    String nurseName = archiveMaster.getNurseName();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorName) && powerUserDto.getUserName().equals(doctorName)) {
                            archiveMaster.setDoctorName(name);
                        }
                        if (StringUtils.isNotBlank(nurseName) && powerUserDto.getUserName().equals(nurseName)) {
                            archiveMaster.setNurseName(name);
                        }
                    }
                }
            }
        }
    }

    @Override
    public OffsetLimitPage selectByUnfile(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        List<Archive_Master_Vo> list = selectByUnfileAndColumn(archiveMasterVo,offset,limit);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> selectByUnfileAndColumn(Archive_Master_Vo archiveMasterVo,Integer offset, Integer limit) {
        //根据条件查询记录
        if(null != offset && null != limit) {
            PageHelper.offsetPage(offset, limit);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectByUnfileNew(archiveMasterVo);
        //获取科室列表
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String deptCode = p.getDeptName();
            String deptAdmissionCode = p.getDeptAdmissionTo();
            if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                String deptName = codeMap.get(deptCode).getName();
                p.setDeptName(deptName);
            }
            if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                p.setDeptAdmissionTo(deptAdmissionTo);
            }
        });
        //masterIds集合
        List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getId);
        //分批次
        List<List<String>> newList = ListUtils.partition(masterIds, 1000);
        for (List<String> messageList : newList) {
            //转成逗号拼接
            String ids = String.join(",", messageList);
            //获取医生缺陷数量
            List<Archive_Master_Vo> doctorDefectNum = archiveMasterMapper.getDoctorDefectNum(ids);
            //医生是否有缺陷
            Map<String, Archive_Master_Vo> doctorMap = ListUtil.toMap(doctorDefectNum, Archive_Master_Vo::getArchiveDetailId);
            Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                String doctorId = p.getId();
                if (doctorMap.containsKey(doctorId)){
                    String faultDoctorNum = doctorMap.get(doctorId).getFaultDoctorNum();
                    p.setFaultDoctorNum(faultDoctorNum);
                    p.setNumb(1);
                }
            });
            //获取护士缺陷数
            List<Archive_Master_Vo> nurseDefectNum = archiveMasterMapper.getNurseDefectNum(ids);
            //护士是否有缺陷
            Map<String, Archive_Master_Vo> nurseMap = ListUtil.toMap(nurseDefectNum, Archive_Master_Vo::getArchiveDetailId);
            //判断是否有缺陷就填入
            Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                String nurseId = p.getId();
                if (nurseMap.containsKey(nurseId)){
                    String faultNurseNum = nurseMap.get(nurseId).getFaultNurseNum();
                    p.setFaultNurseNum(faultNurseNum);
                    p.setNumb(1);
                }
            });
        }
        //设置医生、护士名称和打印标识、科室、是否退回医生、是否退回护士
        setNameAndPrintFlagNew(archiveMasterVo, list);
        if(list!=null && list.size()>0) {
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
            if (powerUserList != null){
                Map<String,JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject,String>() {
                    @Override
                    public String apply(JSONObject temp) {
                        return temp.getString("userName");
                    }});

                for (Archive_Master_Vo emr_fault_vo : list) {
                    //  emr_fault_vo.setBackFee(priceVal);
                    //主管医生
                    JSONObject userInfo = mappedMovies.get(emr_fault_vo.getDoctorInCharge());
                    if (userInfo == null) {
                        emr_fault_vo.setDoctorInCharge(emr_fault_vo.getDoctorInCharge());
                    } else {
                        emr_fault_vo.setDoctorInCharge(userInfo.getString("name"));
                    }
                    //退回人
                    userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                    if (userInfo == null) {
                        emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                    } else {
                        emr_fault_vo.setCreater(userInfo.getString("name"));
                    }
                }

            }
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        Integer userId = user.getUserId();
        if (user.getRoleId()!=0){
            String url = POWER_JSP+"/font/getUserMun?userId="+userId;
            String obj = HttpClientUtils.httpGetFlag(url);
            if (StringUtils.isNotBlank(obj)){
                for (Archive_Master_Vo masterVo:list){
                    masterVo.setPdfFlag("1");
                }
            }
        } else {
            for (Archive_Master_Vo masterVo:list){
                masterVo.setPdfFlag("1");
            }
        }
        return list;
    }


    @Override
    public OffsetLimitPage selectStorageByCol(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master_Vo> list = archiveMasterMapper.selectStorageByCol(archiveMasterVo);
        //查询科室列表
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        for (Archive_Master_Vo archiveMaster:list){
            for (int k = 0; k < dicList.size(); k++) {
                if(StringUtils.isNotBlank(archiveMaster.getDeptName())){
                    String deptName = archiveMaster.getDeptName();
                    if (deptName.equals(dicList.get(k).getCode())) {
                        //出院科室
                        deptName = deptName.replace(deptName, dicList.get(k).getName());
                        archiveMaster.setDeptName(deptName);
                    }
                }
                if (StringUtils.isNotBlank(archiveMaster.getDeptAdmissionTo())){
                    String dept2 = archiveMaster.getDeptAdmissionTo();
                    if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                        //入院科室dept_admission_to
                        dept2 = dept2.replace(dept2, dicList.get(k).getName());
                        archiveMaster.setDeptAdmissionTo(dept2);
                    }
                }
            }
        }
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> selectStorageByCol(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> archiveMasterVos = archiveMasterMapper.selectStorageByCol(archiveMasterVo);
        //查询科室列表
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        for (Archive_Master_Vo archiveMaster:archiveMasterVos){
            for (int k = 0; k < dicList.size(); k++) {
                if(StringUtils.isNotBlank(archiveMaster.getDeptName())){
                    String deptName = archiveMaster.getDeptName();
                    if (deptName.equals(dicList.get(k).getCode())) {
                        //出院科室
                        deptName = deptName.replace(deptName, dicList.get(k).getName());
                        archiveMaster.setDeptName(deptName);
                    }
                }
                if (StringUtils.isNotBlank(archiveMaster.getDeptAdmissionTo())){
                    String dept2 = archiveMaster.getDeptAdmissionTo();
                    if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                        //入院科室dept_admission_to
                        dept2 = dept2.replace(dept2, dicList.get(k).getName());
                        archiveMaster.setDeptAdmissionTo(dept2);
                    }
                }
            }
        }
        return archiveMasterVos;
    }

    @Override
    public OffsetLimitPage selectByLast(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        List<Archive_Master_Vo> list = selectByLastByColumn(archiveMasterVo, offset, limit);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public OffsetLimitPage selectByCmtCol(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        List<Archive_Master_Vo> list = selectByCmtByColumn(archiveMasterVo, offset, limit);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public int updateByClo(Archive_Master record) {
        return archiveMasterMapper.updateByClo(record);
    }

    @Override
    public int deleteRecordByInp(String masterId) {
        return archiveMasterMapper.deleteRecordByInp(masterId);
    }


    @Override
    public int updateByClo2(Archive_Master record) {
        return archiveMasterMapper.updateByClo2(record);
    }

    @Override
    public int updateById(Archive_Master record) {
        return archiveMasterMapper.updateById(record);
    }

    @Override
    public List<Archive_Master> getDoctorInCharge(Archive_Master record) {
        return archiveMasterMapper.getDoctorInCharge(record);
    }

    @Override
    public List<Archive_Master> bbSel(Archive_Master_Vo record) {
        return archiveMasterMapper.bbSel(record);
    }

    @Override
    public OffsetLimitPage bbSel(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master> list = archiveMasterMapper.bbSel(archiveMasterVo);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master> bbSel2(Archive_Master_Vo record) {
        return archiveMasterMapper.bbSel2(record);
    }

    @Override
    public OffsetLimitPage bbSel2(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master> list = archiveMasterMapper.bbSel2(archiveMasterVo);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> selectHandleDetail(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> list = archiveMasterMapper.selectHandleDetail(archiveMasterVo);
        return list;
    }

    @Override
    public OffsetLimitPage selectHandleDetail(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master_Vo> list = archiveMasterMapper.selectHandleDetail(archiveMasterVo);
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String deptCode = p.getDeptName();
            String deptAdmissionCode = p.getDeptAdmissionTo();
            if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                String deptName = codeMap.get(deptCode).getName();
                p.setDeptName(deptName);
            }
            if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                p.setDeptAdmissionTo(deptAdmissionTo);
            }
        });
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> selectOverdue(Archive_Master_Vo archiveMasterVo) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date1=null;
        Date date2=null;
        Date date3=null;
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        //科室列表
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //转换科室
            Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
            Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                String deptCode = p.getDeptName();
                String deptAdmissionCode = p.getDeptAdmissionTo();
                if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                    String deptName = codeMap.get(deptCode).getName();
                    p.setDeptName(deptName);
                }
                if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                    String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                    p.setDeptAdmissionTo(deptAdmissionTo);
                }
            });
            //masterIds集合
            List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getMasterId);
            //分批次
            List<List<String>> newList = ListUtils.partition(masterIds, 1000);
            for (List<String> messageList : newList) {
                //转成逗号拼接
                String ids = String.join(",", messageList);
                //根据分页的masterId获取签收信息
                List<Archive_Master_Vo> followingInfo = archiveMasterMapper.getFollowingInfo(ids);
                //医生是否有缺陷
                Map<String, Archive_Master_Vo> followingMap = ListUtil.toMap(followingInfo, Archive_Master_Vo::getMasterId);
                Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                    String masterId = p.getMasterId();
                    if (followingMap.containsKey(masterId)){
                        String handleTime = followingMap.get(masterId).getHandleTime();
                        String handleName = followingMap.get(masterId).getHandleName();
                        p.setHandleTime(handleTime);
                        p.setHandleName(handleName);
                    }
                });
            }
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    String overTime1 = archiveMaster.getOverTime1();
                    String handleTime = archiveMaster.getHandleTime();
                    String dischargeDateTime = archiveMaster.getDischargeDateTime();
                    try {
                        date1=format.parse(overTime1);
                        date2=format.parse(handleTime);
                        date3=format.parse(dischargeDateTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Calendar ca1 = Calendar.getInstance();
                    Calendar ca2 = Calendar.getInstance();
                    Calendar ca3 = Calendar.getInstance();
                    ca1.setTime(date1);
                    ca2.setTime(date2);
                    ca3.setTime(date3);
                    long distanceMin =( ca2.getTimeInMillis()- ca1.getTimeInMillis())/(1000*60*60*24);
                    long distanceMin2 =( ca2.getTimeInMillis()- ca3.getTimeInMillis())/(1000*60*60*24);
                    int i= (int)distanceMin;
                    int i2= (int)distanceMin2;
                    archiveMaster.setDiffDay(String.valueOf(i2));
                    archiveMasterVo.setDischargeDateTime1(date3);
                    if (i>0){
                        archiveMaster.setOverTime(i);
                    }else {
                        archiveMaster.setOverTime(0);
                    }
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
            }
        }
        return list;
    }




    @Override
    public List<Archive_Master_Vo> selectOverdueE(Archive_Master_Vo archiveMasterVo) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date1=null;
        Date date2=null;
        Date date3=null;
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        //科室列表
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdueE(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //转换科室
            Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
            Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                String deptCode = p.getDeptName();
                String deptAdmissionCode = p.getDeptAdmissionTo();
                if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                    String deptName = codeMap.get(deptCode).getName();
                    p.setDeptName(deptName);
                }
                if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                    String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                    p.setDeptAdmissionTo(deptAdmissionTo);
                }
            });
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    String overTime1 = archiveMaster.getOverTime1();
                    String handleTime = archiveMaster.getHandleTime();
                    String dischargeDateTime = archiveMaster.getDischargeDateTime();
                    try {
                        date1=format.parse(overTime1);
                        date2=format.parse(handleTime);
                        date3=format.parse(dischargeDateTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Calendar ca1 = Calendar.getInstance();
                    Calendar ca2 = Calendar.getInstance();
                    Calendar ca3 = Calendar.getInstance();
                    ca1.setTime(date1);
                    ca2.setTime(date2);
                    ca3.setTime(date3);
                    long distanceMin =( ca2.getTimeInMillis()- ca1.getTimeInMillis())/(1000*60*60*24);
                    long distanceMin2 =( ca2.getTimeInMillis()- ca3.getTimeInMillis())/(1000*60*60*24);
                    int i= (int)distanceMin;
                    int i2= (int)distanceMin2;
                    archiveMaster.setDiffDay(String.valueOf(i2));
                    archiveMasterVo.setDischargeDateTime1(date3);
                    if (i>0){
                        archiveMaster.setOverTime(i);
                    }else {
                        archiveMaster.setOverTime(0);
                    }
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public OffsetLimitPage selectOverdue(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date1=null;
        Date date2=null;
        Date date3=null;
        String overdueDaysTwo = archiveMasterVo.getOverdueDaysTwo();
        if (overdueDaysTwo.equals("")){
            archiveMasterVo.setOverdueDaysTwo("4");
        }else {
            int inum = Integer.parseInt(overdueDaysTwo);
            int inum2=inum+1;
            String s=String.valueOf(inum2);
            archiveMasterVo.setOverdueDaysTwo(s);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //赋值签收信息
            //masterIds集合
            List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getMasterId);
            //转成逗号拼接
            String ids = String.join(",", masterIds);
            //根据分页的masterId获取签收信息
            List<Archive_Master_Vo> followingInfo = archiveMasterMapper.getFollowingInfo(ids);
            //医生是否有缺陷
            Map<String, Archive_Master_Vo> followingMap = ListUtil.toMap(followingInfo, Archive_Master_Vo::getMasterId);
            Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
                String masterId = p.getMasterId();
                if (followingMap.containsKey(masterId)){
                    String handleTime = followingMap.get(masterId).getHandleTime();
                    String handleName = followingMap.get(masterId).getHandleName();
                    p.setHandleTime(handleTime);
                    p.setHandleName(handleName);
                }
            });
            Emr_Dictionary dic = new Emr_Dictionary();
            dic.setEffective(1);
            dic.setTypecode("dept_code");
            //科室列表
            List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (StringUtils.isNotBlank(archiveMaster.getHandleTime())){
                    //赋值超期天数
                    String overTime1 = archiveMaster.getOverTime1();
                    String handleTime = archiveMaster.getHandleTime();
                    String dischargeDateTime = archiveMaster.getDischargeDateTime();
                    try {
                        date1=format.parse(overTime1);
                        date2=format.parse(handleTime);
                        date3=format.parse(dischargeDateTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Calendar ca1 = Calendar.getInstance();
                    Calendar ca2 = Calendar.getInstance();
                    Calendar ca3 = Calendar.getInstance();
                    ca1.setTime(date1);
                    ca2.setTime(date2);
                    ca3.setTime(date3);
                    long distanceMin =( ca2.getTimeInMillis()- ca1.getTimeInMillis())/(1000*60*60*24);
                    long distanceMin2 =( ca2.getTimeInMillis()- ca3.getTimeInMillis())/(1000*60*60*24);
                    int i= (int)distanceMin;
                    int i2= (int)distanceMin2;
                    archiveMaster.setDiffDay(String.valueOf(i2));
                    archiveMasterVo.setDischargeDateTime1(date3);
                    if (i>0){
                        archiveMaster.setOverTime(i);
                    }else {
                        archiveMaster.setOverTime(0);
                    }
                }
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }

                    //转换科室
                    for (int k = 0; k < dicList.size(); k++) {
                        if (StringUtils.isNotBlank(archiveMaster.getDeptName())){
                            String deptName = archiveMaster.getDeptName();

                            if (deptName.equals(dicList.get(k).getCode())) {
                                //出院科室
                                deptName = deptName.replace(deptName, dicList.get(k).getName());
                                archiveMaster.setDeptName(deptName);
                            }
                        }
                      if (StringUtils.isNotBlank(archiveMaster.getDeptAdmissionTo())){
                          String dept2 = archiveMaster.getDeptAdmissionTo();
                          if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                              //入院科室dept_admission_to
                              dept2 = dept2.replace(dept2, dicList.get(k).getName());
                              archiveMaster.setDeptAdmissionTo(dept2);
                          }
                      }

                    }
                }
            }
        }
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> selectOverdueXls2(Archive_Master_Vo archiveMasterVo) {
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        //科室列表
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue2(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                    //转换科室
                    for (int k = 0; k < dicList.size(); k++) {
                        if (StringUtils.isNotBlank(archiveMaster.getDeptName())){
                            String deptName = archiveMaster.getDeptName();

                            if (deptName.equals(dicList.get(k).getCode())) {
                                //出院科室
                                deptName = deptName.replace(deptName, dicList.get(k).getName());
                                archiveMaster.setDeptName(deptName);
                            }
                        }
                        if (StringUtils.isNotBlank(archiveMaster.getDeptAdmissionTo())){
                            String dept2 = archiveMaster.getDeptAdmissionTo();
                            if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                                //入院科室dept_admission_to
                                dept2 = dept2.replace(dept2, dicList.get(k).getName());
                                archiveMaster.setDeptAdmissionTo(dept2);
                            }
                        }

                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Archive_Master_Vo> selectOverdueFirst(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue3(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Archive_Master_Vo> selectOverdueFirst1(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue4(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
            }
        }
        return list;
    }


    @Override
    public OffsetLimitPage selectOverdue2(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date1=null;
        Date date2=null;
        PageHelper.offsetPage(offset, limit);
        String overdueDaysTwo = archiveMasterVo.getOverdueDaysTwo();
        if (overdueDaysTwo.equals("")){
            archiveMasterVo.setOverdueDaysTwo("4");
        }else {
            int inum = Integer.parseInt(overdueDaysTwo);
            int inum2=inum+1;
            String s=String.valueOf(inum2);
            archiveMasterVo.setOverdueDaysTwo(s);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue2(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                Emr_Dictionary dic = new Emr_Dictionary();
                dic.setEffective(1);
                dic.setTypecode("dept_code");
                //科室列表
                List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
                //转换科室
                for (int k = 0; k < dicList.size(); k++) {
                    if (StringUtils.isNotBlank(archiveMaster.getDeptName())){
                        String deptName = archiveMaster.getDeptName();

                        if (deptName.equals(dicList.get(k).getCode())) {
                            //出院科室
                            deptName = deptName.replace(deptName, dicList.get(k).getName());
                            archiveMaster.setDeptName(deptName);
                        }
                    }
                    if (StringUtils.isNotBlank(archiveMaster.getDeptAdmissionTo())){
                        String dept2 = archiveMaster.getDeptAdmissionTo();
                        if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                            //入院科室dept_admission_to
                            dept2 = dept2.replace(dept2, dicList.get(k).getName());
                            archiveMaster.setDeptAdmissionTo(dept2);
                        }
                    }

                }
                String overTime1 = archiveMaster.getOverTime1();
                String handleTime = archiveMaster.getAgainTime();
                try {
                    date1=format.parse(overTime1);
                    date2=format.parse(handleTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar ca1 = Calendar.getInstance();
                Calendar ca2 = Calendar.getInstance();
                ca1.setTime(date1);
                ca2.setTime(date2);
                long distanceMin =( ca2.getTimeInMillis()- ca1.getTimeInMillis())/(1000*60*60*24);
                int i= (int)distanceMin;
                if (i>0){
                    archiveMaster.setOverTime(i);
                }else {
                    archiveMaster.setOverTime(0);
                }
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                        }
                    }
                }
            }
        }
        return new OffsetLimitPage((Page) list);
    }


    @Override
    public OffsetLimitPage selectOverdue3(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        String overdueDaysTwo = archiveMasterVo.getOverdueDaysTwo();
        if (overdueDaysTwo.equals("")){
            archiveMasterVo.setOverdueDaysTwo("4");
        }else {
            int inum = Integer.parseInt(overdueDaysTwo);
            int inum2=inum+1;
            String s=String.valueOf(inum2);
            archiveMasterVo.setOverdueDaysTwo(s);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue3(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                String overTime1 = archiveMaster.getOverTime1();
                int i = Integer.parseInt(overTime1);
                if (i>0){
                    archiveMaster.setOverTime(i);
                }else {
                    archiveMaster.setOverTime(0);
                }

                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                            break;
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                            break;
                        }
                    }
                }
            }
        }
        return new OffsetLimitPage((Page) list);
    }
    @Override
    public OffsetLimitPage selectOverdue4(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        String overdueDaysTwo = archiveMasterVo.getOverdueDaysTwo();
        if (overdueDaysTwo.equals("")){
            archiveMasterVo.setOverdueDaysTwo("4");
        }else {
            int inum = Integer.parseInt(overdueDaysTwo);
            int inum2=inum+1;
            String s=String.valueOf(inum2);
            archiveMasterVo.setOverdueDaysTwo(s);
        }
        List<Archive_Master_Vo> list = archiveMasterMapper.selectOverdue4(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                String overTime1 = archiveMaster.getOverTime1();
                int i = Integer.parseInt(overTime1);
                if (i>0){
                    archiveMaster.setOverTime(i);
                }else {
                    archiveMaster.setOverTime(0);
                }

                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //获取 初审人
                    String firstInstance = archiveMaster.getFirstInstance();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                            break;
                        }
                        if (StringUtils.isNotBlank(firstInstance) && powerUserDto.getUserName().equals(firstInstance)) {
                            archiveMaster.setFirstInstance(name);
                            break;
                        }
                    }
                }
            }
        }
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public OffsetLimitPage selectByFollowinglog(Archive_Master_Vo record, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master_Vo> list = archiveMasterMapper.selectByFollowinglog(record);
        //科室列表
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("safekeeping");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //添加封存类型
        //masterIds集合
        List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getMasterId);
        //转成逗号拼接
        String ids = String.join(",", masterIds);
        //查询封存记录
        List<Archive_Master_Vo> archiveMasterVos = archiveMasterMapper.selectFollowing(ids);
        Map<String, Archive_Master_Vo> masterIdMap = ListUtil.toMap(archiveMasterVos, Archive_Master_Vo::getMasterId);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String masterId = p.getMasterId();
            if (masterIdMap.containsKey(masterId)){
                p.setSafekeepingName(masterIdMap.get(masterId).getSafekeepingName());
            }
        });
        //转换科室
        Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String afekeepingCode = p.getSafekeepingName();
            if(StringUtils.isNotBlank(afekeepingCode) && codeMap.containsKey(afekeepingCode)){
                String afekeepingame = codeMap.get(afekeepingCode).getName();
                p.setSafekeepingName(afekeepingame);
            }
        });
        return  new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> selectByFollowinglog(Archive_Master_Vo archiveMasterVo) {
        return archiveMasterMapper.selectByFollowinglog(archiveMasterVo);
    }

    @Override
    public List<Archive_Master> selectByObject(String patientId,String visitId) {
        return archiveMasterMapper.selectByObject(patientId,visitId);
    }

    @Override
    public void requestObservationRecord(String inpatientNo, String status,String reason,List<Emr_Fault_Detail> list) {
        //留观推送第三方 http://10.162.0.51:8091/sanshuyun-ems-function/file/away/updateStatus
        Map<String,String> params = new HashMap<>();
        //留观号
        params.put("watchNo",inpatientNo);
        //status状态 AUDITED审核，RETURNED 退回
        params.put("status",status);
        if (StringUtils.isNotBlank(reason)) {
            params.put("reason",reason);
        }else {
            //获取打回原因
            StringBuilder returnContent = new StringBuilder();
            if (!CollectionUtils.isEmpty(list)) {
                for (Emr_Fault_Detail obj : list) {
                    if (StringUtils.isNotBlank(returnContent)) {
                        returnContent.append(",");
                    }
                    returnContent.append(obj.getBackContent());
                    String content = obj.getContent();
                    if (StringUtils.isBlank(content)) {
                        content = "无";
                    }
                    returnContent.append(":").append(content);
                }
                if (StringUtils.isNotBlank(returnContent)) {
                    params.put("reason", returnContent.toString());
                }
            }
        }
        try {
            HttpClientTool.doPost(observationRecordRequestUrl,params);
        } catch (IOException e) {
            e.printStackTrace();
            String errorStr = "留观病历操作推送第三方失败,inpatientNo:" + inpatientNo + ";status:" + status;
            System.out.println(errorStr);
            log.error(errorStr);
        }
    }
    @Override
    public List<Archive_Master_Vo> selectByCmtByColumn(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        //判断并设置查询是否打印权限
        //setIdByPrintNum(archiveMasterVo);
        //根据条件查询记录
        if(null != offset && null != limit) {
            PageHelper.offsetPage(offset, limit);
        }
        //转换科室
        List<Archive_Master_Vo> list = archiveMasterMapper.selectByCmtCol(archiveMasterVo);
        //masterIds集合
        List<String> masterIds = ListUtil.distinctSelect(list, Archive_Master_Vo::getId);
        //转成逗号拼接
        String ids = String.join(",", masterIds);
        //获取医生缺陷数量
        List<Archive_Master_Vo> doctorDefectNum = archiveMasterMapper.getDoctorDefectNum(ids);
        //医生是否有缺陷
        Map<String, Archive_Master_Vo> doctorMap = ListUtil.toMap(doctorDefectNum, Archive_Master_Vo::getArchiveDetailId);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String doctorId = p.getId();
            if (doctorMap.containsKey(doctorId)){
                String faultDoctorNum = doctorMap.get(doctorId).getFaultDoctorNum();
                p.setFaultDoctorNum(faultDoctorNum);
                p.setNumb(1);
            }
        });
        //获取护士缺陷数量
        List<Archive_Master_Vo> nurseDefectNum = archiveMasterMapper.getNurseDefectNum(ids);
        //护士是否有缺陷
        Map<String, Archive_Master_Vo> nurseMap = ListUtil.toMap(nurseDefectNum, Archive_Master_Vo::getArchiveDetailId);
        //判断是否有缺陷就填入
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String nurseId = p.getId();
            if (nurseMap.containsKey(nurseId)){
                String faultNurseNum = nurseMap.get(nurseId).getFaultNurseNum();
                p.setFaultNurseNum(faultNurseNum);
                p.setNumb(1);
            }
        });
        //获取科室列表
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
        Setters.<Archive_Master_Vo>instance().list(list).cycleSetProperties(p -> {
            String deptCode = p.getDeptName();
            String deptAdmissionCode = p.getDeptAdmissionTo();
            if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                String deptName = codeMap.get(deptCode).getName();
                p.setDeptName(deptName);
            }
            if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                p.setDeptAdmissionTo(deptAdmissionTo);
            }
        });

        //设置医生、护士名称和打印标识
        setNameAndPrintFlagNew(archiveMasterVo, list);
        return list;
    }

    /**
     * 退回电子病历
     * @param emrFaultDetail
     * @param archiveMaster
     * @param request
     */
    @Override
    public String returnEmr(List<Emr_Fault_Detail> list,Emr_Fault_Detail emrFaultDetail, Archive_Master archiveMaster, HttpServletRequest request) {
        String returnMsg = null;
        //获取退回标识，0打回首页；1打回医生；2打回护士
        String returnFlag = emrFaultDetail.getDealFlag();
        if(StringUtils.isNotBlank(returnFlag)) {
            //组织打回参数值
            /*{
                "INP_NO": "1356601",
                "VISIT_ID": "31",
                "DISCHARGE_DATE_TIME": "2021/3/8 9:54:00",
                "FLAG": "0,2",
                "HOSPITAL_NO": "12440000455858169P",
                "userid": "CSCS",
                "username": "CSCS",
                "code": "1340100",
                "REASON": "第三方打回"
            }*/
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            Map<String,Object> map = new HashMap<>();
            map.put("INP_NO",archiveMaster.getInpNo());
            map.put("VISIT_ID",archiveMaster.getVisitId());
            map.put("DISCHARGE_DATE_TIME",archiveMaster.getDischargeDateTime());
            map.put("FLAG",returnFlag);
            map.put("HOSPITAL_NO","12440000455858169P");
            map.put("userid",user.getUserId().toString());
            map.put("username",user.getUserName());
            map.put("code",archiveMaster.getDeptName());
            map.put("REASON",emrFaultDetail.getDealPerson());
            //定义请求信息记录表
            DocusRequestInfo docusRequestInfo = new DocusRequestInfo();
            docusRequestInfo.setCode("return");
            docusRequestInfo.setCreateUsername(user.getUserName());
            docusRequestInfo.setCreateTime(new Date());
            docusRequestInfo.setJzh(archiveMaster.getPatientId());
            docusRequestInfo.setPrimaryKey(archiveMaster.getInpNo());
            docusRequestInfo.setMasterId(archiveMaster.getId());
            docusRequestInfo.setParamPrimaryMsg(returnFlag);
            docusRequestInfo.setResultState(0);
            try {
                long id = IDHelper.NewID();
                docusRequestInfo.setId(id);
                //map转json字符串
                Map<String,String> paramMap = new HashMap<>();
                JSONObject object = new JSONObject(map);
                String json = object.toString();
                docusRequestInfo.setParamInfo(json);
                paramMap.put(returnParam,json);
                String returnStr = HttpClientTool.doPost(returnUrl, paramMap);
                if(StringUtils.isNotBlank(returnStr) && returnStr.contains("成功")){
                    //成功
                    docusRequestInfo.setResultState(1);
                }else{
                    returnMsg = "提示错误信息（请与V6系统工程师联系）无法退回";
                }
                docusRequestInfo.setResultMsg(returnStr);
            } catch (Exception e) {
                e.printStackTrace();
                returnMsg = "调用退回电子病历失败";
            }
            docusRequestInfoMapper.insert(docusRequestInfo);
        }
        return returnMsg;
    }

    @Override
    public List<Archive_Master_Vo> copyDetailList(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> list = archiveMasterMapper.copyDetailList(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public OffsetLimitPage copyDetailList(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master_Vo> list = archiveMasterMapper.copyDetailList(archiveMasterVo);
        if(list!=null && list.size()>0) {
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Archive_Master_Vo archiveMaster : list) {
                if (null != powerUserList) {
                    //获取主管医生
                    String doctorInCharge = archiveMaster.getDoctorInCharge();
                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(doctorInCharge) && powerUserDto.getUserName().equals(doctorInCharge)) {
                            archiveMaster.setDoctorInCharge(name);
                        }
                    }
                }
            }
        }
        return  new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Archive_Master_Vo> copyCountList(Archive_Master_Vo archiveMasterVo) {
        List<Archive_Master_Vo> list = archiveMasterMapper.copyCountList(archiveMasterVo);
        return list;
    }

    @Override
    public OffsetLimitPage copyCountList(Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master_Vo> list = archiveMasterMapper.copyCountList(archiveMasterVo);
        return  new OffsetLimitPage((Page) list);
    }

    @Override
    public int selectWorkDateNum(GetTime getTime) {
        return medicalRecordHomepageCacheMapper.selectWorkDateNum(getTime) ;
    }

    @Override
    public Integer selectCountNum(Archive_Master_Vo archiveMasterVo) {
        return archiveMasterMapper.selectCountNum(archiveMasterVo);
    }

    @Override
    public OffsetLimitPage deathRecordList(Archive_Master_Vo record, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Archive_Master> list = archiveMasterMapper.getDeathRecordList(record);
        if(list!=null && list.size()>0) {
            //获取科室列表
            Emr_Dictionary dic = new Emr_Dictionary();
            dic.setEffective(1);
            dic.setTypecode("dept_code");
            List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
            //转换科室
            Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
                Setters.<Archive_Master>instance().list(list).cycleSetProperties(p -> {
                String deptCode = p.getDeptName();
                String deptAdmissionCode = p.getDeptAdmissionTo();
                if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                    String deptName = codeMap.get(deptCode).getName();
                    p.setDeptName(deptName);
                }
                if(StringUtils.isNotBlank(deptAdmissionCode) && codeMap.containsKey(deptAdmissionCode)){
                    String deptAdmissionTo = codeMap.get(deptAdmissionCode).getName();
                    p.setDeptAdmissionTo(deptAdmissionTo);
                }
            });
        }
        return  new OffsetLimitPage((Page) list);
    }
}
 

