package com.emr.controller.commomSearch;

import com.alibaba.fastjson.JSON;
import com.ctc.wstx.util.StringUtil;
import com.emr.annotation.OptionalLog;
import com.emr.controller.FormTokenFlagUtil;
import com.emr.dao.*;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.dao.commomSearch.ScanPathMapper;
import com.emr.dao.emrCodeType.Emr_Code_TypeMapper;
import com.emr.dao.emrPdfWaterSet.EmrPdfWaterSetMapper;
import com.emr.dao.tScanAssort.T_Scan_AssortMapper;
import com.emr.dao.zdDictionary.ZdDeptCodeMapper;
import com.emr.dao.zdDictionary.ZdDisDiagStatusMapper;
import com.emr.entity.*;
import com.emr.entity.emrCode.T_Diag;
import com.emr.entity.emrCode.T_Herb_Diag;
import com.emr.entity.emrCode.T_Operate;
import com.emr.entity.emrCodeType.Emr_Code_Type;
import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.entity.recordType.Emr_Type;
import com.emr.entity.recordType.Emr_Type_Related;
import com.emr.entity.tScanAssort.T_Scan_Assort;
import com.emr.service.Zd_AssortServiceImpl;
import com.emr.service.emrCode.DiagService;
import com.emr.service.emrCode.HerbDiagService;
import com.emr.service.emrCode.OperateService;
import com.emr.service.emrCodeType.EmrCodeTypeService;
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.FieldPropertyConvert;
import com.emr.util.Jpg2PdfUtil;
import com.emr.util.PropertiesUtils;
import com.emr.util.img2PdfUtil;
import com.emr.vo.EmrPrintOrDownLoadInfo.EmrPrintOrDownLoadInfoVo;
import com.emr.vo.FontVo.FontCommom;
import com.emr.vo.FontVo.ScanAssortVo;
import com.emr.vo.codeType.CodeTree;
import com.emr.vo.commomSearch.CommomTree;
import com.emr.vo.commomSearch.CommomVo;
import com.emr.vo.commomSearch.ScanPathVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lowagie.text.Image;
import com.lowagie.text.Utilities;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.codec.TiffImage;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
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 {
    @Value("${pdfWater}")
    private String pdfWater;
    Logger logger = LoggerFactory.getLogger(CommomSearchController.class);
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private EmrTypeRelatedService typeRelatedService;
    @Autowired
    private ScanPathMapper scanPathMapper;
    @Autowired
    private T_Scan_AssortService scanAssortService;
    @Autowired
    private EmrCodeTypeService codeTypeService;
    @Autowired
    private OperateService operateService;
    @Autowired
    private DiagService diagService;
    @Autowired
    private HerbDiagService herbDiagService;
    @Autowired
    private Zd_Cm3Mapper cm3Mapper;
    @Autowired
    private Zd_Icd_CodeMapper icdCodeMapper;
    @Autowired
    private Emr_Code_TypeMapper codeTypeMapper;
    @Autowired
    private Archive_DetailMapper archiveDetailMapper;
    @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 EmrPdfWaterSetMapper pdfWaterSetMapper;
    @Autowired
    private ZdDeptCodeMapper deptCodeMapper;
    @Autowired
    private ZdDisDiagStatusMapper disDiagStatusMapper;
    /**
     * @MethodName commomList
     * @Description: 跳转到常用查询页面
     * @Param 无
     * @Returnt commomSearch/commomList
     * @Author: 曾文和
     * @CreateDate: 2019-05-28
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-28
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/commomList")
    @OptionalLog(module="查看", methods="常用查询页面")
    @RequestMapping("commomList")
    public String commomList() {
        return "recordManage/commomSearch/commomList";
    }
    //脐血库
    @RequiresPermissions("/commom/commomList1")
    @OptionalLog(module="查看", methods="常用查询页面")
    @RequestMapping("commomList1")
    public String commomList1() {
        return "recordManage/commomSearch/commomList1";
    }
    //174医院
    @RequiresPermissions("/commom/commomList174")
    @OptionalLog(module="查看", methods="常用查询页面")
    @RequestMapping("commomList174")
    public String commomList174() {
        return "recordManage/commomSearch/commomList174";
    }
    //祈福医院
    @RequiresPermissions("/commom/commomListqf")
    @OptionalLog(module="查看", methods="常用查询页面")
    @RequestMapping("commomListqf")
    public String commomListqf() {
        return "recordManage/commomSearch/commomListqf";
    }

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

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

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

    @RequestMapping("getDept174")
    @ResponseBody
    public String getDept174() {
        try {
            //加载科室集合
            return JSON.toJSONString(deptCodeMapper.selectAll());
        } catch (Exception 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) {
            e.printStackTrace();
            return null;
        }
    }
    /*******************************************病案预览操作*********************************************************/

    //加载转归情况
    @RequestMapping("getDiagStatus174")
    @ResponseBody
    public String getDiagStatus174() {
        try {
            //加载病状转归集合
            return JSON.toJSONString(disDiagStatusMapper.selectAll());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: showRecord
     * @Description: 跳转到病案预览
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "查看", methods = "病案预览页面")
    @RequestMapping("showRecord")
    public String showRecord(String patientId, Model model, HttpServletRequest request) {
        try {
            model.addAttribute("patientId", patientId);
            //加载登陆者
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            model.addAttribute("user", user);
            model.addAttribute("roleId", user.getRoleId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "recordManage/commomSearch/showRecord";
    }

    /**
     * @MethodName: showRecordBlood
     * @Description: 跳转到档案预览
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "查看", methods = "档案预览页面")
    @RequestMapping("showRecordBlood")
    public String showRecordBlood(String patientId, Model model, HttpServletRequest request) {
        try {
            model.addAttribute("patientId", patientId);
            //加载登陆者
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            model.addAttribute("user", user);
            model.addAttribute("roleId", user.getRoleId());
            List<EmrPrintOrDownLoadInfoVo> printCount = printOrDownLoadInfoService.getPrintCount(patientId);
            if (null != printCount && !printCount.isEmpty()) {
                model.addAttribute("printCount", 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "recordManage/commomSearch/showRecordBlood";
    }

    /**
     * @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) {
        try {
            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 = printOrDownLoadInfoService.getPrintCount(patientId);
            if (null != printCount && !printCount.isEmpty()) {
                model.addAttribute("printCount", 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "recordManage/commomSearch/showRecord174";
    }

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

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

    /**
     * 加载上传图片的分类
     */
    @RequestMapping("getAssortList")
    @ResponseBody
    public ResultUtil getAssortList(HttpServletRequest request) {
        try {
            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);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("查询图片分类出错了,请联系系统管理员!");
        }
    }

    /**
     * @MethodName: showRecordIframe
     * @Description: 病案预览Iframe, 按住院次数显示页面
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-04
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-04
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("showRecordIframe")
    public String showRecordIframe(String patientId, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        //打印分类集合
        List<Emr_Type> emrTypes = emrTypeService.selectAllByCreater(1, request);
        model.addAttribute("emrTypes", emrTypes);
        //病案分段集合
        //TODO 重新分页注释
       /* 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());
        }
        model.addAttribute("zdAssorts",zdAssorts);*/
        model.addAttribute("user", user);
        return "recordManage/commomSearch/showRecordIframe";
    }

    //脐血库
    @RequestMapping("showRecordIframeBlood")
    public String showRecordIframeBlood(String patientId, String flag, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        model.addAttribute("flag", flag);
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        //打印分类集合
        List<Emr_Type> emrTypes = emrTypeService.selectAllByCreater(1, request);
        model.addAttribute("emrTypes", emrTypes);
        //病案分段集合
        //TODO 重新分页注释
        List<Zd_Assort> zdAssorts = assortService.selectAllByPower(user);
        model.addAttribute("zdAssorts", zdAssorts);
        int isDownload = apply_approveMapper.selectIsPowerByUser(user.getUserName(), patientId, 3);
        model.addAttribute("isDownload", isDownload);
        //查询是否有打印权限
        Integer printFlag = 0;
        Set<String> menus = user.getMenus();
        for (String menu : menus) {
            if (StringUtils.isNotBlank(menu)) {
                if ("/commom/printPdf".equals(menu)) {
                    printFlag = 1;
                    break;
                }
            }
        }
        model.addAttribute("printFlag", printFlag);
        return "recordManage/commomSearch/showRecordIframeBlood";
    }

    //查询分段集合
    @RequestMapping("selectIsPowerByUser")
    @ResponseBody
    public String selectIsPowerByUser(HttpServletRequest request) {
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<Zd_Assort> zdAssorts = assortService.selectAllByPower(user);
        return JSON.toJSONString(zdAssorts);
    }

    //脐血库
    //获取病案图片根路径
    @RequestMapping("getFilePath")
    @ResponseBody
    public ResultUtil getFilePath(String patientId) {
        try {
            CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
            return ResultUtil.ok(commomVo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("出错了,请联系系统管理员!");
        }
    }

    /**
     * @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 startTime2) {
        if (StringUtils.isNoneBlank(name) && admissTimes != null && StringUtils.isNoneBlank(inpatientNo)) {
            try {
                if (StringUtils.isNotBlank(startTime2)) {
                    startTime2 = startTime2.substring(0, 10);
                }
                //根据病案号，住院次数，姓名查询对应的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);
                    try {
                        if (null != commomVos && !commomVos.isEmpty()) {
                            ObjectMapper mapper = new ObjectMapper();
                            String json = mapper.writeValueAsString(commomVos.get(0));
                            return json;
                        } else {
                            return null;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //脐血库

    /**
     * @MethodName: getRecordTypeTree
     * @Description: 根据patientId组织病案分类集合树
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-04
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-04
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getRecordTypeTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getRecordTypeTree(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) {
                commomVos = commomMapper.selectScanCountByMedicalPatientId(patientId, null, null);
            } else {
                commomVos = commomMapper.selectScanCountByMedicalPatientId(patientId, user.getRoleId(), user.getUserId());
            }
            //归档不表不存在，查病案数据表
            //从归档查type为1
            int type = 1;
            if (null == commomVos || commomVos.isEmpty()) {
                if (user.getRoleId() == 0 || user.getRoleId() == -100) {
                    commomVos = commomMapper.selectScanCountByPatientId(patientId, null, null);
                } else {
                    commomVos = commomMapper.selectScanCountByPatientId(patientId, user.getRoleId(), user.getUserId());
                }
                type = 2;
            }
            //返回每个分段pdf页数
            if (null != commomVos && !commomVos.isEmpty()) {
                Map<String, Integer> map = setPdfPageWithAssorts(patientId, type);
                for (int i = 0; i < commomVos.size(); i++) {
                    for (Map.Entry<String, Integer> entry : map.entrySet()) {
                        if (StringUtils.isNotBlank(commomVos.get(i).getAssortId()) && commomVos.get(i).getAssortId().equals(entry.getKey())) {
                            commomVos.get(i).setAssortCount(entry.getValue());
                            continue;
                        }
                    }
                }
            }
            //按打印分类id查询归属分类集合
            List<Emr_Type_Related> typeRelateds = new ArrayList<>();
            if (typeId != null) {
                typeRelateds = typeRelatedService.selectAssortIdsByTypeId(typeId);
            }
            //第一级：全部影像资料
            CommomTree tree1 = new CommomTree();
            Integer id = 1;
            tree1.setId(id);
            tree1.setAssortName("全部影像资料");
            treeList.add(tree1);
            if (null != commomVos && !commomVos.isEmpty()) {
                for (int i = 0; i < commomVos.size(); i++) {
                    id++;
                    CommomTree tree2 = new CommomTree();
                    tree2.setId(id);
                    tree2.setParentId(1);
                    tree2.setAssortName(commomVos.get(i).getAssortName() + "(" + commomVos.get(i).getAssortCount() + ")");
                    tree2.setAssortId(commomVos.get(i).getAssortId());
                    //判断选中
                    if (null != typeRelateds && !typeRelateds.isEmpty()) {
                        for (int j = 0; j < typeRelateds.size(); j++) {
                            if (StringUtils.isNotBlank(commomVos.get(i).getAssortId()) && commomVos.get(i).getAssortId().equals(typeRelateds.get(j).getAssortId())) {
                                tree2.setChecked("true");
                                break;
                            }
                        }
                    }
                    treeList.add(tree2);
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(treeList);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getRecordTree
     * @Description: 根据patientId组织病案集合树
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-04
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-04
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getRecordTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getRecordTree(String patientId, Integer typeId, HttpServletRequest request) {
        long start = System.currentTimeMillis();
        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) {
                commomVos = commomMapper.selectScanCountByMedicalPatientId(patientId, null, null);
            } else {
                commomVos = commomMapper.selectScanCountByMedicalPatientId(patientId, user.getRoleId(), user.getUserId());
            }
            //归档不表不存在，查病案数据表
            //从归档查type为1
            int type = 1;
            if (null == commomVos || commomVos.isEmpty()) {
                if (user.getRoleId() == 0 || user.getRoleId() == -100) {
                    commomVos = commomMapper.selectScanPathByPatientId(patientId, null, null);
                } else {
                    commomVos = commomMapper.selectScanPathByPatientId(patientId, user.getRoleId(), user.getUserId());
                }
                type = 2;
            }
            long end = System.currentTimeMillis();
            System.out.println((end - start) / 1000 + "s");
            //按打印分类id查询归属分类集合
            List<Emr_Type_Related> typeRelateds = new ArrayList<>();
            if (typeId != null) {
                typeRelateds = typeRelatedService.selectAssortIdsByTypeId(typeId);
            }

            //第一级：全部影像资料
            CommomTree tree1 = new CommomTree();
            Integer id = 1;
            tree1.setId(id);
            tree1.setAssortName("全部影像资料");
            if (null != commomVos && !commomVos.isEmpty()) {
                //去重，取出不重复的分类集合
                Map<String, CommomTree> assortMap = new LinkedHashMap<>();
                for (int i = 0; i < commomVos.size(); i++) {
                    assortMap.put(commomVos.get(i).getAssortId(), commomVos.get(i));
                }
                //判断分类是否全选，全选，父类跟着全选
                if (null != typeRelateds && !typeRelateds.isEmpty()) {
                    Boolean checkedFlag = true;
                    for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                        //定义是否存在
                        Boolean flag = false;
                        for (int i = 0; i < typeRelateds.size(); i++) {
                            if (typeRelateds.get(i).getAssortId().equals(map.getKey())) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            checkedFlag = false;
                            break;
                        }
                    }
                    if (checkedFlag) {
                        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 (int j = 0; j < typeRelateds.size(); j++) {
                            if (StringUtils.isNotBlank(assortId) && assortId.equals(typeRelateds.get(j).getAssortId())) {
                                tree2.setChecked("true");
                                checkFlag = true;
                                break;
                            }
                        }
                    }
                    //定义该类影像图片数量
                    int scanPathCount = 0;
                    //第二层 图片
                    for (int i = 0; i < commomVos.size(); i++) {
                        if (StringUtils.isNotBlank(assortId) && StringUtils.isNotBlank(commomVos.get(i).getAssortId()) &&
                                assortId.equals(commomVos.get(i).getAssortId())) {
                            id++;
                            CommomTree tree3 = new CommomTree();
                            tree3.setId(id);
                            tree3.setParentId(oneId);
                            tree3.setAssortId(assortId);
                            if (checkFlag) {
                                tree3.setChecked("true");
                            }
                            tree3.setAssortName(commomVos.get(i).getScanPage());
                            treeList.add(tree3);
                            scanPathCount++;
                        }
                    }
                    tree2.setAssortName(map.getValue().getAssortName() + "(" + scanPathCount + ")");
                    treeList.add(tree2);
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(treeList);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //脐血库
    @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 (null == commomVos || commomVos.isEmpty()) {
                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);
            }
            //第一级：全部影像资料
            CommomTree tree1 = new CommomTree();
            Integer id = 1;
            tree1.setId(id);
            tree1.setAssortName("全部影像资料");
            if (null != commomVos && !commomVos.isEmpty()) {
                //去重，取出不重复的分类集合
                Map<String, CommomTree> assortMap = new LinkedHashMap<>();
                for (int i = 0; i < commomVos.size(); i++) {
                    assortMap.put(commomVos.get(i).getAssortId(), commomVos.get(i));
                }
                //判断分类是否全选，全选，父类跟着全选
                if (null != typeRelateds && !typeRelateds.isEmpty()) {
                    Boolean checkedFlag = true;
                    for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                        //定义是否存在
                        Boolean flag = false;
                        for (int i = 0; i < typeRelateds.size(); i++) {
                            if (typeRelateds.get(i).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 (int j = 0; j < typeRelateds.size(); j++) {
                            if (StringUtils.isNotBlank(assortId) && assortId.equals(typeRelateds.get(j).getAssortId())) {
                                tree2.setChecked("true");
                                checkFlag = true;
                                break;
                            }
                        }
                    } else {
                        checkFlag = true;
                        tree2.setChecked("true");
                    }
                    //定义该类影像图片数量
                    int scanPathCount = 0;
                    //第二层 图片
                    for (int i = 0; i < commomVos.size(); i++) {
                        if (StringUtils.isNotBlank(assortId) && StringUtils.isNotBlank(commomVos.get(i).getAssortId()) &&
                                assortId.equals(commomVos.get(i).getAssortId())) {
                            id++;
                            CommomTree tree3 = new CommomTree();
                            tree3.setId(id);
                            tree3.setParentId(oneId);
                            tree3.setAssortId(assortId);
                            if (checkFlag) {
                                tree3.setChecked("true");
                            }
                            tree3.setAssortName(commomVos.get(i).getScanPage());
                            treeList.add(tree3);
                            scanPathCount++;
                        }
                    }
                    tree2.setAssortName(map.getValue().getAssortName() + "(" + scanPathCount + ")");
                    treeList.add(tree2);
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(treeList);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Map<String, Integer> setPdfPageWithAssorts(String patientId, int type) throws Exception {
        //定义分段map
        Map<String, Integer> map = new HashMap<>();
        //计算pdf的条数
        if (type == 1) {
            List<Archive_Detail> archive_details = archiveDetailMapper.selectPdfCountByMasterId(patientId);
            if (null != archive_details && !archive_details.isEmpty()) {
                for (int i = 0; i < archive_details.size(); i++) {
                    String pdfPath = archive_details.get(i).getPdfPath();
                    int count = 0;
                    if (StringUtils.isNoneBlank(pdfPath)) {
                        String[] pdfPaths = pdfPath.split(",");
                        for (String pdfFile : pdfPaths) {
                            if (StringUtils.isNotBlank(pdfFile)) {
                                File file = new File(pdfFile);
                                if (file.isFile()) {
                                    boolean flag = Jpg2PdfUtil.check(pdfFile);
                                    if (flag) {
                                        PdfReader pdfReader = new PdfReader(new FileInputStream(pdfFile));
                                        int pages = pdfReader.getNumberOfPages();
                                        count += pages;
                                    }
                                }

                            }
                        }
                    }
                    map.put(archive_details.get(i).getAssortid(), count);
                }
            }
            return map;
        } else {
            //计算病案数据的页数
            FontCommom commom = new FontCommom();
            commom.setPatientId(patientId);
            List<ScanAssortVo> scanAssortVos = scanAssortMapper.seleteScanAssortPath(commom);
            if (null != scanAssortVos && !scanAssortVos.isEmpty()) {
                for (int j = 0; j < scanAssortVos.size(); j++) {
                    if (StringUtils.isNotBlank(scanAssortVos.get(j).getFilePath()) && StringUtils.isNotBlank(scanAssortVos.get(j).getScanPage())) {
                        String[] pages = scanAssortVos.get(j).getScanPage().split(",");
                        // 实例化图片
                        Image image = null;
                        //不成张合成的高度
                        float tempHeight = 0;
                        Integer pageCount = 0;
                        for (String filePath : pages) {
                            if (StringUtils.isNotBlank(filePath)) {
                                filePath = scanAssortVos.get(j).getFilePath() + "\\" + filePath;
                                File file1 = new File(filePath);
                                if (file1.exists()) {
                                    if (file1.getName().endsWith(".tif") || file1.getName().endsWith(".tiff")) {
                                        Object localObject1 = null;
                                        Object localObject2 = null;
                                        URL paramURL = Utilities.toURL(filePath);
                                        try {
                                            if (paramURL.getProtocol().equals("file")) {
                                                localObject2 = paramURL.getFile();
                                                localObject2 = Utilities
                                                        .unEscapeURL((String) localObject2);
                                                localObject1 = new RandomAccessFileOrArray(
                                                        (String) localObject2);
                                            } else {
                                                localObject1 = new RandomAccessFileOrArray(paramURL);
                                            }

                                            int pageNums = TiffImage
                                                    .getNumberOfPages((RandomAccessFileOrArray) localObject1);
                                            if (pageNums > 0) {
                                                for (int i = 1; i <= pageNums; i++) {
                                                    localObject2 = TiffImage.getTiffImage(
                                                            (RandomAccessFileOrArray) localObject1, i);
                                                    image = (Image) localObject2;
                                                }
                                            }
                                            if (localObject1 != null)
                                                ((RandomAccessFileOrArray) localObject1).close();

                                        } finally {
                                            if (localObject1 != null)
                                                ((RandomAccessFileOrArray) localObject1).close();
                                        }
                                    } else if (file1.getName().endsWith(".png")
                                            || file1.getName().endsWith(".jpg")
                                            || file1.getName().endsWith(".gif")
                                            || file1.getName().endsWith(".jpeg")
                                    ) {
                                        // 实例化图牿
                                        image = Image.getInstance(filePath);
                                    }
                                    // 获得图片的高庿
                                    float heigth = image.getHeight();
                                    float width = image.getWidth();
                                    // 合理压缩，h>w，按w压缩，否则按w压缩
                                    int percent = Jpg2PdfUtil.getPercent(heigth, width);

                                    // 设置图片居中显示
                                    image.setAlignment(Image.ALIGN_CENTER);
                                    // 按百分比显示图片的比便
                                    if (width > 1024 || heigth > 786) {
                                        image.scalePercent(percent + 5);
                                        pageCount++;
                                        //整张，把合成的高度置为0；
                                        tempHeight = 0;
                                    } else if (heigth < 786) {
                                        if (tempHeight == 0) {
                                            pageCount++;
                                        }
                                        tempHeight += heigth;
                                        if (tempHeight > 786) {
                                            pageCount++;
                                            tempHeight = heigth;
                                        }
                                    }
                                }
                            }
                        }
                        map.put(scanAssortVos.get(j).getAssortId(), pageCount);
                    }
                }
            }
            return map;
        }
    }

    /**
     * @MethodName: showRecordContent
     * @Description: 显示病案pdf内容，加载pdf
     * @Param String patientId:patientId String assortIds:病案分段id集合
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-06
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-06
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "showRecordContent/{patientId}/{assortIds}", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void showRecordContent(@PathVariable("patientId") String patientId, @PathVariable("assortIds") String assortIds, HttpServletResponse response) {
        if (StringUtils.isNoneBlank(patientId)) {
            String pdfName = "数字病案PDF";
            patientId = "'" + patientId + "'";
            try {
                //查询归档的病案是否存在
                List<Archive_Detail> pdfPathList = archiveDetailMapper.selectPdfPathByPatient(patientId, assortIds);
                if (null != pdfPathList && !pdfPathList.isEmpty()) {
                    List<String> fileList = new ArrayList<>();
                    for (int i = 0; i < pdfPathList.size(); i++) {
                        String pdfPath = pdfPathList.get(i).getPdfPath();
                        if (StringUtils.isNotBlank(pdfPath)) {
                            fileList.add(pdfPath);
                        }
                    }
                    Jpg2PdfUtil.mulFile2One(response, fileList, pdfWater);
                } else {
                    //否则话读取图片集合
                    //根据patient和分类集合查询图片地址对象集合
                    List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByPatientIds(patientId, assortIds);
                    //组织图片地址集合
                    List<String> filePaths = new ArrayList<>();
                    if (null != scanPathVos && !scanPathVos.isEmpty()) {
                        for (int i = 0; i < scanPathVos.size(); i++) {
                            String fileRealPath = scanPathVos.get(i).getFileRealPath();
                            if (StringUtils.isNoneBlank(fileRealPath)) {
                                File file = new File(fileRealPath);
                                if (file.isFile()) {
                                    filePaths.add(fileRealPath);
                                }
                            }
                        }
                        if (null != filePaths && !filePaths.isEmpty()) {
                            //根据图片路径转换pdf
                            EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                            img2PdfUtil.imageToPdf(response, filePaths, pdfName, emrPdfWaterSet);
                        }
                    }
                }
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }

    //脐血库
    @RequestMapping(value = "showRecordContentBlood/{flag}/{patientId}/{assortIds}")
    @ResponseBody
    public void showRecordContentBlood(@PathVariable("patientId") String patientId,
                                       @PathVariable("assortIds") String assortIds,
                                       @PathVariable("flag") String flag, HttpServletResponse response) {
        String pdfName = "档案管理PDF";
        try {
            if (StringUtils.isNotBlank(patientId)) {
                patientId = patientId.replace("\'", "");
                CommomVo commomVo = new CommomVo();
                if (StringUtils.isNotBlank(flag) && "file_path".equals(flag)) {
                    commomVo = commomMapper.selectByPrimaryKeyPath(patientId);
                } else {
                    commomVo = commomMapper.selectByPrimaryKey(patientId);
                }
                String[] scanPaths = assortIds.split(",");
                //组织图片地址集合
                List<String> filePaths = new ArrayList<>();
                if (null != scanPaths) {
                    flag = FieldPropertyConvert.fieldToProperty(flag);
                    Field declaredField = commomVo.getClass().getDeclaredField(flag);
                    declaredField.setAccessible(true);
                    String src = (String) declaredField.get(commomVo);
                    for (int i = 0; i < scanPaths.length; i++) {
                        if (StringUtils.isNotBlank(scanPaths[i])) {
                            String fileRealPath = src + "/" + scanPaths[i];
                            File file = new File(fileRealPath);
                            if (file.isFile()) {
                                filePaths.add(fileRealPath);
                            }
                        }
                    }
                    if (null != filePaths && !filePaths.isEmpty()) {
                        //根据图片路径转换pdf
                        EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                        img2PdfUtil.imageToPdf(response, filePaths, pdfName, emrPdfWaterSet);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //脐血库

    /**
     * @MethodName: updateScanAssort
     * @Description: 重新分页
     * @Param String patientId,String assortIds:病案分段id集合,Integer index：pdf当前页数
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-06
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-06
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/updateScanAssort")
    @OptionalLog(module = "修改", methods = "病案预览页面病案图片重新分类")
    @RequestMapping(value = "updateScanAssort")
    @ResponseBody
    public ResultUtil updateScanAssort(String patientId, String assortIds, Integer index, String newAssortId) {
        if (StringUtils.isNoneBlank(patientId) && StringUtils.isNoneBlank(assortIds) && null != index && StringUtils.isNoneBlank(newAssortId)) {
            try {
                //根据index:当前pdf页数，patientId，admissIds获取pdf信息
                List<ScanPathVo> scanPathVos = getPdfPathVo(index, patientId, assortIds);
                List<String> list = new ArrayList<>();
                if (null != scanPathVos && !scanPathVos.isEmpty()) {
                    for (ScanPathVo scanPathVo : scanPathVos) {
                        list.add(scanPathVo.getScanPage());
                    }
                    //批量更新
                    scanAssortService.SimpleUpdate(patientId, newAssortId, list);
                    return ResultUtil.ok();
                } else {
                    return ResultUtil.error("无图片");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
    //脐血库

    /**
     * @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 = "病案预览页面病案图片重新分类")
    @RequestMapping(value = "updateScanAssortByBlood", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil updateScanAssortByBlood(String patientId, String assortIds, String newAssortId) {
        if (StringUtils.isNoneBlank(patientId) && StringUtils.isNoneBlank(assortIds) && StringUtils.isNoneBlank(newAssortId)) {
            try {
                //根据patientId，admissIds(scanPage分类图片集合)批量更新分段id assrotdId
                //批量更新
                String[] split = assortIds.split(",");
                assortIds = "";
                for (String str : split) {
                    assortIds += "'" + str + "',";
                }
                assortIds = assortIds.substring(0, assortIds.length() - 1);
                scanAssortService.SimpleUpdateByPatientIdAndScanPages(patientId, newAssortId, assortIds);
                return ResultUtil.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /*****************************************编码操作**************************************************/

    /**
     * @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 = "病案预览页面删除病案图片")
    @RequestMapping(value = "delScanAssortByBlood", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil delScanAssortByBlood(String patientId, String assortIds) {
        if (StringUtils.isNoneBlank(patientId) && StringUtils.isNoneBlank(assortIds)) {
            try {
                //根据patientId，admissIds(scanPage分类图片集合)批量更新分段id assrotdId
                //批量更新
                String[] split = assortIds.split(",");
                assortIds = "";
                //逐个删除图片
                CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
                String path = commomVo.getHomeAddr();
                for (String str : split) {
                    assortIds += "'" + str + "',";
                    //删除影像图片文件，2020-04-01修改不删除图片
                    /*if(StringUtils.isNotBlank(path)){
                        String src = path + "/" + str;
                        File file = new File(src);
                        if(file.exists()){
                            file.delete();
                        }
                    }*/
                }
                assortIds = assortIds.substring(0, assortIds.length() - 1);
                scanAssortService.SimpleDelByPatientIdAndScanPages(patientId, assortIds);
                return ResultUtil.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * @MethodName: codeTable
     * @Description: 跳转到编码录入页面
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-12-04
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-12-04
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("codeTable")
    public String codeTable(String patientId, Model model) {
        model.addAttribute("patientId", patientId);
        try {
            //加载诊断编码和名称
            List<T_Diag> diags = diagService.selectAllByPatientId(patientId, null);
            model.addAttribute("diags", diags);
            //加载手术编码和手术名称
            List<T_Operate> operates = operateService.selectAllByPatientId(patientId, null);
            model.addAttribute("operates", operates);
            //麻醉方式
            List<Emr_Dictionary> anaesthesias = dictionaryMapper.selectDictionaryByTypeCode("anaesthesia");
            model.addAttribute("anaesthesias", anaesthesias);
            //切口愈合等级
            List<Emr_Dictionary> cutHealGrades = dictionaryMapper.selectDictionaryByTypeCode("cut_heal_grade");
            model.addAttribute("cutHealGrades", cutHealGrades);
            //是否择期手术
            List<Emr_Dictionary> whether = dictionaryMapper.selectDictionaryByTypeCode("whether");
            model.addAttribute("whether", whether);
            //手术类型
            List<Emr_Dictionary> operateClasses = dictionaryMapper.selectDictionaryByTypeCode("operate_class");
            model.addAttribute("operateClasses", operateClasses);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "recordManage/commomSearch/codeTable";
    }

    /**
     * @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 (int i = 0; i < icdCodes.size(); i++) {
                    if (StringUtils.isNoneBlank(icdCodes.get(i).getCode())) {
                        map.put(icdCodes.get(i).getCode(), icdCodes.get(i).getName());
                    }
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(map);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /* */

    /**
     * @MethodName: getOperateCodeContents
     * @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 (int i = 0; i < zdCm3s.size(); i++) {
                    if (StringUtils.isNoneBlank(zdCm3s.get(i).getCode())) {
                        map.put(zdCm3s.get(i).getCode(), zdCm3s.get(i).getName());
                    }
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(map);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: loadSelect
     * @Description: 加载编码字典
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-12-05
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-12-05
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("loadCM3")
    @ResponseBody
    public String loadCM3() {
        try {
            //加载手术cmd3
            List<Zd_Cm3> cm3s = cm3Mapper.selectAll(null, null);
            return JSON.toJSONString(cm3s);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getCodeTypeTree
     * @Description: 根据patientId加载类别树
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-11
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-11
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getCodeTypeTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getCodeTypeTree(String patientId) {
        if (StringUtils.isNoneBlank(patientId)) {
            try {
                List<Emr_Code_Type> types = codeTypeService.selectAllByPatientId(patientId);
                List<CodeTree> treeList = new ArrayList<>();
                if (null != types && !types.isEmpty()) {
                    Integer id = 0;
                    Integer parentId = 0;
                    //第一级，类别层级
                    for (int i = 0; i < types.size(); i++) {
                        id++;
                        CodeTree tree = new CodeTree();
                        BeanUtils.copyProperties(types.get(i), tree);
                        tree.setId(id);
                        tree.setParentId(0);
                        tree.setSelfId(types.get(i).getId());
                        tree.setName(types.get(i).getTypeName());
                        //子集赋值父Id
                        parentId = id;
                        treeList.add(tree);
                        //第二级，手术类或西医编码类或中医编码类
                        String typeFlag = types.get(i).getTypeFlag();
                        //1.手术
                        if (StringUtils.isNoneBlank(typeFlag) && "operate".equals(typeFlag)) {
                            List<T_Operate> operates = operateService.selectAllByPatientId(patientId, null);
                            if (null != operates && !operates.isEmpty()) {
                                for (int j = 0; j < operates.size(); j++) {
                                    id++;
                                    CodeTree tree1 = new CodeTree();
                                    BeanUtils.copyProperties(operates.get(j), tree1);
                                    tree1.setId(id);
                                    tree1.setParentId(parentId);
                                    tree1.setName(operates.get(j).getOperateNo() + "." + operates.get(j).getOperateName());
                                    //转换时间格式
                                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                                    if (null != tree1.getOperateDate()) {
                                        tree1.setOperateDateStr(fmt.format(tree1.getOperateDate()));
                                    }
                                    if (null != tree1.getOperDate()) {
                                        tree1.setOperDateStr(fmt.format(tree1.getOperDate()));
                                    }
                                    treeList.add(tree1);
                                }
                            }
                            //西医诊断
                        } else if (StringUtils.isNoneBlank(typeFlag) && "diag".equals(typeFlag)) {
                            List<T_Diag> diags = diagService.selectAllByPatientId(patientId, null);
                            if (null != diags && !diags.isEmpty()) {
                                for (int j = 0; j < diags.size(); j++) {
                                    id++;
                                    CodeTree tree2 = new CodeTree();
                                    BeanUtils.copyProperties(diags.get(j), tree2);
                                    tree2.setId(id);
                                    tree2.setParentId(parentId);
                                    tree2.setName(diags.get(j).getDiagNo() + "." + diags.get(j).getDiagName());
                                    //转换时间格式
                                    if (null != tree2.getOperDate()) {
                                        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        tree2.setOperDateStr(fmt.format(tree2.getOperDate()));
                                        treeList.add(tree2);
                                    }
                                }
                            }
                            //中医诊断
                        } else if (StringUtils.isNoneBlank(typeFlag) && "herbDiag".equals(typeFlag)) {
                            List<T_Herb_Diag> herbDiags = herbDiagService.selectAllByPatientId(patientId, null);
                            if (null != herbDiags && !herbDiags.isEmpty()) {
                                for (int j = 0; j < herbDiags.size(); j++) {
                                    id++;
                                    CodeTree tree3 = new CodeTree();
                                    BeanUtils.copyProperties(herbDiags.get(j), tree3);
                                    tree3.setId(id);
                                    tree3.setParentId(parentId);
                                    tree3.setName(herbDiags.get(j).getHerbNo() + "." + herbDiags.get(j).getHerbName());
                                    //转换时间格式
                                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                                    tree3.setOperDateStr(fmt.format(tree3.getOperDate()));
                                    treeList.add(tree3);
                                }
                            }
                        }
                    }
                }
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(treeList);
                return json;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * @MethodName: addCodeType
     * @Description: 保存编码类别信息
     * @Param Emr_Code_Type codeType编码类别对象,Integer index：pdf当前页码,String patientId,String assortIds：分段id
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/addCodeType", "/commom/updateCodeType"})
    @OptionalLog(module = "新增", methods = "编码类别", fieldName = "typeName")
    @RequestMapping("addCodeType")
    @ResponseBody
    public ResultUtil addCodeType(Emr_Code_Type codeType, Integer index, String patientId, String assortIds,
                                  HttpServletRequest request) {
        if (StringUtils.isBlank(assortIds)) {
            return ResultUtil.error("没有分段数据,请先在用户分配调阅里添加并分配分段数据!");
        }
        if (StringUtils.isNoneBlank(patientId) && null != index) {
            try {
                //验证标志和名称都不能重复
                Emr_Code_Type isExistFlag = codeTypeMapper.checkFlagAndNameIsExist(codeType.getTypeFlag(), null);
                Emr_Code_Type isExistName = codeTypeMapper.checkFlagAndNameIsExist(null, codeType.getTypeName());
                if (codeType.getId() == null) {
                    if (isExistFlag == null) {
                        if (isExistName == null) {
                            //新增
                            codeType.setPatientId(patientId);
                            //根据index:当前pdf页数，patientId，admissIds获取pdf信息
                            List<ScanPathVo> scanPathVo = getPdfPathVo(index, patientId, assortIds);
                            if (null != scanPathVo && !scanPathVo.isEmpty()) {
                                codeType.setAssortId(scanPathVo.get(0).getAssortId());
                                codeType.setScanPage(scanPathVo.get(0).getScanPage());
                            } else {
                                return ResultUtil.error("图片不存在!");
                            }
                            codeTypeService.addCodeType(codeType, request);
                            return ResultUtil.ok();
                        } else {
                            return ResultUtil.error("类别名称不能重复!");
                        }
                    } else {
                        return ResultUtil.error("类别标志不能重复!");
                    }
                } else {
                    if (null != isExistName && isExistName.getId() != codeType.getId()) {
                        return ResultUtil.error("类别名称不能重复!");
                    } else {
                        if (null != isExistFlag && isExistFlag.getId() != codeType.getId()) {
                            return ResultUtil.error("类别标志不能重复!");
                        } else {
                            //修改
                            codeTypeService.updateCodeType(codeType, request);
                            return ResultUtil.ok();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        } else {
            return null;
        }
    }

    /**
     * @MethodName: delCodeTypeById
     * @Description: 根据id删除编码类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-11
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-11
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/delCodeTypeById")
    @OptionalLog(module = "删除", methods = "编码类别", fieldName = "typeName", tableName = "emr_code_type")
    @RequestMapping(value = "delCodeTypeById/{id}")
    @ResponseBody
    public ResultUtil delCodeTypeById(@PathVariable("id") Integer id) {
        try {
            codeTypeService.deleteByPrimaryKey(id);
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }
    /********************************************手术编码*******************************************************/

    /**
     * @MethodName: addDiagCode
     * @Description: 保存诊断编码
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-01-03
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-01-03
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/addOperCode")
    @RequestMapping(value = "addDiagCode")
    @ResponseBody
    public ResultUtil addDiagCode(String patientId, String diagNos, String diagNames, String diagCodes, String inhospstats) {
        try {
            diagService.addDiagCode(patientId, diagNos, diagNames, diagCodes, inhospstats);
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * @MethodName: checkOperateNo
     * @Description: 验证手术序号是否存在
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "checkOperateNo")
    @ResponseBody
    public ResultUtil checkOperateNo(String patientId, Short operateNo) {
        if (StringUtils.isNoneBlank(patientId) && operateNo != null) {
            try {
                //根据patientId和手术编码查询手术编码集合
                List<T_Operate> operates = operateService.selectAllByPatientId(patientId, operateNo);
                if (operates != null && !operates.isEmpty()) {
                    //存在
                    return ResultUtil.error();
                } else {
                    return ResultUtil.ok();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.error();
    }

    /**
     * @MethodName: getOperByCodeOrName
     * @Description: 通过手术编码或手术名称查询手术字典集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getOperByCodeOrName", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getOperByCodeOrName(String code, String name) {
        //根据手术编码和名称查询手术编码对象
        try {
            List<Zd_Cm3> cm3s = cm3Mapper.selectAll(code, name);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(cm3s);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: saveOperCode
     * @Description: 保存手术编码
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/addOperCode", "/commom/updateOperCode"})
    @OptionalLog(module = "新增", methods = "手术编码", fieldName = "operateName")
    @RequestMapping(value = "saveOperCode")
    @ResponseBody
    public ResultUtil saveOperCode(T_Operate operate, Integer isUpdateOperNo, HttpServletRequest request) {
        try {
            if (operate.getCurrentOperateNo() == null) {
                //新增
                boolean flag = FormTokenFlagUtil.isFlag(request);
                if (!flag) {
                    return ResultUtil.error("请不要重复提交!");
                }
                operateService.insert(operate);
            } else {
                //修改
                if (isUpdateOperNo == 1) {
                    //有修改手术序号
                    //查询手术序号是否存在
                    List<T_Operate> operates = operateService.selectAllByPatientId(operate.getPatientId(), operate.getOperateNo());
                    if (null != operates && !operates.isEmpty()) {
                        //存在
                        return ResultUtil.error("该手术序号已存在!");
                    } else {
                        operateService.updateByPrimaryKeySelective(operate);
                    }
                } else {
                    //手术序号一样
                    operateService.updateByPrimaryKeySelective(operate);
                }
            }
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

        /**
     * @MethodName: deleteOperCodeByPatientIdAndOperNo
     * @Description: 根据petientId和手术序号删除手术编码对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/deleteOperCode")
    @OptionalLog(module = "删除", methods = "手术编码", fieldName = "operateName", tableName = "t_operate")
    @RequestMapping(value = "deleteOperCodeByPatientIdAndOperNo")
    @ResponseBody
    public ResultUtil deleteOperCodeByPatientIdAndOperNo(String patientId, Short operateNo) {
        if (StringUtils.isNoneBlank(patientId) && null != operateNo) {
            try {
                operateService.deleteOperCodeByPatientIdAndOperNo(patientId, operateNo);
                return ResultUtil.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        } else {
            return ResultUtil.error();
        }
    }/**************************************************西医诊断操作*************************************************/

/**
     * @MethodName: addOperCode
     * @Description: 保存手术编码
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-01-03
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-01-03
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/addOperCode")
    @RequestMapping(value = "addOperCode")
    @ResponseBody
    public ResultUtil addOperCode(String patientId, String operNos, String operDates, String operCodes, String operNames, String operateClasses, String operators, String assistant1s, String assistant2s, String cuts, String chossurgs, String anaesthesiaTypes, String anaesthesiaNames) {
        try {
            operateService.addOperCode(patientId, operNos, operDates, operCodes, operNames, operateClasses, operators, assistant1s, assistant2s, cuts, chossurgs, anaesthesiaTypes, anaesthesiaNames);
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * @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) {
        try {
            List<Emr_Dictionary> dictionaries = dictionaryMapper.selectDictionaryByTypeCode(typeCode);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(dictionaries);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @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() {
        try {
            List<Zd_Icd_Code> icdCodes = icdCodeMapper.selectAll(null, null);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(icdCodes);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getIcdCodeByCodeOrName
     * @Description: 根据icd编码或名称查询icd字典集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getIcdCodeByCodeOrName", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getIcdCodeByCodeOrName(String code, String name) {
        try {
            List<Zd_Icd_Code> icdCodes = icdCodeMapper.selectAll(code, name);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(icdCodes);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: checkDiagNo
     * @Description: 验证西医诊断序号是否存在
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "checkDiagNo")
    @ResponseBody
    public ResultUtil checkDiagNo(String patientId, Short diagNo) {
        if (StringUtils.isNoneBlank(patientId) && diagNo != null) {
            try {
                List<T_Diag> diags = diagService.selectAllByPatientId(patientId, diagNo);
                if (diags != null && !diags.isEmpty()) {
                    //存在
                    return ResultUtil.error();
                } else {
                    return ResultUtil.ok();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.error();
    }

    /**
     * @MethodName: saveDiag
     * @Description: 保存西医诊断
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/addOperCode", "/commom/updateOperCode"})
    @OptionalLog(module = "保存", methods = "西医诊断编码", fieldName = "diagName")
    @RequestMapping(value = "saveDiag")
    @ResponseBody
    public ResultUtil saveDiag(T_Diag diag, Integer isUpdateOperNo, HttpServletRequest request) {
        try {
            if (diag.getCurrentDiagNo() == null) {
                //新增
                boolean flag = FormTokenFlagUtil.isFlag(request);
                if (!flag) {
                    return ResultUtil.error("请不要重复提交!");
                }
                diagService.insert(diag);
            } else {
                //修改
                if (isUpdateOperNo == 1) {
                    //有修改序号
                    //查询序号是否存在
                    List<T_Diag> diags = diagService.selectAllByPatientId(diag.getPatientId(), diag.getDiagNo());
                    if (null != diags && !diags.isEmpty()) {
                        //存在
                        return ResultUtil.error("该诊断序号已存在！");
                    } else {
                        diagService.updateByPrimaryKeySelective(diag);
                    }
                } else {
                    //诊断序号一样
                    diagService.updateByPrimaryKeySelective(diag);
                }
            }
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }
    /*****************************************中医诊断********************************************************/

    /**
     * @MethodName: deleteCodeByPatientIdAndDiagNo
     * @Description: 根据petientId和诊断序号删除西医诊断编码对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-13
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-13
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/deleteOperCode")
    @OptionalLog(module = "删除", methods = "西医诊断编码", fieldName = "diagName", tableName = "t_diag")
    @RequestMapping(value = "deleteCodeByPatientIdAndDiagNo")
    @ResponseBody
    public ResultUtil deleteCodeByPatientIdAndDiagNo(String patientId, Short diagNo) {
        if (StringUtils.isNoneBlank(patientId) && null != diagNo) {
            try {
                diagService.deleteDiagByPatientIdAndDiagNo(patientId, diagNo);
                return ResultUtil.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        } else {
            return ResultUtil.error();
        }
    }

    /**
     * @MethodName: checkHerbNo
     * @Description: 验证中医诊断序号是否存在
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "checkHerbNo")
    @ResponseBody
    public ResultUtil checkHerbNo(String patientId, Short herbNo) {
        if (StringUtils.isNoneBlank(patientId) && herbNo != null) {
            try {
                List<T_Herb_Diag> herbDiags = herbDiagService.selectAllByPatientId(patientId, herbNo);
                if (herbDiags != null && !herbDiags.isEmpty()) {
                    //存在
                    return ResultUtil.error();
                } else {
                    return ResultUtil.ok();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.error();
    }

    /**
     * @MethodName: saveHerbDiag
     * @Description: 保存中医诊断
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-12
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-12
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/addOperCode", "/commom/updateOperCode"})
    @OptionalLog(module = "保存", methods = "中医诊断编码", fieldName = "herbName")
    @RequestMapping(value = "saveHerbDiag")
    @ResponseBody
    public ResultUtil saveHerbDiag(T_Herb_Diag herbDiag, Integer isUpdateOperNo, HttpServletRequest request) {
        try {
            if (herbDiag.getCurrentHerbDiagNo() == null) {
                //新增
                boolean flag = FormTokenFlagUtil.isFlag(request);
                if (!flag) {
                    return ResultUtil.error("请不要重复提交!");
                }
                herbDiagService.insert(herbDiag);
            } else {
                //修改
                if (isUpdateOperNo == 1) {
                    //有修改序号
                    //查询序号是否存在
                    List<T_Herb_Diag> herbDiags = herbDiagService.selectAllByPatientId(herbDiag.getPatientId(), herbDiag.getHerbNo());
                    if (null != herbDiags && !herbDiags.isEmpty()) {
                        //存在
                        return ResultUtil.error("该诊断序号已存在！");
                    } else {
                        herbDiagService.updateByPrimaryKeySelective(herbDiag);
                    }
                } else {
                    //诊断序号一样
                    herbDiagService.updateByPrimaryKeySelective(herbDiag);
                }
            }
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * @MethodName: deleteCodeByPatientIdAndHerbNo
     * @Description: 根据petientId和诊断序号删除中医诊断编码对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-13
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-13
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/commom/deleteOperCode")
    @OptionalLog(module = "删除", methods = "中医诊断编码", fieldName = "herbName", tableName = "t_herb_diag")
    @RequestMapping(value = "deleteCodeByPatientIdAndHerbNo")
    @ResponseBody
    public ResultUtil deleteCodeByPatientIdAndHerbNo(String patientId, Short herbNo) {
        if (StringUtils.isNoneBlank(patientId) && null != herbNo) {
            try {
                herbDiagService.deleteHerbDiagByPatientIdAndHerbNo(patientId, herbNo);
                return ResultUtil.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        } else {
            return ResultUtil.error();
        }
    }

    //封装根据index:当前pdf页数，patientId，admissIds获取pdf信息
    private List<ScanPathVo> getPdfPathVo(Integer index, String patientId, String assortIds) throws Exception {
        List<ScanPathVo> list = new ArrayList<>();
        patientId = "'" + patientId + "'";
        List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByPatientIds(patientId, assortIds);
        //重新组织存在的文件，即转换成功的文件
        if (null != scanPathVos && !scanPathVos.isEmpty()) {
            // 实例化图片
            Image image = null;
            //不成张合成的高度
            float tempHeight = 0;
            Integer pageCount = 0;
            for (ScanPathVo scanPathVo : scanPathVos) {
                String fileRealPath = scanPathVo.getFileRealPath();
                if (StringUtils.isNoneBlank(fileRealPath)) {
                    //判断文件是否存在
                    File file1 = new File(fileRealPath);
                    if (file1.exists()) {
                        if (file1.getName().endsWith(".tif") || file1.getName().endsWith(".tiff")) {
                            Object localObject1 = null;
                            Object localObject2 = null;
                            URL paramURL = Utilities.toURL(fileRealPath);
                            try {
                                if (paramURL.getProtocol().equals("file")) {
                                    localObject2 = paramURL.getFile();
                                    localObject2 = Utilities
                                            .unEscapeURL((String) localObject2);
                                    localObject1 = new RandomAccessFileOrArray(
                                            (String) localObject2);
                                } else {
                                    localObject1 = new RandomAccessFileOrArray(paramURL);
                                }

                                int pageNums = TiffImage
                                        .getNumberOfPages((RandomAccessFileOrArray) localObject1);
                                if (pageNums > 0) {
                                    for (int i = 1; i <= pageNums; i++) {
                                        localObject2 = TiffImage.getTiffImage(
                                                (RandomAccessFileOrArray) localObject1, i);
                                        image = (Image) localObject2;
                                    }
                                }
                                if (localObject1 != null)
                                    ((RandomAccessFileOrArray) localObject1).close();

                            } finally {
                                if (localObject1 != null)
                                    ((RandomAccessFileOrArray) localObject1).close();
                            }
                        } else if (file1.getName().endsWith(".png")
                                || file1.getName().endsWith(".jpg")
                                || file1.getName().endsWith(".gif")
                                || file1.getName().endsWith(".jpeg")
                        ) {
                            // 实例化图牿
                            image = Image.getInstance(fileRealPath);
                        }
                        // 获得图片的高庿
                        float heigth = image.getHeight();
                        float width = image.getWidth();
                        // 合理压缩，h>w，按w压缩，否则按w压缩
                        int percent = Jpg2PdfUtil.getPercent(heigth, width);

                        // 设置图片居中显示
                        image.setAlignment(Image.ALIGN_CENTER);
                        // 按百分比显示图片的比便
                        if (width > 1024 || heigth > 786) {
                            image.scalePercent(percent + 5);
                            pageCount++;
                            if (pageCount == index) {
                                //当前页返回
                                list.clear();
                                list.add(scanPathVo);
                                return list;
                            }
                            //整张，把合成的高度置为0；
                            tempHeight = 0;
                        } else if (heigth < 786) {
                            if (tempHeight == 0) {
                                pageCount++;
                            }
                            tempHeight += heigth;
                            if (tempHeight > 786) {
                                pageCount++;
                                if (pageCount == index) {
                                    //当前页返回
                                    list.clear();
                                    list.add(scanPathVo);
                                    return list;
                                } else if (pageCount == (index + 1)) {
                                    //已另起一页，返回前一页
                                    return list;
                                }
                                tempHeight = heigth;
                            } else {
                                //连续的几张图片高度总和小于786添加进集合
                                list.add(scanPathVo);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    /*@RequestMapping("toPdf")
    public String toPdf(String patientId,String assortIds,String name,Model model){
        model.addAttribute("patientId",patientId);
        model.addAttribute("assortIds",assortIds);
        model.addAttribute("name",name);
        return "recordManage/commomSearch/pdf";
    }*/
    @RequiresPermissions("/commom/updatePic")
    @RequestMapping(value = "updatePic", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil updatePic(@RequestParam(required = false, value = "files")
                                        MultipartFile[] files, String patientId, String assortId, String flag) {
        try {
            CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
            flag = FieldPropertyConvert.fieldToProperty(flag);
            Field field = commomVo.getClass().getDeclaredField(flag);
            field.setAccessible(true);
            String path = (String) field.get(commomVo) + "/";
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            //定义批量添加进图片明细表集合
            List<T_Scan_Assort> insertList = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                String fullName = files[i].getOriginalFilename();
                String src = path + fullName;
                File file = new File(src);
                //判断是否存在，存在文件加日期
                if (file.exists()) {
                    //原始名
                    String baseName = FilenameUtils.getBaseName(files[i].getOriginalFilename());
                    //扩展名
                    String ext = FilenameUtils.getExtension(files[i].getOriginalFilename());
                    fullName = baseName + "_" + fmt.format(new Date()) + "." + ext;
                }
                src = path + fullName;
                //上传图片
                files[i].transferTo(new File(src));
                T_Scan_Assort scanAssort = new T_Scan_Assort();
                scanAssort.setPatientId(patientId);
                scanAssort.setAssortId(assortId);
                scanAssort.setScanPage(fullName);
                insertList.add(scanAssort);
            }
            scanAssortService.SimpleInsert(insertList);
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("上传出错了,请联系系统管理员!");
        }
    }
}
