package com.emr.controller.templateSearch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emr.annotation.OptionalLog;
import com.emr.controller.FormTokenFlagUtil;
import com.emr.dao.Archive_DetailMapper;
import com.emr.dao.CommomMapper;
import com.emr.dao.EmrComomSetMapper;
import com.emr.dao.Emr_DictionaryMapper;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.dao.commomSearch.ScanPathMapper;
import com.emr.dao.emrPdfWaterSet.EmrPdfWaterSetMapper;
import com.emr.dao.recordLock.Emr_LockMapper;
import com.emr.dao.templateSearch.Emr_CustomizeMapper;
import com.emr.dao.templateSearch.Emr_ModleMapper;
import com.emr.dao.templateSearch.Emr_Modle_RelatedMapper;
import com.emr.entity.*;
import com.emr.entity.approve.Emr_Apply_Approve;
import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.entity.recordLock.Emr_Lock;
import com.emr.entity.templateSearch.Emr_Customize;
import com.emr.entity.templateSearch.Emr_Modle;
import com.emr.entity.templateSearch.Emr_Modle_Check;
import com.emr.service.CommomService;
import com.emr.service.emrFunGroupDistribution.FunGroupDistributionService;
import com.emr.service.emrLock.EmrLockServiceImpl;
import com.emr.service.emrPrintOrDownLoadInfo.PrintOrDownLoadInfoService;
import com.emr.service.templateSearch.TemplateSearchService;
import com.emr.util.*;
import com.emr.vo.Msg;
import com.emr.vo.commomSearch.CommomTree;
import com.emr.vo.commomSearch.CommomVo;
import com.emr.vo.commomSearch.ScanPathForPatientListVo;
import com.emr.vo.commomSearch.ScanPathVo;
import com.emr.vo.templateSearch.Emr_Modle_RelatedVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ProjectName:TemplateSearchController
 * @Description:自定义查询页面
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/5/21 15:37
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/5/21 15:37
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("template/")
public class TemplateSearchController {
    @Autowired
    private Emr_CustomizeMapper customizeMapper;
    @Autowired
    private TemplateSearchService templateSearchService;
    @Autowired
    private Emr_ModleMapper emrModleMapper;
    @Autowired
    private Emr_CustomizeMapper emrCustomizeMapper;
    @Autowired
    private Emr_Modle_RelatedMapper emrModleRelatedMapper;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private ScanPathMapper scanPathMapper;
    @Autowired
    private EmrLockServiceImpl lockService;
    @Autowired
    private Emr_LockMapper lockMapper;
    @Autowired
    private FunGroupDistributionService funGroupDistributionService;
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;
    @Autowired
    private Emr_Apply_ApproveMapper applyApproveMapper;
    @Autowired
    private PrintOrDownLoadInfoService printOrDownLoadInfoService;
    @Autowired
    private EmrPdfWaterSetMapper pdfWaterSetMapper;
    @Autowired
    private EmrComomSetMapper emrComomSetMapper;
    @Autowired
    private CommomService commomService;
    @Autowired
    private Archive_DetailMapper archiveDetailMapper;
    @Value("${export_pdf_hospital_info}")
    private String hospitaInfo;

    @Value("${export_pdf_patient_info}")
    private String patientInfo;

