package com.emr.controller.commomSearch;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.dao.*;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.dao.emrPdfWaterSet.EmrPdfWaterSetMapper;
import com.emr.dao.emrPrintAndDownLoad.EmrPrintDownloadInfoMapper;
import com.emr.dao.tScanAssort.T_Scan_AssortMapper;
import com.emr.entity.*;
import com.emr.entity.emrLog.Emr_Log;
import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.entity.recordType.Emr_Type;
import com.emr.entity.recordType.Emr_Type_Related;
import com.emr.service.CommomService;
import com.emr.service.Zd_AssortServiceImpl;
import com.emr.service.emrLog.LogService;
import com.emr.service.emrPrintOrDownLoadInfo.PrintOrDownLoadInfoService;
import com.emr.service.recordType.EmrTypeRelatedService;
import com.emr.service.recordType.EmrTypeService;
import com.emr.service.tScanAssort.T_Scan_AssortService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.Jpg2PdfUtil;
import com.emr.util.img2PdfUtil;
import com.emr.vo.EmrPrintOrDownLoadInfo.EmrPrintOrDownLoadInfoVo;
import com.emr.vo.FontVo.ScanAssortVo;
import com.emr.vo.browseRecords;
import com.emr.vo.commomSearch.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ProjectName:CommomSearchController
 * @Description:自定义查询
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/5/28 11:16
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/5/28 11:16
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("commom/")
public class CommomSearchController {
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private Archive_DetailMapper archiveDetailMapper;
    @Autowired
    private EmrTypeRelatedService typeRelatedService;
    @Autowired
    private T_Scan_AssortService scanAssortService;
    @Autowired
    private Zd_Cm3Mapper cm3Mapper;
    @Autowired
    private Zd_Icd_CodeMapper icdCodeMapper;
    @Autowired
    private T_Scan_AssortMapper scanAssortMapper;
    @Autowired
    private EmrTypeService emrTypeService;
    @Autowired
    private Zd_AssortServiceImpl assortService;
    @Autowired
    private Emr_Apply_ApproveMapper apply_approveMapper;
    @Autowired
    private PrintOrDownLoadInfoService printOrDownLoadInfoService;
    @Autowired
    private Zd_AssortMapper assortMapper;
    @Autowired
    private CommomService commomService;
    @Autowired
    private LogService logService;
    @Autowired
    private EmrPdfWaterSetMapper pdfWaterSetMapper;
    @Value("${initialization}")
    private String initialization;
    @Autowired
    private EmrPrintDownloadInfoMapper emrPrintDownloadInfoMapper;

    //祈福医院
    @RequiresPermissions("/commom/commomListqf")
    @OptionalLog(module = "查看", methods = "常用查询页面")
    @RequestMapping("commomListqf")
    public String commomListqf() {
        return "recordManage/commomSearch/commomListqf";
    }

    /**
     * @description: 加载是否初始化标识
     * @params:  Initialization
     * @return: Initialization
     * @author linjj
     * @date: 2023/6/2 17:04
     */
    @RequestMapping("getInitialization")
    @ResponseBody
    public String getInitialization() {
        return initialization;
    }



