package com.emr.controller.templateSearch;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.controller.FormTokenFlagUtil;
import com.emr.dao.CommomMapper;
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.Emr_Dictionary;
import com.emr.entity.Emr_Fun_Group_Distribution;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
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.CommomVo;
import com.emr.vo.commomSearch.ScanPathForPatientListVo;
import com.emr.vo.commomSearch.ScanPathVo;
import com.emr.vo.templateSearch.Emr_Modle_RelatedVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
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;
    /**
     * @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) {
        try{
            List<Emr_Customize> parents = customizeMapper.selectParents();
            model.addAttribute("parents",parents);
            String formToken = UUID.randomUUID().toString();
            request.getSession().setAttribute("formToken",formToken);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "recordManage/templateSearch/templateList1";
    }

    @RequestMapping("getParentSelect")
    @ResponseBody
    public Msg getParentSelect(HttpServletRequest request) {
        try{
            List<Emr_Customize> parents = customizeMapper.selectParents();
            return Msg.success().add("list",parents);
        }catch (Exception 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) {
        try{
            Integer id = customizeMapper.selectListCheckName(parentId, columnName);
            if (id != null) {
                return ResultUtil.error();
            } else {
                return ResultUtil.ok();
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * @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) {
        try {
            Integer existId = customizeMapper.checkColumnExist(columnValue, tableValue);
            if (existId == null || id.equals(existId)) {
                return ResultUtil.ok();
            } else {
                return ResultUtil.error();
            }
        }catch (Exception e){
            e.printStackTrace();
            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) {
        try {
            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("请不要重复提交!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            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) {
        try {
            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();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("修改失败，请联系超管！");
        }
    }

    /**
     * @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() {
        try {
            //添加首级目录
            Emr_Customize customize = new Emr_Customize();
            customize.setId(0);
            customize.setColumnName("模板列表");
            List<Emr_Customize> list = new ArrayList<>();
            list.add(customize);
            List<Emr_Customize> templates = customizeMapper.selectAllByTree();
            list.addAll(templates);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(list);
            return json;
        } catch (Exception 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) {
        try {
            templateSearchService.deleteTemplate(id);
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /***************************************自定义模板选择********************************************/
    /**
     * @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);
            String formToken = UUID.randomUUID().toString();
            request.getSession().setAttribute("formToken",formToken);
        }catch (Exception e){
            e.printStackTrace();
        }
        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){
            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) {
        if ("系统默认模板".equals(modleFlag)) {
            return ResultUtil.error("该模板标识已存在！");
        }
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserId().toString();
        try {
            Emr_Modle modle = emrModleMapper.checkModleFlag(creater, modleFlag);
            if(modle == null){
                return ResultUtil.ok();
            }else{
                return ResultUtil.error("该模板标识已存在！");
            }
        }catch (Exception e){
            e.printStackTrace();
            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) {
        if ("系统默认模板".equals(modleName)) {
            return ResultUtil.error("该模板名称已存在！");
        }
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserId().toString();
        try {
            Emr_Modle modle = emrModleMapper.checkModleName(creater, modleName);
            if(modle == null){
                return ResultUtil.ok();
            }else{
                return ResultUtil.error("该模板名称已存在！");
            }
        }catch (Exception e){
            e.printStackTrace();
            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) {
        try {
            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("模板标识或模板名称不能为空!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            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){
                String creaters = CommomService.creaters(request);
                modleList = emrModleMapper.selectAllByCreater(creaters);
            }else{
                userName = "'" + userName + "'";
                modleList = emrModleMapper.selectAllByCreater(userName);
            }
            //设置默认模板选中
            if (null != modleList && !modleList.isEmpty()) {
                //定义是否有创建选中，有则取消系统的的选中
                Boolean flag = false;
                for (int i = 0; i < modleList.size(); i++) {
                    if (modleList.get(i).getSelectFlag() == 1 && modleList.get(i).getId() != 1 && modleList.get(i).getCreater().equals(userName)) {
                        modleList.get(i).setChecked("true");
                        flag = true;
                        break;
                    }
                }
                //有则取消系统的的选中,不是系统管理员roleId!=0系统模板isOper置为零
                for (int i = 0; i < modleList.size(); i++) {
                    if (modleList.get(i).getId() == 1) {
                        if (flag) {
                            modleList.get(i).setChecked("");
                        } else {
                            modleList.get(i).setChecked("true");
                        }
                    }
                }
            }
            List<Emr_Modle> modles = new ArrayList<>();
            Emr_Modle modle = new Emr_Modle();
            //添加父节点
            modle.setId(-1);
            modle.setModleName("模板选择列表");
            modles.add(modle);
            modles.addAll(modleList);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(modles);
            return json;
        } catch (Exception 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) {
        try {
            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("模板标志或模板名称不能为空!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            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) {
        try {
            //查询默认的，将默认的取消
            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("修改失败,该模板为客户创建,不建议修改");
            }
        } catch (Exception e) {
            e.printStackTrace();
            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) {
        try {
            templateSearchService.deleteTemplateSelect(id);
            return ResultUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * @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<>();
                if (id != null) {
                    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 (int i = 0; i < customizes.size(); i++) {
                            if (customizes.get(i).getParentId() == 0) {
                                customize.add(customizes.get(i));
                            }
                        }
                    }
                    //组织模板子集集合
                    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 (int i = 0; i < customizes.size(); i++) {
                                if (c.getId().equals(customizes.get(i).getParentId())) {
                                    check.setId(c.getId());
                                    check.setColumnName(c.getColumnName());
                                    //判断是否选中
                                    if (null != relateds && !relateds.isEmpty()) {
                                        for (int j = 0; j < relateds.size(); j++) {
                                            if (relateds.get(j).getCustomizeId().equals(customizes.get(i).getId())) {
                                                customizes.get(i).setChecked("true");
                                                break;
                                            }
                                        }
                                    }
                                    data.add(customizes.get(i));
                                }
                            }
                            check.setData(data);
                            checks.add(check);
                        }
                    }
                }
                model.addAttribute("checks", checks);
                model.addAttribute("modleId", id);
            }
        }catch (Exception 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) {
        if(modleId != null && StringUtils.isNotBlank(checks)){
            try {
                templateSearchService.addModleRelated(modleId, checks,request);
                return ResultUtil.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        }else{
            return ResultUtil.error("modleId不能为空！");
        }
    }
    /***************************************自定义查询********************************************/
    /**
     * @MethodName: customSearchList
     * @Description: 跳转到自定义查询页面
     * @Param  无
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-23
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-23
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/template/customSearchList")
    @OptionalLog(module = "查看",methods = "自定义查询页面")
    @RequestMapping("customSearchList")
    public String customSearchList(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);
                modles1.addAll(modles);
            }
            model.addAttribute("modles",modles1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "recordManage/templateSearch/customSearchList";
    }
    //祈福医院
    @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);
                modles1.addAll(modles);
            }
            model.addAttribute("modles",modles1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "recordManage/templateSearch/customSearchListqf";
    }

    /**
     * @MethodName: cutomSearchIframe
     * @Description: 跳转到自定义查询页面
     * @Param  selectFlagId：默认模板id
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-23
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-23
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("customSearchIframe")
    public String customSearchIframe(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()){
                    String fields = "";
                    for (int i = 0;i<relateds.size();i++){
                        String  columnValue = relateds.get(i).getColumnValue();
                        String field = BeanFieldToValue.column2modelProperty(columnValue);
                        fields += field + ",";
                    }
                    model.addAttribute("fields",fields);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return "recordManage/templateSearch/customSearchIfame";
    }
    //祈福医院
    @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()){
                    String fields = "";
                    for (int i = 0;i<relateds.size();i++){
                        String  columnValue = relateds.get(i).getColumnValue();
                        String field = BeanFieldToValue.column2modelProperty(columnValue);
                        fields += field + ",";
                    }
                    model.addAttribute("fields",fields);
                }
            }catch (Exception 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){
            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);
            String approves = "";
            if(null != approveList && !approveList.isEmpty()){
                for (int i = 0; i < approveList.size(); i++) {
                    approves += approveList.get(i).getPatientId() + ",";
                }
            }
            return JSON.toJSONString(approves);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查询已锁定的集合
    @RequestMapping("getLocks")
    @ResponseBody
    public String getLocks(){
        try {
            //查询已锁定的集合
            List<Emr_Lock> emr_locks = lockMapper.selectLockListByStatus(1);
            String locks = "";
            if(null != emr_locks && !emr_locks.isEmpty()) {
                for (int i = 0; i < emr_locks.size(); i++) {
                    locks += "'" + emr_locks.get(i).getPatientId() + "',";
                }
            }
            return JSON.toJSONString(locks);
        }catch (Exception 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 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);
                //匹配权限
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                Set<String> menus = user.getMenus();
                if(null != commomVos && !commomVos.isEmpty()){
                    if(null != menus && !menus.isEmpty()){
                        Integer lockOper = 0;
                        Integer unlockOper = 0;
                        Integer borrowingOper = 0;
                        Integer downloadOper = 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;
                                }
                            }
                        }
                        List<Emr_Fun_Group_Distribution> distributions = new ArrayList<>();
                        //查询是否有免申请查看病案权限
                        if(user.getRoleId() != 0){
                            distributions = funGroupDistributionService.selectUserIdsByTypeFlag("approve", user.getUserId());
                        }
                        for (CommomVo commom : commomVos){
                            commom.setLockOper(lockOper);
                            commom.setUnlockOper(unlockOper);
                            commom.setBorrowingOper(borrowingOper);
                            commom.setDownloadOper(downloadOper);
                            if(null != distributions && !distributions.isEmpty() || user.getRoleId() == 0){
                                commom.setIsShowDetail(1);
                            }
                        }
                    }
                }
                PageInfo pageInfo = new PageInfo<>(commomVos);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(pageInfo);
                return json;
            }catch (Exception 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, String sql, String fieldCns,String tableThNames) throws Exception {
        if (StringUtils.isNoneBlank(sql)) {
            try {
                //中文转换和%转义
                sql = sql.replaceAll("%25","%");
                //构造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){
                e.printStackTrace();
            }
        }
    }
    /**
     * @MethodName: downloadZip
     * @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 = "下载图片压缩包",methods = "病案查询页面")
    @RequestMapping(value="downloadZip",produces = {"text/json;charset=UTF-8"},method = RequestMethod.POST)
    @ResponseBody
    public void downloadZip(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 (int i = 0; i < scanPathVos.size(); i++) {
                        String fileRealPath = scanPathVos.get(i).getFileRealPath();
                        if(StringUtils.isNoneBlank(fileRealPath)){
                            filePaths.add(fileRealPath);
                        }
                    }
                    String zipName = "数字病案图片压缩包";
                    downloadZip(response,zipName,filePaths);
                }
            }catch (Exception 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 (int i = 0; i < scanPathVos.size(); i++) {
                        patientIdSet.add(scanPathVos.get(i).getPatientId());
                    }
                    for(String patinetId : patientIdSet){
                        ScanPathForPatientListVo vo = new ScanPathForPatientListVo();
                        List<String> filePaths = new ArrayList<>();
                        for (int i = 0; i < scanPathVos.size(); i++) {
                            if(scanPathVos.get(i).getPatientId().equals(patinetId)){
                                vo.setName(scanPathVos.get(i).getName());
                                vo.setInpatientNo(scanPathVos.get(i).getInpatientNo());
                                vo.setDisDate(scanPathVos.get(i).getDisDate());
                                String fileRealPath = scanPathVos.get(i).getFileRealPath();
                                if(StringUtils.isNoneBlank(fileRealPath) && new File(fileRealPath).exists()){
                                    filePaths.add(fileRealPath);
                                }
                            }
                        }
                        if(null != filePaths && !filePaths.isEmpty()){
                            vo.setScanPathList(filePaths);
                            list.add(vo);
                        }
                    }
                    String zipName = "档案pdf压缩包";
                    downloadPdfZip(response,zipName,list);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //封装下载压缩包方法
    public static void downloadZip(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) {
            e.printStackTrace();
        }
    }

    //封装下载pdf压缩包方法
    public  void downloadPdfZip(HttpServletResponse response,String zipName,Set<ScanPathForPatientListVo> list){
        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);
            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"));
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                //合成pdf
                img2PdfUtil.imageToPdfToBuffOut(out,scanPathList,fileName,emrPdfWaterSet);
                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) {
            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 {
                String json = "";
                long start = System.currentTimeMillis();
                List<CommomVo> list = commomMapper.selectAll(sql);
                long end = System.currentTimeMillis();
                //System.out.println("查询patiendId集合时间"+(end - start)/1000.0+"s");
                if(null != list && !list.isEmpty()) {
                    for (int i = 0; i < list.size(); i++) {
                        json += "'" + list.get(i).getPatientId() + "',";
                    }
                }
                return JSON.toJSONString(json);
            }catch (Exception 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) throws Exception {
        if (StringUtils.isNoneBlank(patientIds)) {
            try {
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByPatientIds(patientIds,null);
                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 pdfName = "数字病案PDF";
                    Jpg2PdfUtil.imageToPdf(response,filePaths,pdfName);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    //脐血库
    @RequestMapping(value="getScanCountByPatientId")
    @ResponseBody
    public String getScanCountByPatientId(String patientId,String flag){
        if (StringUtils.isNoneBlank(patientId)) {
            try {
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientId,null,flag);
                if(null != scanPathVos && !scanPathVos.isEmpty()){
                    return "1";
                }else{
                    return "0";
                }
            }catch (Exception 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(",");
                    assortIds = "";
                    for (int i = 0; i < assortIdStr.length; i++) {
                        if(i != assortIdStr.length - 1){
                            assortIds += "'" + assortIdStr[i] + "',";
                        }else{
                            assortIds += "'" + assortIdStr[i] + "'";
                        }
                    }
                }
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds,assortIds,flag);
                if(null != scanPathVos && !scanPathVos.isEmpty()){
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    //文件路径集合
                    List<String> filePaths = new ArrayList<>();
                    for (int i = 0; i < scanPathVos.size(); i++) {
                        String fileRealPath = scanPathVos.get(i).getFileRealPath();
                        if(StringUtils.isNoneBlank(fileRealPath)){
                            filePaths.add(fileRealPath);
                        }
                    }
                    //批量添加下载记录
                    printOrDownLoadInfoService.SimpleInsert(scanPathVos,typeId,Short.valueOf("2"));
                    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
                    ScanPathVo vo = scanPathVos.get(0);
                    String disDate = "";
                    if(null != vo.getDisDate()){
                        disDate = fmt.format(vo.getDisDate());
                    }
                    //每个文件名
                    String pdfName = vo.getInpatientNo().trim() + "-" + vo.getName().trim() + "-" + disDate.trim() + "_"+fmt.format(new Date());
                    //emrPdfWaterSet设置启用下载的状态
                    emrPdfWaterSet.setEffective(emrPdfWaterSet.getDownloadEffective());
                    emrPdfWaterSet.setIsImg(emrPdfWaterSet.getDownloadIsImg());
                    img2PdfUtil.imageToPdf(response,filePaths,pdfName,emrPdfWaterSet);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * @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(",");
                    assortIds = "";
                    for (int i = 0; i < assortIdStr.length; i++) {
                        if(i != assortIdStr.length - 1){
                            assortIds += "'" + assortIdStr[i] + "',";
                        }else{
                            assortIds += "'" + assortIdStr[i] + "'";
                        }
                    }
                }
                List<ScanPathVo> scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds,assortIds,flag);
                //批量添加下载记录
                printOrDownLoadInfoService.SimpleInsert(scanPathVos,typeId,Short.valueOf("1"));
            }catch (Exception 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){
        try{
            List<CommomVo> commomtables = commomMapper.selectAllByPatients(patientIds);
            if(null != commomtables && !commomtables.isEmpty()){
                lockService.insert(commomtables,request);
                return ResultUtil.ok();
            }else{
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
            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){
        try{
            if(StringUtils.isNoneBlank(patientId)){
                Emr_Lock lock = lockMapper.selectLockByPatientId(patientId,1);
                if(null != lock){
                    lockService.udpate(lock,request);
                }
                return ResultUtil.ok();
            }else{
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
            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){
        try{
            if(StringUtils.isNoneBlank(patientIds)){
                lockService.udpateUnlockByPatients(patientIds,request);
                return ResultUtil.ok();
            }else{
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