    /**
     * @MethodName templateList
     * @Description: 跳转到自定义模板页面
     * @Param 无
     * @Returnt emplateSearch/templateList1
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "查看", methods = "自定义模板页面")
    @RequiresPermissions("/template/templateList")
    @RequestMapping("templateList")
    public String templateList(Model model, HttpServletRequest request) {
        List<Emr_Customize> parents = null;
        try {
            parents = customizeMapper.selectParents();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("parents", parents);
        String formToken = UUID.randomUUID().toString();
        request.getSession().setAttribute("formToken", formToken);
        return "recordManage/templateSearch/templateList1";
    }

    @RequestMapping("getParentSelect")
    @ResponseBody
    public Msg getParentSelect() {
        try {
            List<Emr_Customize> parents = customizeMapper.selectParents();
            return Msg.success().add("list", parents);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return Msg.fail("刷新父节点选择出错了,请联系系统管理员!");
        }
    }

    /**
     * @MethodName: checkName
     * @Description: 验证模板名称是否重复
     * @Param Integer parentId：父节点id,String columnName:模板名称
     * @Return 存在则返回ResultUtil.error()，code=500;不存在则返回ResultUtil.ok()，code=0;
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkName")
    @ResponseBody
    public ResultUtil checkName(Integer parentId, String columnName) throws Exception {
        Integer id = customizeMapper.selectListCheckName(parentId, columnName);
        if (id != null) {
            return ResultUtil.error();
        } else {
            return ResultUtil.ok();
        }
    }

    /**
     * @MethodName: checkColumnExist
     * @Description: 验证字段值+表值是否重复
     * @Param String columnValue:字段值,String tableValue：表值
     * @Return 存在则返回ResultUtil.error()，code=500;不存在则返回ResultUtil.ok()，code=0;
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkColumnExist")
    @ResponseBody
    public ResultUtil checkColumnExist(String columnValue, String tableValue, Integer id) throws Exception {
        Integer existId = customizeMapper.checkColumnExist(columnValue, tableValue);
        if (existId == null || id.equals(existId)) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error();
        }
    }

    /**
     * @MethodName: addTemplate
     * @Description: 添加
     * @Param Emr_Customize
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/addTemplate")
    @OptionalLog(module = "新增", methods = "自定义模板", fieldName = "columnName")
    @RequestMapping("addTemplate")
    @ResponseBody
    public ResultUtil addTemplate(Emr_Customize customize, HttpServletRequest request) throws Exception {
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if (flag) {
            if (StringUtils.isBlank(customize.getColumnName())) {
                return ResultUtil.error("字段名/模板名不能为空!");
            }
            if (customize.getParentId() == null) {
                customize.setParentId(0);
            }
            Integer id = customizeMapper.selectListCheckName(customize.getParentId(), customize.getColumnName());
            if (id != null) {
                return ResultUtil.error("字段名/模板名不能重复!");
            }
            templateSearchService.addTemplate(customize, request);
            return ResultUtil.ok(customize.getId());
        } else {
            return ResultUtil.error("请不要重复提交!");
        }
    }

    /**
     * @MethodName: updateTemplate
     * @Description: 更新
     * @Param Emr_Customize
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/updateTemplate")
    @OptionalLog(module = "修改", methods = "自定义模板", fieldName = "columnName")
    @RequestMapping("updateTemplate")
    @ResponseBody
    public ResultUtil updateTemplate(Emr_Customize customize, HttpServletRequest request) throws Exception {
        if (null == customize.getParentId()) {
            customize.setParentId(0);
        }
        Integer id = customizeMapper.selectListCheckName(customize.getParentId(), customize.getColumnName());
        if (null != id && !id.equals(customize.getId())) {
            return ResultUtil.error("字段名已存在!");
        }
        templateSearchService.updateTemplate(customize, request);
        return ResultUtil.ok();
    }

    /**
     * @MethodName: getTemplateTree
     * @Description: 获取模板树
     * @Param 无
     * @Return 模板集合
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getTemplateTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getTemplateTree() {
        //添加首级目录
        Emr_Customize customize = new Emr_Customize();
        customize.setId(0);
        customize.setColumnName("模板列表");
        List<Emr_Customize> list = new ArrayList<>();
        list.add(customize);
        try {
            List<Emr_Customize> templates = customizeMapper.selectAllByTree();
            list.addAll(templates);
            return JSON.toJSONString(list);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: deleteTemplate
     * @Description: 获取模板树
     * @Param 无
     * @Return 模板集合
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/deleteTemplate")
    @OptionalLog(module = "删除", methods = "自定义模板", fieldName = "columnName", tableName = "emr_customize")
    @RequestMapping("deleteTemplate")
    @ResponseBody
    public ResultUtil deleteTemplate(Integer id) throws Exception {
        templateSearchService.deleteTemplate(id);
        return ResultUtil.ok();
    }

    /***************************************自定义模板选择********************************************/
    /**
     * @MethodName: templateSelectList
     * @Description: 跳转到自定义模板选择页面
     * @Param 无
     * @Return 模板集合
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/templateSelectList")
    @OptionalLog(module = "查看", methods = "自定义模板选择页面")
    @RequestMapping("templateSelectList")
    public String templateSelectList(Model model, HttpServletRequest request) {
        try {
            getSelectFlagTemplate(model, request);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        String formToken = UUID.randomUUID().toString();
        request.getSession().setAttribute("formToken", formToken);
        return "recordManage/templateSearch/templateSelectList";
    }

    /**
     * 封装传输默认模板对象
     */
    private void getSelectFlagTemplate(Model model, HttpServletRequest request) {
        Emr_Modle emrModle = new Emr_Modle();
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        Integer roleId = user.getRoleId();
        //roleId=0为系统管理员，userName为null
        try {
            emrModle = emrModleMapper.selectFlagExist(userName);
            if (null == emrModle) {
                emrModle = emrModleMapper.selectByPrimaryKey(1);
                if (null != roleId && roleId == 0) {
                    emrModle.setIsOper(1);
                } else {
                    emrModle.setIsOper(0);
                }
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("emrModle", emrModle);
    }

    /**
     * @MethodName: checkModleFlag
     * @Description: 验证模板标识不能重复
     * @Param modleName:模板名称
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkModleFlag")
    @ResponseBody
    public ResultUtil checkModleFlag(String modleFlag, HttpServletRequest request) throws Exception {
        if ("系统默认模板".equals(modleFlag)) {
            return ResultUtil.error("该模板标识已存在！");
        }
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserId().toString();
        Emr_Modle modle = emrModleMapper.checkModleFlag(creater, modleFlag);
        if (modle == null) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error("该模板标识已存在！");
        }
    }

    /**
     * @MethodName: checkModleName
     * @Description: 验证模板名称不能重复
     * @Param modleName:模板名称
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("checkModleName")
    @ResponseBody
    public ResultUtil checkModleName(String modleName, HttpServletRequest request) throws Exception {
        if ("系统默认模板".equals(modleName)) {
            return ResultUtil.error("该模板名称已存在！");
        }
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserId().toString();
        Emr_Modle modle = emrModleMapper.checkModleName(creater, modleName);
        if (modle == null) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.error("该模板名称已存在！");
        }
    }

    /**
     * @MethodName: addTemplateSelect
     * @Description: 新增模板选择
     * @Param 无
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/addTemplateSelect")
    @OptionalLog(module = "新增", methods = "自定义模板分类", fieldName = "modleName")
    @RequestMapping("addTemplateSelect")
    @ResponseBody
    public ResultUtil addTemplateSelect(Emr_Modle emrModle, HttpServletRequest request) throws Exception {
        if (StringUtils.isNotBlank(emrModle.getModleName()) && StringUtils.isNotBlank(emrModle.getModleFlag())) {
            boolean flag = FormTokenFlagUtil.isFlag(request);
            if (flag) {
                templateSearchService.addTemplateSelect(emrModle, request);
                return ResultUtil.ok(emrModle.getId());
            } else {
                return ResultUtil.error("请不要重复提交!");
            }
        } else {
            return ResultUtil.error("模板标识或模板名称不能为空!");
        }
    }

    /**
     * @MethodName: getTemplateSelectTree
     * @Description: 获取模板树
     * @Param 无
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getTemplateSelectTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getTemplateSelectTree(HttpServletRequest request) {
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        Integer roleId = user.getRoleId();
        try {
            List<Emr_Modle> modleList = new ArrayList<>();
            if (roleId == 0) {
                modleList = emrModleMapper.selectAllByCreater(null);
            } else if (roleId == -100) {
                StringBuilder creaters = CommomService.creaters(request);
                modleList = emrModleMapper.selectAllByCreater(creaters.toString());
            } else {
                userName = "'" + userName + "'";
                modleList = emrModleMapper.selectAllByCreater(userName);
            }
            //设置默认模板选中
            if (null != modleList && !modleList.isEmpty()) {
                //定义是否有创建选中，有则取消系统的的选中
                boolean flag = false;
                for (Emr_Modle emr_modle : modleList) {
                    if (emr_modle.getSelectFlag() == 1 && emr_modle.getId() != 1 && emr_modle.getCreater().equals(userName)) {
                        emr_modle.setChecked("true");
                        flag = true;
                        break;
                    }
                }
                //有则取消系统的的选中,不是系统管理员roleId!=0系统模板isOper置为零
                for (Emr_Modle emr_modle : modleList) {
                    if (emr_modle.getId() == 1) {
                        if (flag) {
                            emr_modle.setChecked("");
                        } else {
                            emr_modle.setChecked("true");
                        }
                    }
                }
            }
            List<Emr_Modle> modles = new ArrayList<>();
            Emr_Modle modle = new Emr_Modle();
            //添加父节点
            modle.setId(-1);
            modle.setModleName("模板选择列表");
            modles.add(modle);
            assert modleList != null;
            modles.addAll(modleList);
            return JSON.toJSONString(modles);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: updateTemplateSelect
     * @Description: 修改模板
     * @Param Emr_Modle modle:模板对象,Integer selectFlagId：默认模板Id
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/updateTemplateSelect")
    @OptionalLog(module = "修改", methods = "自定义模板分类", fieldName = "modleName")
    @RequestMapping("updateTemplateSelect")
    @ResponseBody
    public ResultUtil updateTemplateSelect(Emr_Modle modle, Integer selectFlagId, HttpServletRequest request) throws Exception {
        if ("系统默认模板".equals(modle.getModleFlag())) {
            return ResultUtil.error("该模板标识已存在！");
        }
        if ("系统默认模板".equals(modle.getModleName())) {
            return ResultUtil.error("该模板名称已存在！");
        }
        if (StringUtils.isNotBlank(modle.getModleFlag()) && StringUtils.isNotBlank(modle.getModleName())) {
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String creater = user.getUserId().toString();
            Emr_Modle emr_modle = emrModleMapper.checkModleFlag(creater, modle.getModleFlag());
            if (null != emr_modle && !emr_modle.getId().equals(modle.getId())) {
                return ResultUtil.error("该模板标志已存在！");
            }
            Emr_Modle emr_modle1 = emrModleMapper.checkModleName(creater, modle.getModleName());
            if (null != emr_modle1 && !emr_modle1.getId().equals(modle.getId())) {
                return ResultUtil.error("该模板名称已存在！");
            }
            templateSearchService.updateTemplateSelect(modle, selectFlagId, request);
            return ResultUtil.ok();
        } else {
            return ResultUtil.error("模板标志或模板名称不能为空!");
        }
    }

    /**
     * @MethodName: udpateCheckByModle
     * @Description: 修改模板选中
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("/udpateCheckByModle/{id}")
    @ResponseBody
    public ResultUtil udpateCheckByModle(@PathVariable("id") Integer id, HttpServletRequest request) throws Exception {
        //查询默认的，将默认的取消
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserName();
        Emr_Modle flagModle = emrModleMapper.selectFlagExist(creater);
        //将此设为默认
        Emr_Modle modle = emrModleMapper.selectByPrimaryKey(id);
        if (id == 1 || modle.getCreater().equals(creater)) {
            if (flagModle != null) {
                flagModle.setSelectFlag(0);
                templateSearchService.updateTemplateSelect(flagModle, request);
            }
            modle.setSelectFlag(1);
            templateSearchService.updateTemplateSelect(modle, request);
            return ResultUtil.ok();
        } else {
            return ResultUtil.error("修改失败,该模板为客户创建,不建议修改");
        }
    }

    /**
     * @MethodName: deleteTemplate
     * @Description: 获取模板树
     * @Param 无
     * @Return 模板集合
     * @Author: 曾文和
     * @CreateDate: 2019-05-21
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-21
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/deleteTemplateSelect")
    @OptionalLog(module = "删除", methods = "自定义模板分类", fieldName = "modleName", tableName = "emr_modle")
    @RequestMapping("deleteTemplateSelect")
    @ResponseBody
    public ResultUtil deleteTemplateSelect(Integer id) throws Exception {
        templateSearchService.deleteTemplateSelect(id);
        return ResultUtil.ok();
    }

    /**
     * @MethodName: templateSelectIframe
     * @Description: 模板选择iframe页面
     * @Param 无
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-22
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("templateSelectIframe")
    public String templateSelectIframe(Integer id, Model model, HttpServletRequest request) {
        try {
            if (id != null) {
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                //回显选中id
                String creater = user.getUserName();
                Emr_Modle flagModle = emrModleMapper.selectFlagExist(creater);
                model.addAttribute("flagModle", flagModle);
                Emr_Modle emrModle = emrModleMapper.selectByPrimaryKey(id);
                Integer roleId = user.getRoleId();
                if (roleId != 0 && emrModle.getId() == 1) {
                    emrModle.setIsOper(0);
                }
                //如果选中的是id1并且和选中的id不一样则把改id为1的是否选中改0
                if (emrModle.getId() == 1) {
                    if (null != flagModle && !emrModle.getId().equals(flagModle.getId())) {
                        emrModle.setSelectFlag(0);
                    } else {
                        emrModle.setSelectFlag(1);
                    }
                }
                model.addAttribute("emrModle", emrModle);
                List<Emr_Modle_Check> checks = new ArrayList<>();
                List<Emr_Customize> customizes = emrCustomizeMapper.selectAll();
                List<Emr_Modle_RelatedVo> relateds = emrModleRelatedMapper.selectAllByModleId(id);
                //组织模板父集集合
                List<Emr_Customize> customize = new ArrayList<>();
                if (null != customizes && !customizes.isEmpty()) {
                    for (Emr_Customize customize1 : customizes) {
                        if (customize1.getParentId() == 0) {
                            customize.add(customize1);
                        }
                    }
                }
                //组织模板子集集合
                if (null != customizes && !customizes.isEmpty()) {
                    for (Emr_Customize c : customize) {
                        Emr_Modle_Check check = new Emr_Modle_Check();
                        List<Emr_Customize> data = new ArrayList<>();
                        for (Emr_Customize customize1 : customizes) {
                            if (c.getId().equals(customize1.getParentId())) {
                                check.setId(c.getId());
                                check.setColumnName(c.getColumnName());
                                //判断是否选中
                                if (null != relateds && !relateds.isEmpty()) {
                                    for (Emr_Modle_RelatedVo related : relateds) {
                                        if (related.getCustomizeId().equals(customize1.getId())) {
                                            customize1.setChecked("true");
                                            break;
                                        }
                                    }
                                }
                                data.add(customize1);
                            }
                        }
                        check.setData(data);
                        checks.add(check);
                    }
                }
                model.addAttribute("checks", checks);
                model.addAttribute("modleId", id);
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "recordManage/templateSearch/templateSelectIframe";
    }

    /**
     * @MethodName: addModleRelated
     * @Description: Integer modleId：模板id,String checks:客户自定义字段集合，“，”拼接
     * @Param 无
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-23
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-23
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/addModleRelated")
    @OptionalLog(module = "保存", methods = "自定义模板分配")
    @RequestMapping("addModleRelated")
    @ResponseBody
    public ResultUtil addModleRelated(Integer modleId, String checks, HttpServletRequest request) throws Exception {
        if (modleId != null && StringUtils.isNotBlank(checks)) {
            templateSearchService.addModleRelated(modleId, checks, request);
            return ResultUtil.ok();
        } else {
            return ResultUtil.error("modleId不能为空！");
        }
    }

    /***************************************自定义查询********************************************/
    //祈福医院
    @RequiresPermissions("/template/customSearchListqf")
    @OptionalLog(module = "查看", methods = "自定义查询页面")
    @RequestMapping("customSearchListqf")
    public String customSearchListqf(Model model, HttpServletRequest request) {
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<Emr_Modle> modles1 = new ArrayList<>();
        try {
            List<Emr_Modle> modles = emrModleMapper.selectAllByCreaterOrderSelect(user.getUserName());
            //添加id为1的
            Emr_Modle sysModle = emrModleMapper.selectByPrimaryKey(1);
            //判断是否有选中
            boolean flagExist = false;
            if (null != modles && !modles.isEmpty()) {
                //定义是否有选中
                for (Emr_Modle modle : modles) {
                    if (modle.getSelectFlag() == 1) {
                        flagExist = true;
                        break;
                    }
                }
            }
            if (flagExist) {
                modles1.addAll(modles);
                modles1.add(sysModle);
            } else {
                modles1.add(sysModle);
                assert modles != null;
                modles1.addAll(modles);
            }
            model.addAttribute("modles", modles1);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "recordManage/templateSearch/customSearchListqf";
    }

    //祈福医院
    @RequestMapping("customSearchIframeqf")
    public String customSearchIframeqf(Integer selectFlagId, Model model) {
        if (null != selectFlagId) {
            try {
                List<Emr_Modle_RelatedVo> relateds = emrModleRelatedMapper.selectAllByModleId(selectFlagId);
                model.addAttribute("relateds", relateds);
                //列名转属性名
                if (null != relateds && !relateds.isEmpty()) {
                    StringBuilder fields = new StringBuilder();
                    for (Emr_Modle_RelatedVo related : relateds) {
                        String columnValue = related.getColumnValue();
                        String field = BeanFieldToValue.column2modelProperty(columnValue);
                        fields.append(field).append(",");
                    }
                    model.addAttribute("fields", fields);
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
        return "recordManage/templateSearch/customSearchIfameqf";
    }

    //加载申请借阅类型
    @RequestMapping("getLoadApplyType")
    @ResponseBody
    public String getLoadApplyType() {
        try {
            //加载借阅的申请类型
            List<Emr_Dictionary> applyTypes = dictionaryMapper.selectDictionaryByTypeCode("apply_type");
            return JSON.toJSONString(applyTypes);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }

    }

    //加载通过审批且未过期的patientId集合
    @RequestMapping("getApproves")
    @ResponseBody
    public String getApproves(HttpServletRequest request, int type) {
        try {
            //查询通过审批且未过期的patientId集合
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String userName = user.getUserName();
            List<Emr_Apply_Approve> approveList = applyApproveMapper.selectPatientIdsByUser(userName, null, type);
            StringBuilder approves = new StringBuilder();
            if (null != approveList && !approveList.isEmpty()) {
                for (Emr_Apply_Approve emr_apply_approve : approveList) {
                    approves.append(emr_apply_approve.getPatientId()).append(",");
                }
            }
            return JSON.toJSONString(approves);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    //查询已锁定的集合
    @RequestMapping("getLocks")
    @ResponseBody
    public String getLocks() {
        try {
            //查询已锁定的集合
            List<Emr_Lock> emr_locks = lockMapper.selectLockListByStatus(1);
            StringBuilder locks = new StringBuilder();
            if (null != emr_locks && !emr_locks.isEmpty()) {
                for (Emr_Lock emr_lock : emr_locks) {
                    locks.append("'").append(emr_lock.getPatientId()).append("',");
                }
            }
            return JSON.toJSONString(locks);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: cutomSearchTable
     * @Description: 根据模板搜索条件动态查询数据
     * @Param sql:查询语句
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-23
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-23
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "cutomSearchTable", produces = {"text/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    public String cutomSearchTable(String selectSql,String fromTableSql,String whereSql,String orderBys,Integer page, Integer limit, HttpServletRequest request,String sortNames,String sortOrder) {
        //匹配权限
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        if (!sortNames.equals("id")&&!sortNames.equals("id")){
            if (sortNames.equals("disDate")){
                orderBys="order by commomtable.dis_date"+" "+sortOrder;
            }
            if (sortNames.equals("admissDate")){
                orderBys="order by commomtable.admiss_date"+" "+sortOrder;
            }
            if (sortNames.equals("admissId")){
                orderBys="order by commomtable.admiss_id"+" "+sortOrder;
            }
            if (sortNames.equals("inpatientNo")){
                orderBys="order by commomtable.inpatient_no"+" "+sortOrder;
            }
        }
        String sql = getSql(selectSql, fromTableSql, whereSql, orderBys, user);
        if (StringUtils.isNoneBlank(selectSql)) {
            if (null != page && null != limit) {
                PageHelper.startPage(page, limit);
            }
            try {
                List<CommomVo> commomVos = commomMapper.selectAll(sql);
                Set<String> menus = user.getMenus();
                if (null != commomVos && !commomVos.isEmpty()) {
                    if (null != menus && !menus.isEmpty()) {
                        int lockOper = 0;
                        int unlockOper = 0;
                        int borrowingOper = 0;
                        int downloadOper = 0;
                        int editOper = 0;
                        int delOper = 0;
                        for (String menu : menus) {
                            if (StringUtils.isNotBlank(menu)) {
                                if ("/commom/addLockByPatientId".equals(menu)) {
                                    lockOper = 1;
                                }
                                if ("/commom/updateLockByPatientId".equals(menu)) {
                                    unlockOper = 1;
                                }
                                if ("/commom/addApplyApprove".equals(menu)) {
                                    borrowingOper = 1;
                                }
                                if ("/commom/downloadPdf".equals(menu)) {
                                    downloadOper = 1;
                                }
                                if ("/commom/updateRecord".equals(menu)) {
                                    editOper = 1;
                                }
                                if ("/commom/deleteRecord".equals(menu)) {
                                    delOper = 1;
                                }
                            }
                        }
                        List<Emr_Fun_Group_Distribution> distributions = new ArrayList<>();
                        //查询是否有免申请查看病案权限
                        if (user.getRoleId() != 0) {
                            distributions = funGroupDistributionService.selectUserIdsByTypeFlag("approve", user.getUserId());
                        }
                        EmrComomSet emrComomSet = emrComomSetMapper.selectByPrimaryKey(1);
                        for (CommomVo commom : commomVos) {
                            commom.setLockOper(lockOper);
                            commom.setUnlockOper(unlockOper);
                            commom.setBorrowingOper(borrowingOper);
                            commom.setDownloadOper(downloadOper);
                            commom.setEditOper(editOper);
                            commom.setDelOper(delOper);
                            //判断是否是本科室
                            boolean isDeptShow = judgeThisDeptPatient(commom,emrComomSet.getIsDeptShow(),user.getRemark());
                            if (null != distributions && !distributions.isEmpty() || user.getRoleId() == 0 || isDeptShow) {
                                commom.setIsShowDetail(1);
                            }
                        }
                    }
                }
                assert commomVos != null;
                PageInfo pageInfo = new PageInfo<>(commomVos);
                return JSON.toJSONString(pageInfo);
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    private String getSql(String selectSql, String fromTableSql, String whereSql, String orderBys, Power_User user) {
        String userName = user.getUserName();
        String initSelectSql = "select commomtable.patient_id,CASE WHEN emr_apply_approve.id is null THEN 0 ELSE 1 END isShowDetail,CASE WHEN emr_apply_approve1.id IS NULL THEN 0 ELSE 1 END isDownload,CASE WHEN emr_lock.id is null THEN 0 ELSE 1 END lockStatus";
        if(StringUtils.isNotBlank(selectSql)){
            initSelectSql += "," + selectSql;
        }
        String initFromTableSql = " from commomtable left join emr_apply_approve on commomtable.patient_id = emr_apply_approve.patient_id and emr_apply_approve.approve_state = 1 and emr_apply_approve.effe_time > GETDATE()-1 and emr_apply_approve.applyer = '" +userName+ "' and emr_apply_approve.apply_type != 3 left join emr_apply_approve emr_apply_approve1 on commomtable.patient_id = emr_apply_approve1.patient_id and emr_apply_approve1.approve_state = 1 and emr_apply_approve1.effe_time > GETDATE()-1 and emr_apply_approve1.applyer = '" +userName+ "' and emr_apply_approve1.apply_type = 3 left join emr_lock on commomtable.patient_id = emr_lock.patient_id and emr_lock.lock_state = 1 ";
        if(StringUtils.isNotBlank(fromTableSql)){
            initFromTableSql += fromTableSql;
        }
        String sql = initSelectSql + initFromTableSql;
        if(StringUtils.isNotBlank(whereSql) && !"undefined".equals(whereSql)){
            sql += whereSql;
        }
        if(StringUtils.isNotBlank(orderBys)){
            sql += orderBys;
        }
        return sql;
    }

    /**
     * @Description: judgeThisDeptPatient方法是判断是否是属于本科室免申请直接查看
     * @param: [commom]
     * @return: boolean
     * @author 曾文和
     * @createTime 2022/7/26 0:44
     */

    private boolean judgeThisDeptPatient(CommomVo commom,Integer isDeptShow,String powerDepts) {
        //查询是否需要属于本科室免申请直接查看
        if(null != isDeptShow && isDeptShow == 1){
            //获取出院科室
            String disDept = commom.getDisDept();
            if(StringUtils.isNoneBlank(powerDepts)){
                //分割管辖科室名称
                String[] powerDeptList = powerDepts.split(",");
                for(String deptName : powerDeptList){
                    if(StringUtils.isNoneBlank(disDept) && disDept.equals(deptName)){
                        return true;
                    }
                }

            }
        }
        return false;
    }

    /**
     * 南方医院无登录查询
     * @param sql
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @RequestMapping(value = "cutomSearchTableSouth", produces = {"text/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    public String cutomSearchTableSouth(String sql, Integer page, Integer limit, HttpServletRequest request) {
        if (StringUtils.isNoneBlank(sql)) {
            if (null != page && null != limit) {
                PageHelper.startPage(page, limit);
            }
            try {
                List<CommomVo> commomVos = commomMapper.selectAll(sql);
                //匹配权限
                String userName = (String) request.getSession().getAttribute("cuserName");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (null != commomVos && !commomVos.isEmpty()) {
                    for (CommomVo vo:commomVos) {
                        Emr_Apply_Approve approve = applyApproveMapper.selectByApplyerAndPatientId(userName, vo.getPatientId());
                        if (null != approve) {
                            Date date = sdf.parse(approve.getEffeTime());
                            Calendar calendar = new GregorianCalendar();
                            calendar.setTime(date);
                            calendar.add(calendar.DATE, 1);
                            date = calendar.getTime();
                            if ("1".equals(approve.getApproveState()) && new Date().compareTo(date) < 0){
                                vo.setBorrowingOper(1);
                            } else if (approve.getApprover() == null && approve.getApproveState() == null) {
                                vo.setBorrowingOper(2);
                            } else {
                                vo.setBorrowingOper(0);
                            }
                        } else {
                            vo.setBorrowingOper(0);
                        }
                    }
                }
                assert commomVos != null;
                PageInfo pageInfo = new PageInfo<>(commomVos);
                return JSON.toJSONString(pageInfo);
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * @MethodName: exportExcel
     * @Description: 根据模板搜索条件导出excel
     * @Param String sql:查询语句,String fields：需要导出的字段
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-28
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-28
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/exportExcel"})
    @OptionalLog(module = "导出excel", methods = "病案查询页面")
    @RequestMapping(value = "exportExcel", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response,HttpServletRequest request, String selectSql,String fromTableSql,String whereSql,String orderBys, String fieldCns, String tableThNames) {
        try {
            //匹配权限
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String sql = getSql(selectSql, fromTableSql, whereSql, orderBys, user);
            //构造excel的数据
            List<CommomVo> list = commomMapper.selectAll(sql);
            //文件名
            String fileName = "档案管理常用查询导出数据(" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames, fieldCns, list, fileName, response);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }

    //脐血库、祈福

    /**
     * @MethodName: downloadBloodZip
     * @Description: 根据patientId集合批量下载图片并打包
     * @Param String patientIds:patientIds集合
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/downloadZip"})
    @OptionalLog(module = "下载图片转换pdf压缩包", methods = "病案查询页面")
    @RequestMapping(value = "downloadBloodZip", produces = {"text/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    public void downloadBloodZip(HttpServletResponse response, String patientIds, String flag) {

        if (StringUtils.isNoneBlank(patientIds)) {
            try {
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds, null, flag);
                if (null != scanPathVos && !scanPathVos.isEmpty()) {
                    Set<ScanPathForPatientListVo> list = new LinkedHashSet<>();
                    Set<String> patientIdSet = new LinkedHashSet<>();
                    //批量添加下载记录
                    printOrDownLoadInfoService.SimpleInsert(scanPathVos, null, Short.valueOf("2"));
                    for (ScanPathVo scanPathVo : scanPathVos) {
                        patientIdSet.add(scanPathVo.getPatientId());
                    }
                    for (String patinetId : patientIdSet) {
                        ScanPathForPatientListVo vo = new ScanPathForPatientListVo();
                        List<String> filePaths = new ArrayList<>();
                        for (ScanPathVo scanPathVo : scanPathVos) {
                            if (scanPathVo.getPatientId().equals(patinetId)) {
                                vo.setName(scanPathVo.getName());
                                vo.setInpatientNo(scanPathVo.getInpatientNo());
                                String disDate = scanPathVo.getDisDate();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                vo.setDisDate(sdf.parse(disDate));
                                String fileRealPath = scanPathVo.getFileRealPath();
                                if (StringUtils.isNoneBlank(fileRealPath) && new File(fileRealPath).exists()) {
                                    filePaths.add(fileRealPath);
                                }
                            }
                        }
                        if (!filePaths.isEmpty()) {
                            vo.setScanPathList(filePaths);
                            list.add(vo);
                        }
                    }
                    String zipName = "档案pdf压缩包";
                    downloadPdfZip(response, zipName, list);
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
        //以前的方法
//        if (StringUtils.isNoneBlank(patientIds)) {
//            try {
//                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds, null, flag);
//                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)){
////                            filePaths.add(fileRealPath);
////                        }
////                    }
////                    String zipName = "数字病案图片压缩包";
////                    downloadZip1(response,zipName,filePaths);
////                }
//                if (null != scanPathVos && !scanPathVos.isEmpty()) {
//                    // 创建临时路径,存放压缩文件
//                    File file = new File("D:/tmp");
//                    //查询保存文件目录是否存在
//                    createFile(file);
//                    // 压缩输出流,包装流,将临时文件输出流包装成压缩流,将所有文件输出到这里,打成zip包
//                    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(file));
//                    // 循环调用压缩文件方法,将一个一个需要下载的文件打入压缩文件包
//                 for (int i = 0; i < scanPathVos.size(); i++) {
//                       String fileRealPath = scanPathVos.get(i).getFileRealPath();
//                        if(StringUtils.isNoneBlank(fileRealPath)){
//                           filePaths.add(fileRealPath);
//                       }
//                   }
//                    for (String path : filePaths) {
//                        // 该方法在下面定义
//                        fileToZip(path, zipOut);
//                    }
//                    // 压缩完成后,关闭压缩流
//                    zipOut.close();
//
//                    //拼接下载默认名称并转为ISO-8859-1格式
//                    String fileName = new String(("我的压缩文件.zip").getBytes(),"ISO-8859-1");
//                    response.setHeader("Content-Disposition", "attchment;filename="+fileName);
//
//                    //该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
//                    ServletOutputStream outputStream = response.getOutputStream();
//                    FileInputStream inputStream = new FileInputStream("D:/tmp");
//                    // 如果是SpringBoot框架,在这个路径
//                    // org.apache.tomcat.util.http.fileupload.IOUtils产品
//                    // 否则需要自主引入apache的 commons-io依赖
//                    // copy方法为文件复制,在这里直接实现了下载效果
//                    IOUtils.copy(inputStream, outputStream);
//
//                    // 关闭输入流
//                    inputStream.close();
//
//                    //下载完成之后，删掉这个zip包
//                    File fileTempZip = new File("D:/tmp");
//                    fileTempZip.delete();
//                }
//            } catch (Exception e) {
//                ExceptionPrintUtil.printException(e);
//                e.printStackTrace();
//            }
//        }
    }

    public void createFile(File file) {
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
    }
    public static void fileToZip(String filePath,ZipOutputStream zipOut) throws IOException {
        // 需要压缩的文件
        File file = new File(filePath);
        // 获取文件名称,如果有特殊命名需求,可以将参数列表拓展,传fileName
        String fileName = file.getName();
        FileInputStream fileInput = new FileInputStream(filePath);
        // 缓冲
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
        // 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称
        zipOut.putNextEntry(new ZipEntry(fileName));
        int length = 0;
        // 最常规IO操作,不必紧张
        while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write(bufferArea, 0, length);
        }
        //关闭流
        fileInput.close();
        // 需要注意的是缓冲流必须要关闭流,否则输出无效
        bufferStream.close();
        // 压缩流不必关闭,使用完后再关
    }



    public void downloadBloodZip1(HttpServletResponse response, String patientIds, String flag) {
        if (StringUtils.isNoneBlank(patientIds)) {
            try {
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds, null, flag);
                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)){
                            filePaths.add(fileRealPath);
                        }
                    }
                    String zipName = "数字病案图片压缩包";
                    downloadZip1(response,zipName,filePaths);
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
    }





    public static void downloadZip1(HttpServletResponse response,String zipName,List<String> filePaths){
        try {
            zipName = java.net.URLEncoder.encode(zipName, "UTF-8");
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + zipName + "("+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +").zip");
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bos = new BufferedOutputStream(zos);
            for (int i = 0; i < filePaths.size(); i++) {
                String base = filePaths.get(i);
                File realFile = new File(base);
                if(realFile.exists()) {
                    String fileName = base.substring(base.lastIndexOf("\\")+1);         //每个文件名
                    zos.putNextEntry(new ZipEntry(fileName));
                    //读入转字节流
                    InputStream in = new FileInputStream(base);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int n = 0;
                    while ((n = in.read(buffer)) != -1) {
                        out.write(buffer, 0, n);
                    }
                    byte[] file = out.toByteArray();       //这个zip文件的字节
                    BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
                    //输出
                    int len = 0;
                    byte[] buf = new byte[10 * 1024];
                    while( (len=bis.read(buf, 0, buf.length)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bis.close();
                    bos.flush();
                }
            }
            bos.close();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }


    //封装下载pdf压缩包方法
    private void downloadPdfZip(HttpServletResponse response, String zipName, Set<ScanPathForPatientListVo> list) {
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ZipOutputStream zos = null;
        BufferedOutputStream bos = null;
        ByteArrayOutputStream out = null;
        BufferedInputStream bis = null;
        try {
            zipName = java.net.URLEncoder.encode(zipName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + zipName + "(" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ").zip");
            zos = new ZipOutputStream(response.getOutputStream());
            bos = new BufferedOutputStream(zos);
            EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
            for (ScanPathForPatientListVo vo : list) {
                String disDate = "";
                if (null != vo.getDisDate()) {
                    disDate = fmt.format(vo.getDisDate());
                }
                List<String> scanPathList = vo.getScanPathList();
                //每个文件名
                String fileName = vo.getInpatientNo().trim() + "-" + vo.getName().trim() + "-" + disDate.trim() + "_" + fmt.format(new Date());
                zos.putNextEntry(new ZipEntry(fileName + ".pdf"));
                //合成pdf
                out = new ByteArrayOutputStream();
                img2PdfUtil.imageToPdfToBuffOut(out, scanPathList, emrPdfWaterSet);
                byte[] file = out.toByteArray();       //这个zip文件的字节
                bis = new BufferedInputStream(new ByteArrayInputStream(file));
                //输出
                int len = 0;
                byte[] buf = new byte[1024 * 1024];
                while ((len = bis.read(buf, 0, buf.length)) != -1) {
                    bos.write(buf, 0, len);
                }
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            try {
                if (null != bos) {
                    bos.flush();
                    bos.close();
                }
                if (null != bis) {
                    bis.close();
                }
                out.flush();
                out.close();
                if (null != zos) {
                    zos.flush();
                    zos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
    /**
     * @MethodName: getPatientIdsBySql
     * @Description: 根据patientId集合下载PDF
     * @Param String patientIds:patientIds集合
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "getPatientIdsBySql")
    @ResponseBody
    public String getPatientIdsBySql(String sql) {
        if (StringUtils.isNoneBlank(sql)) {
            try {
                StringBuilder json = new StringBuilder();
                List<CommomVo> list = commomMapper.selectAll(sql);
                if (null != list && !list.isEmpty()) {
                    for (CommomVo commomVo : list) {
                        json.append("'").append(commomVo.getPatientId()).append("',");
                    }
                }
                return JSON.toJSONString(json);
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * @MethodName: downloadPdf
     * @Description: 根据patientId集合下载PDF
     * @Param String patientIds:patientIds集合
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/downloadPdf"})
    @OptionalLog(module = "下载PDF", methods = "病案查询页面")
    @RequestMapping(value = "downloadPdf", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void downloadPdf(HttpServletResponse response, String patientIds) {
        if (StringUtils.isNoneBlank(patientIds)) {
            try {
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByPatientIds(patientIds, null);
                List<String> filePaths = new ArrayList<>();
                if (null != scanPathVos && !scanPathVos.isEmpty()) {
                    for (ScanPathVo scanPathVo : scanPathVos) {
                        String fileRealPath = scanPathVo.getFileRealPath();
                        if (StringUtils.isNoneBlank(fileRealPath)) {
                            filePaths.add(fileRealPath);
                        }
                    }
                    String pdfName = "数字病案PDF";
                    Jpg2PdfUtil.imageToPdf(response, filePaths, pdfName);
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
    }

    //脐血库、祈福
    @RequestMapping(value = "getScanCountByPatientId")
    @ResponseBody
    public String getScanCountByPatientId(String patientId, String flag) {
        if (StringUtils.isNoneBlank(patientId)) {
            try {
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientId(patientId, null, flag);
                if (null != scanPathVos && !scanPathVos.isEmpty()) {
                    return "1";
                }
                List<CommomTree> commomTrees = archiveDetailMapper.selectPdfPathByPatient3(patientId, null);
                if (null != commomTrees && !commomTrees.isEmpty()){
                    return "1";
                }

            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
        return "0";
    }

    //脐血库、祈福
    @RequiresPermissions(value = {"/commom/downloadPdf"})
    @RequestMapping(value = "downloadPdfBlood", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void downloadPdfBlood(HttpServletResponse response, String patientIds, String assortIds, Integer typeId, String flag) {
        if (StringUtils.isNoneBlank(patientIds)) {
            try {
                if (StringUtils.isNotBlank(assortIds)) {
                    String[] assortIdStr = assortIds.split(",");
                    StringBuilder assortIdsBuilder = new StringBuilder();
                    for (int i = 0; i < assortIdStr.length; i++) {
                        if (i != assortIdStr.length - 1) {
                            assortIdsBuilder.append("'").append(assortIdStr[i]).append("',");
                        } else {
                            assortIdsBuilder.append("'").append(assortIdStr[i]).append("'");
                        }
                    }
                    assortIds = assortIdsBuilder.toString();
                }
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds1(patientIds, assortIds, flag);
                if (null != scanPathVos && !scanPathVos.isEmpty()) {
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    //批量添加下载记录
                    printOrDownLoadInfoService.SimpleInsert(scanPathVos, typeId, Short.valueOf("2"));
                    //每个文件名
                    String pdfName = exportFlieName(scanPathVos);
                    //emrPdfWaterSet设置启用下载的状态
                    emrPdfWaterSet.setEffective(emrPdfWaterSet.getDownloadEffective());
                    emrPdfWaterSet.setIsImg(emrPdfWaterSet.getDownloadIsImg());
                    EmrPdfWaterSet emrPdfWaterSet1 = commomService.getEmrPdfWaterSet(emrPdfWaterSet);
                    imgToPdfUtil.imageToPdf(response, scanPathVos, pdfName, emrPdfWaterSet,emrPdfWaterSet1);
                }else {
                    String fileRealPath=null;
                    List<CommomTree> commomTrees = archiveDetailMapper.selectPdfPathByPatient3(patientIds, assortIds);
                    List<String> filePaths = new ArrayList();
                    for (int i = 0; i < commomTrees.size(); ++i) {
                        fileRealPath =  commomTrees.get(i).getPDFPATH();
                        if (StringUtils.isNoneBlank(new CharSequence[]{fileRealPath})) {
                            filePaths.add(fileRealPath);
                        }
                    }
                    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
                    List<ScanPathVo> scanPathVos1 = scanPathMapper.selectFilaname(patientIds);
                    ScanPathVo vo = scanPathVos1.get(0);
                    String disDate = "";
                    if (null != vo.getDisDate()) {
                        disDate = fmt.format(vo.getDisDate());
                    }
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    //下载文件名
                    String filename = vo.getInpatientNo().trim() + "-" + vo.getName().trim() + "-" + disDate.trim() + "_" + fmt.format(new Date());
                    Jpg2PdfUtil.mulFile2One3(response,filePaths,filename,emrPdfWaterSet);
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
    }

    private String  exportFlieName(List<ScanPathVo> scanPathVos) throws ParseException {
        StringBuffer sb = new StringBuffer();
        sb.append(hospitaInfo);
        ScanPathVo scanPathVo = scanPathVos.get(0);
        JSONObject jsonObject= (JSONObject) JSONObject.toJSON(scanPathVo);
        List<String> patientInfoList = Arrays.asList(patientInfo.split(","));
        for (String list:patientInfoList){
            String contents = jsonObject.getString(list).trim();
            if (list.equals("disDate")){
                String dateString = jsonObject.getString(list);
                SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
                Date date = originalFormat.parse(dateString);
                String formattedDate = targetFormat.format(date);
                sb.append("_"+formattedDate);
            }else {
                sb.append("_"+contents);
            }
        }
        return sb.toString();
    }

    /**
     * 移动图片路径
     *
     * @param response
     * @param oldPatientId
     * @param newPatientId
     * @param assortIds
     * @param newAssortId
     * @param flag
     * @return
     */
    @RequiresPermissions(value = {"/commom/movePdf"})
    @RequestMapping(value = "movePdfBlood", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil movePdfBlood(HttpServletResponse response, String oldPatientId, String newPatientId, String assortIds, String newAssortId, String flag) {
        if (StringUtils.isNoneBlank(oldPatientId) && StringUtils.isNoneBlank(newPatientId)) {
            if (StringUtils.isNotBlank(assortIds)) {
                String[] assortIdStr = assortIds.split(",");
                StringBuilder assortIdsBuilder = new StringBuilder();
                for (int i = 0; i < assortIdStr.length; i++) {
                    if (i != assortIdStr.length - 1) {
                        assortIdsBuilder.append("'").append(assortIdStr[i]).append("',");
                    } else {
                        assortIdsBuilder.append("'").append(assortIdStr[i]).append("'");
                    }
                }
                assortIds = assortIdsBuilder.toString();
            }
            oldPatientId = "'" + oldPatientId + "'";
            List<ScanPathVo> oldScanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(oldPatientId, assortIds, flag);
            CommomVo commomVo = commomMapper.selectByPrimaryKey(newPatientId);
            if (null == commomVo) {
                return ResultUtil.error("目标病案不存在!");
            }
            if (null != oldScanPathVos && !oldScanPathVos.isEmpty()) {
                for (ScanPathVo scanPathVo : oldScanPathVos) {
                    String newFile =  commomVo.getFilePath() + "\\" + scanPathVo.getScanPage();
                    String oldFile = scanPathVo.getFileRealPath();
                    try {
                        templateSearchService.movePdf(oldFile, newFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String sql = "UPDATE dbo.t_scan_assort SET patient_id = '"+ newPatientId +"', assort_id = '" + newAssortId +
                            "' WHERE patient_id = " + oldPatientId + " AND scan_page = '" + scanPathVo.getScanPage() + "'";
                    scanPathMapper.updateScanFileByPatientIdAndScanPage(sql);
                }
            }
            return  ResultUtil.ok();
        }
        return ResultUtil.error("程序出现错误,请联系管理员进行处理!");
    }

    /**
     * @MethodName: printInfoBlood
     * @Description: 根据patientId集合批量下载图片并打包
     * @Param String patientIds:patientIds集合
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "打印病案", methods = "病案预览页面")
    @RequestMapping(value = "printInfoBlood", produces = {"text/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    public void printInfoBlood(String patientIds, String assortIds, Integer typeId, String flag) {
        if (StringUtils.isNoneBlank(patientIds)) {
            try {
                if (StringUtils.isNotBlank(assortIds)) {
                    String[] assortIdStr = assortIds.split(",");
                    StringBuilder assortIdsBuilder = new StringBuilder();
                    for (int i = 0; i < assortIdStr.length; i++) {
                        if (i != assortIdStr.length - 1) {
                            assortIdsBuilder.append("'").append(assortIdStr[i]).append("',");
                        } else {
                            assortIdsBuilder.append("'").append(assortIdStr[i]).append("'");
                        }
                    }
                    assortIds = assortIdsBuilder.toString();
                    List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds, assortIds, flag);
                    //批量添加打印记录
                    printOrDownLoadInfoService.SimpleInsert(scanPathVos, typeId, Short.valueOf("1"));
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        }
    }

    /**
     * @MethodName: addLockByPatientId
     * @Description: 添加锁定
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/addLockByPatientId"})
    @OptionalLog(module = "新增", methods = "病案查询页面病案锁定")
    @RequestMapping("addLockByPatientId")
    @ResponseBody
    public ResultUtil addLockByPatientId(String patientIds, HttpServletRequest request) throws Exception {
        List<CommomVo> commomtables = commomMapper.selectAllByPatients(patientIds);
        if (null != commomtables && !commomtables.isEmpty()) {
            lockService.insert(commomtables, request);
            return ResultUtil.ok();
        } else {
            return null;
        }
    }

    /**
     * @MethodName: updateLockByPatientId
     * @Description: 解除锁定
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/updateLockByPatientId"})
    @OptionalLog(module = "修改", methods = "病案查询页面病案锁定")
    @RequestMapping("updateLockByPatientId")
    @ResponseBody
    public ResultUtil updateLockByPatientId(String patientId, HttpServletRequest request) throws Exception {
        if (StringUtils.isNoneBlank(patientId)) {
            Emr_Lock lock = lockMapper.selectLockByPatientId(patientId, 1);
            if (null != lock) {
                lockService.udpate(lock, request);
            }
            return ResultUtil.ok();
        } else {
            return null;
        }
    }

    /**
     * @MethodName: updateLockByPatientIds
     * @Description: 批量解除锁定
     * @Param String patientIds:patientIds
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions(value = {"/commom/updateLockByPatientId"})
    @OptionalLog(module = "批量修改", methods = "病案查询页面病案锁定")
    @RequestMapping("updateLockByPatientIds")
    @ResponseBody
    public ResultUtil updateLockByPatientIds(String patientIds, HttpServletRequest request) throws Exception {
        if (StringUtils.isNoneBlank(patientIds)) {
            lockService.udpateUnlockByPatients(patientIds, request);
            return ResultUtil.ok();
        } else {
            return null;
        }
    }
}