    //加载性别
    @RequestMapping("getSex")
    @ResponseBody
    public String getSex() {
        try {
            //加载性别集合
            List<Emr_Dictionary> sexList = dictionaryMapper.selectDictionaryByTypeCode("sex_code");
            return JSON.toJSONString(sexList);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    //加载科室
    @RequestMapping("getDept")
    @ResponseBody
    public String getDept() {
        try {
            //加载科室集合
            List<Emr_Dictionary> deptList = dictionaryMapper.selectDictionaryByTypeCode("dept_code");
            return JSON.toJSONString(deptList);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据公共表id查询公共表信息
     *
     * @param patientId
     * @return
     */
    @RequestMapping("getCommomInfoById")
    @ResponseBody
    public String getCommomInfoById(String patientId) {
        try {
            CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
            return JSON.toJSONString(commomVo);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加载公共表信息
     *
     * @return
     */
    @RequestMapping("getCommonInfo")
    @ResponseBody
    public String getCommonInfo() {
        try {
            List<CommomVo> commomVoList = commomMapper.selectAllInfo();
            return JSON.toJSONString(commomVoList);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    //加载转归情况
    @RequestMapping("getDiagStatus")
    @ResponseBody
    public String getDiagStatus() {
        try {
            //加载病状转归集合
            List<Emr_Dictionary> diagStatusList = dictionaryMapper.selectDictionaryByTypeCode("dis_diag_status");
            return JSON.toJSONString(diagStatusList);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 根据用户权限查询分段
     * @param request
     * @return
     */
    @RequestMapping("selectIsPowerByUser")
    @ResponseBody
    public String selectIsPowerByUser(HttpServletRequest request) {
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        try {
            List<Zd_Assort> zdAssorts = assortService.selectAllByPower(user);
            return JSON.toJSONString(zdAssorts);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }






    /***
     * 根据用户权限查询分段
     * @param request
     * @return
     */
    @RequestMapping("selectEmrType")
    @ResponseBody
    public String selectEmrType(HttpServletRequest request) {
        List<Emr_Type> emrTypes = assortService.selectEmrType();
        return JSON.toJSONString(emrTypes);
    }
    /******************************病案预览操作****************************/
    /**
     * 174医院、祈福
     *
     * @MethodName: showRecord174
     * @Description: 跳转到档案预览
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("showRecord174")
    public String showRecord174(String patientId, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        //加载登陆者
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        if (null != user) {
            model.addAttribute("user", user);
            model.addAttribute("roleId", user.getRoleId());
        }
        List<EmrPrintOrDownLoadInfoVo> printCount = null;
        try {
            printCount = printOrDownLoadInfoService.getPrintCount(patientId);

        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        if (null != printCount && !printCount.isEmpty()) {
            model.addAttribute("printCount", 1);
        }
        Short admissTimes = null;
        String name = null;
        String disDate = null;
        String disDept = null;
        String attending = null;
        String fileSource = null;
        List<CommomVo> commomVos = commomMapper.selectAllAndPatientId(patientId);
        for (CommomVo list : commomVos) {
            admissTimes = list.getAdmissTimes();
            name = list.getName();
            fileSource = list.getFileSource();
            disDate = list.getDisDate();
            disDept = list.getDisDept();
            attending = list.getAttending();
        }
        String userName = user.getUserPosition();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        Date date = new Date(System.currentTimeMillis());
        String format = formatter.format(date);
        browseRecords browseRecords = new browseRecords();
        browseRecords.setAdmissTimes(admissTimes);
        browseRecords.setPatientName(name);
        browseRecords.setDisDate(disDate);
        browseRecords.setDisDept(disDept);
        browseRecords.setAttending(attending);
        browseRecords.setPatientId(patientId);
        browseRecords.setBrowseTime(format);
        browseRecords.setBrowseName(userName);
        // 获取访问真实IP
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inet != null;
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        browseRecords.setIp(ipAddress);
//        emrPrintDownloadInfoMapper.insertBrowseRecords(browseRecords);
        return "recordManage/commomSearch/showRecord174";
    }

    @RequestMapping("showRecordSouth")
    public String showRecordSouth(String patientId, String userName, String deptName, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        model.addAttribute("userName", userName);
        model.addAttribute("deptName", deptName);
        //加载登陆者
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        if (null != user) {
            model.addAttribute("user", user);
            model.addAttribute("roleId", user.getRoleId());
        }
        List<EmrPrintOrDownLoadInfoVo> printCount = null;
        try {
            printCount = printOrDownLoadInfoService.getPrintCount(patientId);

        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        if (null != printCount && !printCount.isEmpty()) {
            model.addAttribute("printCount", 1);
        }
        Emr_Log emrLog = new Emr_Log();
        emrLog.setLogTitle("接口查看");
        emrLog.setLogContent("接口预览页面");
        logService.insertInterface(emrLog, userName);
        return "recordManage/commomSearch/showRecordSouth";
    }

    //加载病案信息
    @RequestMapping("getRecord")
    @ResponseBody
    public String getRecord(String patientId, String flag) {
        List<CommomVo> commomVos;
        if (StringUtils.isNoneBlank(patientId)) {
            try {
                //根据patientId查询包含其他诊断的基本信息
                 commomVos = commomMapper.selectOtherDiagByPatientId(patientId, flag);
                if (commomVos.size()==0){
                     commomVos = commomMapper.selectMasterByPatientId(patientId);
                }
                return JSON.toJSONString(commomVos.get(0));
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    //加载住院次数
    @RequestMapping("getAdmissTimes")
    @ResponseBody
    public String getAdmissTimes(String name, String inpatientNo) {
        List<CommomVo> admissTimes = null;
        if (StringUtils.isNoneBlank(name) && StringUtils.isNotBlank(inpatientNo)) {
            try {
                //根据名字病案号查询住院次数集合
                admissTimes = commomMapper.selectAdmissTimesByNameAndNo(name, inpatientNo);
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
                return null;
            }
        }
        if (null != admissTimes && !admissTimes.isEmpty()) {
            for (CommomVo admissTime : admissTimes) {
                //设置住院次数下拉框text中文名称
                admissTime.setAdmissTimesName("第" + toChinese(admissTime.getAdmissTimes() + "") + "次");
            }
            return JSON.toJSONString(admissTimes);
        }
        return null;
    }

    /**
     * 加载上传图片的分类
     */
    @RequestMapping("getAssortList")
    @ResponseBody
    public ResultUtil getAssortList(HttpServletRequest request) throws Exception {
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<Zd_Assort> zdAssorts = new ArrayList<>();
        if (user.getRoleId() == 0 || user.getRoleId() == -100) {
            zdAssorts = assortMapper.selectAll(new Zd_Assort());
        } else {
            zdAssorts = assortMapper.selectAllAndUserReaderByUserIdAndRoleId(user.getUserId(), user.getRoleId());
        }
        return ResultUtil.ok(zdAssorts);
    }

    /**
     * 脐血库、祈福
     * 跳转查看pdfiframe页
     *
     * @param patientId
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("showRecordIframeBlood")
    public String showRecordIframeBlood(String patientId, String flag, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        //打印分类集合
        List<Emr_Type> emrTypes = null;
        List<Zd_Assort> zdAssorts = null;
        int isDownload = 0;
        try {
            emrTypes = emrTypeService.selectAllByCreater(1, request);
            //病案分段集合
            zdAssorts = assortService.selectAllByPower(user);
            isDownload = apply_approveMapper.selectIsPowerByUser(user.getUserName(), patientId, 3);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("emrTypes", emrTypes);
        model.addAttribute("zdAssorts", zdAssorts);
        model.addAttribute("isDownload", isDownload);
        //查询是否有打印权限
        int printFlag = 0;
        int moveFlag = 0;
        Set<String> menus = user.getMenus();
        for (String menu : menus) {
            if (StringUtils.isNotBlank(menu)) {
                if ("/commom/printPdf".equals(menu)) {
                    printFlag = 1;
                }
                if ("/commom/movePdf".equals(menu)) {
                    moveFlag = 1;
                }
            }
        }
        model.addAttribute("moveFlag", moveFlag);
        model.addAttribute("printFlag", printFlag);
        model.addAttribute("flag", flag);
        return "recordManage/commomSearch/showRecordIframeBlood";
    }

    /**
     * 南方医院访问
     *
     * @param userName
     * @param flag
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("showRecordIframeSouth")
    public String showRecordIframeSouth(String patientId, String userName, String deptName, String flag, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        model.addAttribute("userName", request.getSession().getAttribute("userName"));
        model.addAttribute("deptName", request.getSession().getAttribute("deptName"));
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        //打印分类集合
        List<Emr_Type> emrTypes = null;
        List<Zd_Assort> zdAssorts = null;
        int isDownload = 0;
        try {
            emrTypes = emrTypeService.selectAllByCreater(1, request);
            //病案分段集合
            zdAssorts = assortService.selectAllByPower(user);
            isDownload = apply_approveMapper.selectIsPowerByUser(user.getUserName(), patientId, 3);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("emrTypes", emrTypes);
        model.addAttribute("zdAssorts", zdAssorts);
        model.addAttribute("isDownload", isDownload);
        //查询是否有打印权限
        int printFlag = 0;
        int moveFlag = 0;
        Set<String> menus = user.getMenus();
        for (String menu : menus) {
            if (StringUtils.isNotBlank(menu)) {
                if ("/commom/printPdf".equals(menu)) {
                    printFlag = 1;
                }
                if ("/commom/movePdf".equals(menu)) {
                    moveFlag = 1;
                }
            }
        }
        model.addAttribute("moveFlag", moveFlag);
        model.addAttribute("printFlag", printFlag);
        model.addAttribute("flag", flag);
        return "recordManage/commomSearch/showRecordIframeSouth";
    }

    /**
     * 查看其它诊断
     *
     * @MethodName: getOtherDiagNameByAdmissTimesAndInpatientNo
     * @Description: 根据admissTimes和inpatientNo查询包含其他诊断名称的基本信息
     * @Param Integer admissTimes:住院次数,String inpatientNo：病案号
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-05
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-05
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getOtherDiagNameByAdmissTimesAndInpatientNo", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getOtherDiagNameByAdmissTimesAndInpatientNo(String name, Short admissTimes, String inpatientNo, String flag) {
        if (StringUtils.isNoneBlank(name) && admissTimes != null && StringUtils.isNoneBlank(inpatientNo)) {
            try {
                //根据病案号，住院次数，姓名查询对应的patientId
                List<String> patientIdList = commomMapper.selectPatientIdByAdmissTimesAndInpatientNoAndName(admissTimes, inpatientNo, name, null, null);
                String patientId = "";
                if (null != patientIdList && !patientIdList.isEmpty()) {
                    if (patientIdList.size() == 1) {
                        patientId = patientIdList.get(0);
                    } else {
                        return "查询结果不唯一,符合条件共计" + patientIdList.size() + "条";
                    }
                } else {
                    return "查询无该档案";
                }
                if (StringUtils.isNoneBlank(patientId)) {
                    List<CommomVo> commomVos = commomMapper.selectOtherDiagByPatientId(patientId, flag);
                    if (null != commomVos && !commomVos.isEmpty()) {
                        return JSON.toJSONString(commomVos.get(0));
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 脐血、祈福分类树
     *
     * @param patientId
     * @param typeId
     * @param request
     * @return
     */
    @RequestMapping(value = "getBloodRecordTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getBloodRecordTree(String patientId, Integer typeId, HttpServletRequest request) {
        List<CommomTree> treeList = new ArrayList<>();
        //查询该有的权限分类
        try {
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            List<CommomTree> commomVos = new ArrayList<>();
            if (user.getRoleId() == 0 || user.getRoleId() == -100 || user.getRoleId() == -999) {
                commomVos = commomMapper.selectScanPathByPatientId(patientId, null, null);
            } else {
                commomVos = commomMapper.selectScanPathByPatientId(patientId, user.getRoleId(), user.getUserId());
            }
            //按打印分类id查询归属分类集合
            List<Emr_Type_Related> typeRelateds = new ArrayList<>();
            if (typeId != null) {
                typeRelateds = typeRelatedService.selectAssortIdsByTypeId(typeId);
            }
            if (commomVos.size() > 0) {
                //第一级：全部影像资料
                CommomTree tree1 = new CommomTree();
                Integer id = 1;
                tree1.setId(id);
                tree1.setNewName("全部影像资料");
                if (null != commomVos && !commomVos.isEmpty()) {
                    //去重，取出不重复的分类集合
                    Map<String, CommomTree> assortMap = new LinkedHashMap<>();
                    for (CommomTree commomVo1 : commomVos) {
                        assortMap.put(commomVo1.getAssortId(), commomVo1);
                    }
                    //判断分类是否全选，全选，父类跟着全选
                    if (null != typeRelateds && !typeRelateds.isEmpty()) {
                        boolean checkedFlag = true;
                        for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                            //定义是否存在
                            boolean flag = false;
                            for (Emr_Type_Related typeRelated : typeRelateds) {
                                if (typeRelated.getAssortId().equals(map.getKey())) {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag) {
                                checkedFlag = false;
                                break;
                            }
                        }
                        if (checkedFlag) {
                            tree1.setChecked("true");
                        }
                    } else {
                        tree1.setChecked("true");
                    }
                    treeList.add(tree1);
                    int oneId = 0;
                    for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                        id++;
                        oneId = id;
                        String assortId = map.getValue().getAssortId();
                        CommomTree tree2 = new CommomTree();
                        tree2.setId(id);
                        tree2.setParentId(1);
                        tree2.setAssortId(map.getValue().getAssortId());
                        //判断选中
                        boolean checkFlag = false;
                        if (null != typeRelateds && !typeRelateds.isEmpty()) {
                            for (Emr_Type_Related typeRelated : typeRelateds) {
                                if (StringUtils.isNotBlank(assortId) && assortId.equals(typeRelated.getAssortId())) {
                                    tree2.setChecked("true");
                                    checkFlag = true;
                                    break;
                                }
                            }
                        } else {
                            checkFlag = true;
                            tree2.setChecked("true");
                        }
                        //定义该类影像图片数量
                        int scanPathCount = 0;
                        //第二层 图片
                        for (CommomTree commomVo : commomVos) {
                            if (StringUtils.isNotBlank(assortId) && StringUtils.isNotBlank(commomVo.getAssortId()) &&
                                    assortId.equals(commomVo.getAssortId())) {
                                id++;
                                CommomTree tree3 = new CommomTree();
                                tree3.setId(id);
                                tree3.setParentId(oneId);
                                tree3.setAssortId(assortId);
                                if (checkFlag) {
                                    tree3.setChecked("true");
                                }
                                scanPathCount++;
                                //图片名称
                                String name = commomVo.getScanPage();
                                tree3.setAssortName(name);
                                //设置树图片节点的名称
                                tree3.setNewName("(第" + scanPathCount + "页)" + name);
                                tree3.setSource(commomVo.getSource());
                                //存储水印图片
                                treeList.add(tree3);

                            }
                        }
                        tree2.setNewName(map.getValue().getAssortName() + "(" + scanPathCount + ")");
                        treeList.add(tree2);
                    }
                }
            }
            if (commomVos.size() == 0) {
                List<CommomTree> archiveDetail = archiveDetailMapper.selectPdfPathByPatient2(patientId);
                //第一级：全部影像资料
                CommomTree tree1 = new CommomTree();
                Integer id = 1;
                tree1.setId(id);
                tree1.setNewName("全部影像资料");
                if (null != archiveDetail && !archiveDetail.isEmpty()) {
                    //去重，取出不重复的分类集合
                    Map<String, CommomTree> assortMap = new LinkedHashMap<>();
                    for (CommomTree commomVo1 : archiveDetail) {
                        assortMap.put(commomVo1.getAssortId(), commomVo1);
                    }
                    //判断分类是否全选，全选，父类跟着全选
                    if (null != typeRelateds && !typeRelateds.isEmpty()) {
                        boolean checkedFlag = true;
                        for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                            //定义是否存在
                            boolean flag = false;
                            for (Emr_Type_Related typeRelated : typeRelateds) {
                                if (typeRelated.getAssortId().equals(map.getKey())) {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag) {
                                checkedFlag = false;
                                break;
                            }
                        }
                        if (checkedFlag) {
                            tree1.setChecked("true");
                        }
                    } else {
                        tree1.setChecked("true");
                    }
                    treeList.add(tree1);
                    int oneId = 0;
                    for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                        id++;
                        oneId = id;
                        String assortId = map.getValue().getAssortId();
                        CommomTree tree2 = new CommomTree();
                        tree2.setId(id);
                        tree2.setParentId(1);
                        tree2.setAssortId(map.getValue().getAssortId());
                        //判断选中
                        boolean checkFlag = false;
                        if (null != typeRelateds && !typeRelateds.isEmpty()) {
                            for (Emr_Type_Related typeRelated : typeRelateds) {
                                if (StringUtils.isNotBlank(assortId) && assortId.equals(typeRelated.getAssortId())) {
                                    tree2.setChecked("true");
                                    checkFlag = true;
                                    break;
                                }
                            }
                        } else {
                            checkFlag = true;
                            tree2.setChecked("true");
                        }
                        //定义该类影像图片数量
                        int scanPathCount = 0;
                        //第二层 图片
                        int scanPathCountNum = 0;
                        for (CommomTree commomVo : archiveDetail) {
                            if (StringUtils.isNotBlank(assortId) && StringUtils.isNotBlank(commomVo.getAssortId()) &&
                                    assortId.equals(commomVo.getAssortId())) {
                                id++;
                                CommomTree tree3 = new CommomTree();
                                tree3.setId(id);
                                tree3.setParentId(oneId);
                                tree3.setAssortId(assortId);
                                if (checkFlag) {
                                    tree3.setChecked("true");
                                }
                                scanPathCount++;
                                //图片名称
                                String name = commomVo.getScanPage();
                                tree3.setAssortName(name);
                                //设置树图片节点的名称
                                tree3.setNewName(commomVo.getTitle());
                                tree3.setSource(commomVo.getSource());
                                //存储水印图片
                                treeList.add(tree3);
                                scanPathCountNum = commomVo.getPageCount();


                            }
                        }
                        tree2.setNewName(map.getValue().getAssortName() + "(" + scanPathCountNum + ")");
                        treeList.add(tree2);
                    }
                }
            }
            return JSON.toJSONString(treeList);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 祈福打印预览前加载图片
     *
     * @param patientId
     * @param rootPaths
     * @param names
     * @param sources
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "selectPrintPic", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil selectPrintPic(HttpServletResponse response, String patientId, String rootPaths, String names, String sources, HttpServletRequest request) throws Exception {
        //生成加载进度mapKey
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String mapKey = user.getUserName() + "_" + patientId;
        List<String> outs = commomService.selectPrintPic(response, patientId, rootPaths, names, sources, mapKey);
        return ResultUtil.ok(outs);
    }


    @RequestMapping(value = "selectPrintPic2", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil selectPrintPic2(HttpServletResponse response, String patientId, String rootPaths, String names, String sources, HttpServletRequest request) throws Exception {
        //生成加载进度mapKey
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String mapKey = user.getUserName() + "_" + patientId;
        List<String> outs = commomService.selectPrintPic2(response, patientId, names, sources, mapKey);
        return ResultUtil.ok(outs);
    }


//    @RequestMapping("showPdf")
//    public void showPdf(String patientId, HttpServletRequest request, HttpServletResponse response) {
//        EmrPdfWaterSet emrPdfWaterSet = new EmrPdfWaterSet();
//        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
//        String mapKey = user.getUserName() + "_" + patientId;
//        List<String> fileList = (List<String>) request.getSession().getAttribute(mapKey);
//        String pdfWater = "儿童医院";
//        Jpg2PdfUtil.mulFile2One(response, fileList, pdfWater);
//    }

    /**
     * 南方太和医院打印预览前加载图片
     *
     * @param patientId
     * @param rootPaths
     * @param names
     * @param sources
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "selectPrintPicTh", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil selectPrintPicTh(String patientId, String rootPaths, String names, String sources, HttpServletRequest request) throws Exception {
        //生成加载进度mapKey
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String mapKey = user.getUserName() + "_" + patientId;
        List<String> outs = commomService.selectPrintPicTh(patientId, rootPaths, names, sources, mapKey);
        return ResultUtil.ok(outs);
    }


    @RequestMapping("getPrintPicLoading")
    @ResponseBody
    public ResultUtil getPrintPicLoading(String patientId, HttpServletRequest request) throws Exception {
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String mapKey = user.getUserName() + "_" + patientId;
        Integer loadingInteger = commomService.getPrintPicLoading(mapKey);
        return ResultUtil.ok(loadingInteger);
    }

    /**
     * 脐血库、祈福查看pdf
     *
     * @param patientId
     * @param scanPages
     * @param sources
     * @param flag
     * @param response
     */
    @RequestMapping(value = "showRecordContentBlood")
    @ResponseBody
    public ResultUtil showRecordContentBlood(String patientId, String scanPages, String sources, String flag, HttpServletResponse response, HttpServletRequest request) {
        try {
            commomService.showRecordContentBlood(patientId, scanPages, sources, flag, response, request);
            return ResultUtil.ok();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return ResultUtil.error("showRecordContentBlood查询文件出错了");
        }
    }

    @RequestMapping(value = "getRecordContentBlood")
    @ResponseBody
    public void getRecordContentBlood(String patientId, HttpServletRequest request, HttpServletResponse response) {
        List<CommomTree> commomTrees = archiveDetailMapper.selectPdfPathByPatient2(patientId);
        if (commomTrees.size() == 0) {
            try {
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                String mapKey = user.getUserName() + "_" + patientId;
                List<String> scanPages = (List<String>) request.getSession().getAttribute(mapKey);
                if (!CollectionUtils.isEmpty(scanPages)) {
                    String pdfName = "档案管理PDF";
                    //根据图片路径转换pdf
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);

                    //定义第二文本水印 姓名 + 科室 + ip
                    EmrPdfWaterSet emrPdfWaterSet1 = commomService.getEmrPdfWaterSet(emrPdfWaterSet);
                    //UserEffective为1是开启用户信息水印
                    Short userEffective = emrPdfWaterSet.getUserEffective();
                    if (userEffective==1){
                        img2PdfUtil.imageToPdf(response, scanPages, pdfName, emrPdfWaterSet, emrPdfWaterSet1);
                    }else {
                        img2PdfUtil.imageToPdfUserEffective(response, scanPages, pdfName, emrPdfWaterSet);
                    }
                    //移除缓存
                    request.removeAttribute(mapKey);
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        } else {
            String pdfWater = "";
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String mapKey = user.getUserName() + "_" + patientId;
            List<String> filePaths = (List<String>) request.getSession().getAttribute(mapKey);
            if (!CollectionUtils.isEmpty(filePaths)) {
                //根据图片路径转换pdf
                EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                //定义第二文本水印 姓名 + 科室 + ip
                EmrPdfWaterSet emrPdfWaterSet1 = commomService.getEmrPdfWaterSet(emrPdfWaterSet);
                Jpg2PdfUtil.mulFile2One2(response, filePaths, pdfWater,emrPdfWaterSet);
                //移除缓存
                request.removeAttribute(mapKey);
            }

        }
    }

    /**
     * 南方医院访问
     *
     * @param patientId
     * @param userName
     * @param scanPages
     * @param sources
     * @param flag
     * @param response
     */
    @RequestMapping(value = "showRecordContentSouth")
    @ResponseBody
    public void showRecordContentSouth(String patientId, String userName, String deptName, String scanPages, String sources, String flag, HttpServletResponse response, HttpServletRequest request) {
        try {
            userName = (String) request.getSession().getAttribute("userName");
            deptName = (String) request.getSession().getAttribute("deptName");
            commomService.showRecordContentSouth(patientId, userName, deptName, scanPages, sources, flag, response);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }

    /**
     * 脐血库、祈福
     *
     * @MethodName: updateScanAssortByBlood
     * @Description: 重新分页
     * @Param String patientId,String assortIds:病案图片集合,newAssortId新的分类id
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-03-09
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-03-09
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/updateScanAssort")
    @OptionalLog(module = "修改", methods = "档案预览页面病案图片重新分类", fieldName = "name", tableName = "commomtable")
    @RequestMapping(value = "updateScanAssortByBlood", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil updateScanAssortByBlood(CommomVo commomVo, String assortIds, String newAssortId) throws Exception {
        if (StringUtils.isNoneBlank(commomVo.getPatientId()) && StringUtils.isNoneBlank(assortIds) && StringUtils.isNoneBlank(newAssortId)) {
            //根据patientId，admissIds(scanPage分类图片集合)批量更新分段id assrotdId
            //组织picNames
            StringBuilder picNameStr = new StringBuilder();
            String[] picNames = assortIds.split(",");
            for (String picName : picNames) {
                if (StringUtils.isNotBlank(picName)) {
                    picNameStr.append("'").append(picName).append("',");
                }
            }
            picNameStr = new StringBuilder(picNameStr.substring(0, picNameStr.length() - 1));
            //批量更新
            scanAssortService.SimpleUpdateByPatientIdAndScanPages(commomVo.getPatientId(), newAssortId, picNameStr.toString());
            return ResultUtil.ok();
        }
        return null;
    }

    /*****************************病案图片操作****************************/
    @OptionalLog(module = "保存", methods = "图片资料", fieldName = "name", tableName = "commomtable")
    @RequiresPermissions("/commom/updatePic")
    @RequestMapping(value = "updatePic", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil updatePic(CommomVo commomVo, @RequestParam(required = false, value = "files") MultipartFile[] files, String assortId) throws Exception {
        ResultUtil resultUtil = commomService.updatePic(files, commomVo.getPatientId(), assortId);
        if (!resultUtil.getCode().equals(0)) {
            return resultUtil;
        }
        return ResultUtil.ok();
    }

    /**
     * @MethodName: delScanAssortByBlood
     * @Description: 删除图片
     * @Param String patientId,String assortIds:病案图片集合
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-03-09
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-03-09
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/delScanAssort")
    @OptionalLog(module = "删除", methods = "档案预览页面删除病案图片", fieldName = "name", tableName = "commomtable")
    @RequestMapping(value = "delScanAssortByBlood", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil delScanAssortByBlood(String patientId) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String assortIds = request.getParameter("assortIds");
        if (StringUtils.isNoneBlank(patientId) && StringUtils.isNoneBlank(assortIds)) {
            scanAssortService.SimpleDelByPatientIdAndScanPages(patientId, assortIds);
            return ResultUtil.ok();
        }
        return null;
    }

    /**************************恢复已删除图片开始*************************/
    /**
     * @MethodName: getDeledPicRecordTree
     * @Description: 组织已删除图片的病案分类树
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-06-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-06-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("selectDeledPicRecordTree")
    @ResponseBody
    public List<ScanDeledAssortTree> selectDeledPicRecordTree(String patientId, String flag) {
        List<ScanDeledAssortTree> treeList = new ArrayList<>();
        //根据patientId查询已删除图片集合
        try {
            List<ScanAssortVo> scanAssortVos = scanAssortMapper.selectDeledPicList(patientId, flag);
            //第一级：全部影像资料
            ScanDeledAssortTree tree1 = new ScanDeledAssortTree();
            Integer id = 1;
            tree1.setId(id);
            tree1.setName("全部影像资料(" + scanAssortVos.size() + ")");
            tree1.setCount(scanAssortVos.size());
            //定义图片集合
            StringBuilder scanPathList = new StringBuilder();
            //定义绝对路径集合
            StringBuilder srcs = new StringBuilder();
            //定义分类名称集合
            StringBuilder assortNames = new StringBuilder();
            if (!scanAssortVos.isEmpty()) {
                //定义图片分类不重复结合
                Set<String> assortNameSet = new LinkedHashSet<>();
                for (ScanAssortVo scanAssort : scanAssortVos) {
                    if (StringUtils.isNotBlank(scanAssort.getAssortName())) {
                        assortNameSet.add(scanAssort.getAssortName());
                        scanPathList.append(scanAssort.getScanPage()).append(",");
                        srcs.append(scanAssort.getRootPath()).append("\\").append(scanAssort.getScanPage()).append(",");
                        assortNames.append(scanAssort.getAssortName()).append(",");
                    }
                }
                //设置图片名称集合
                tree1.setScanPageList(scanPathList.toString());
                tree1.setSrcs(srcs.toString());
                tree1.setAssortNames(assortNames.toString());
                treeList.add(tree1);
                for (String assortName : assortNameSet) {
                    id++;
                    ScanDeledAssortTree tree2 = new ScanDeledAssortTree();
                    tree2.setId(id);
                    tree2.setParentId(1);
                    //定义图片集合
                    StringBuilder scanPathList1 = new StringBuilder();
                    StringBuilder srcs1 = new StringBuilder();
                    //定义分类图片的个数
                    Integer count = 0;
                    for (ScanAssortVo scanAssort : scanAssortVos) {
                        if (StringUtils.isNotBlank(scanAssort.getAssortName())) {
                            if (scanAssort.getAssortName().equals(assortName)) {
                                scanPathList1.append(scanAssort.getScanPage()).append(",");
                                srcs1.append(scanAssort.getRootPath()).append("\\").append(scanAssort.getScanPage()).append(",");
                                count++;
                            }
                        }
                    }
                    tree2.setName(assortName + "(" + count + ")");
                    tree2.setCount(count);
                    tree2.setScanPageList(scanPathList1.toString());
                    tree2.setSrcs(srcs1.toString());
                    tree2.setAssortNames(assortName);
                    treeList.add(tree2);
                }
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return treeList;
    }

    /**
     * @MethodName: getDeledPicRecordTree
     * @Description: 组织已删除图片的病案分类树
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-06-08
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-06-08
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "修改", methods = "恢复已删除图片", fieldName = "name", tableName = "commomtable")
    @RequiresPermissions("/commom/recoverPic")
    @RequestMapping(value = "recoverPic", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil recoverPic(CommomVo commomVo, String scanPages) throws Exception {
        scanAssortService.recoverPic(commomVo.getPatientId(), scanPages);
        return ResultUtil.ok();
    }
    /**************************恢复已删除图片结束***********************/
    /**************************病案维护开始*****************************/
    /**
     * 祈福医院病案修改
     *
     * @param commomVo
     * @return
     * @throws Exception
     */
    @RequiresPermissions("/commom/updateCommomInfo")
    @OptionalLog(module = "保存", methods = "病案信息修改")
    @RequestMapping("updateCommomInfo")
    @ResponseBody
    public ResultUtil updateCommomInfo(CommomVo commomVo) throws Exception {
        if (null != commomVo.getInpatientNo()) {
            int vo = commomMapper.selectCountByPatients(commomVo.getPatientId());
            if (vo > 0) {
                int i = commomMapper.updateByPrimaryKeySelective(commomVo);
                if (i > 0) {
                    return ResultUtil.ok();
                } else {
                    return ResultUtil.error("修改失败!");
                }
            } else {
                return ResultUtil.error("修改失败,该病案主键不存在!");
            }
        } else {
            return ResultUtil.error("修改失败,主键不能为空!");
        }
    }

    /**************************病案维护结束*****************************/
    /******************************编码操作******************************/
    /**
     * @MethodName: getDiagCodeContents
     * @Description: 根据icd编码查询诊断对象集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-03
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-03
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getDiagCodeContents", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getDiagCodeContents(String code, String name) {
        try {
            List<Zd_Icd_Code> icdCodes = new ArrayList<>();
            if (StringUtils.isNotBlank(code)) {
                icdCodes = icdCodeMapper.selectAll(code, null);
            } else {
                icdCodes = icdCodeMapper.selectAll(null, name);
            }
            Map<String, String> map = new HashMap<>();
            if (null != icdCodes && !icdCodes.isEmpty()) {
                for (Zd_Icd_Code icdCode : icdCodes) {
                    if (StringUtils.isNoneBlank(icdCode.getCode())) {
                        map.put(icdCode.getCode(), icdCode.getName());
                    }
                }
            }
            return JSON.toJSONString(map);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * getOperateCodeContents
     *
     * @MethodName:
     * @Description: 根据手术编码查询手术对象集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-03
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-03
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getOperateCodeContents", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getOperateCodeContents(String code, String name) {
        try {
            List<Zd_Cm3> zdCm3s = new ArrayList<>();
            if (StringUtils.isNotBlank(code)) {
                zdCm3s = cm3Mapper.selectAll(code, null);
            } else {
                zdCm3s = cm3Mapper.selectAll(null, name);
            }
            Map<String, String> map = new HashMap<>();
            if (null != zdCm3s && !zdCm3s.isEmpty()) {
                for (Zd_Cm3 zdCm3 : zdCm3s) {
                    if (StringUtils.isNoneBlank(zdCm3.getCode())) {
                        map.put(zdCm3.getCode(), zdCm3.getName());
                    }
                }
            }
            return JSON.toJSONString(map);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getDictionaryByTypeCode
     * @Description: 根据字典标识查询字典集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getDictionaryByTypeCode", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getDictionaryByTypeCode(String typeCode) throws Exception {
        List<Emr_Dictionary> dictionaries = dictionaryMapper.selectDictionaryByTypeCode(typeCode);
        return JSON.toJSONString(dictionaries);
    }

    /**
     * @MethodName: getIcdCodeList
     * @Description: 加载icd编码字典表
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getIcdCodeList", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getIcdCodeList() throws Exception {
        List<Zd_Icd_Code> icdCodes = icdCodeMapper.selectAll(null, null);
        return JSON.toJSONString(icdCodes);
    }

    //阿拉伯数字转中文
    private static String toChinese(String str) {
        String[] s1 = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        String[] s2 = {"十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"};
        StringBuilder result = new StringBuilder();
        int n = str.length();
        for (int i = 0; i < n; i++) {
            int num = str.charAt(i) - '0';
            if (i != n - 1 && num != 0) {
                result.append(s1[num]).append(s2[n - 2 - i]);
            } else {
                result.append(s1[num]);
            }
        }
        return result.toString();
    }
}
