package com.emr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emr.annotation.OptionalLog;
import com.emr.dao.Archive_DetailMapper;
import com.emr.dao.CommomMapper;
import com.emr.dao.Emr_DictionaryMapper;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.dao.emrPdfWaterSet.EmrPdfWaterSetMapper;
import com.emr.entity.Emr_Dictionary;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.Zd_Assort;
import com.emr.entity.approve.Emr_Apply_Approve;
import com.emr.entity.emrLog.Emr_Log;
import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.entity.recordType.Emr_Type;
import com.emr.entity.recordType.Emr_Type_Related;
import com.emr.service.CommomService;
import com.emr.service.Zd_AssortServiceImpl;
import com.emr.service.approve.ApplyApproveService;
import com.emr.service.emrLog.LogService;
import com.emr.service.emrPrintOrDownLoadInfo.PrintOrDownLoadInfoService;
import com.emr.service.recordType.EmrTypeRelatedService;
import com.emr.service.recordType.EmrTypeService;
import com.emr.util.*;
import com.emr.vo.EmrPrintOrDownLoadInfo.EmrPrintOrDownLoadInfoVo;
import com.emr.vo.User;
import com.emr.vo.commomSearch.CommomTree;
import com.emr.vo.commomSearch.CommomVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.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.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("font/")
public class FontShowRecordController {
    @Autowired
    private Archive_DetailMapper archiveDetailMapper;
    @Autowired
    private EmrPdfWaterSetMapper pdfWaterSetMapper;
    @Value("${waterPicPath}")
    private String WATERPICPATH;
    @Value("${EMR_RECORD_JSP}")
    private String EMRRECORDJSP;
    @Autowired
    private EmrTypeRelatedService typeRelatedService;
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private PrintOrDownLoadInfoService printOrDownLoadInfoService;
    @Autowired
    private CommomService commomService;
    @Autowired
    private LogService logService;
    @Autowired
    private ApplyApproveService applyApproveService;
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;


    /**
     * @MethodName recordList
     * @Description:
     * @Param
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2020-03-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-03-27
     * @Version: 1.0
     */
    @RequestMapping(value = "recordList")
    public String showRecord(String inpatientNo, String idCard, Model model, HttpServletRequest request) {
        try {
            //根据病案号查看病案是否存在
            if (StringUtils.isNotBlank(inpatientNo) || StringUtils.isNotBlank(idCard)) {
                int commom = commomMapper.isExistInpatientOrAdmissIdOridCard(inpatientNo, idCard, null, null);
                if (commom == 0) {
                    model.addAttribute("msg", "病案不存在!");
                    return "font/msg";
                }
            } else {
                model.addAttribute("msg", "参数病案号与参数身份证号不能全部为空!");
                return "font/msg";
            }
            //虚假登陆
            //验证shiro(有shiro才此操作)
            Power_User user = new Power_User();
            user.setUserName("第三方");
            user.setUserId(-999);
            user.setRoleId(-999);
            Set<String> menu = new TreeSet<>();
            user.setMenus(menu);
            UsernamePasswordToken userToken = new UsernamePasswordToken(user.getUserName(), "123456");
            Subject subject = SecurityUtils.getSubject();
            subject.login(userToken);
            request.getSession().setAttribute("CURRENT_USER", user);
            model.addAttribute("inpatientNo", inpatientNo);
            model.addAttribute("idCard", idCard);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "font/recordList";
    }

    /**
     * @description:
     * @params:
     * @return:
     * @author linjj
     * @date: 2023/7/31 8
     */
    @RequestMapping(value = "showRecordList")
    public String showRecordList(String inpatientNo, String idCard, Model model, HttpServletRequest request) {
        try {
            //根据病案号查看病案是否存在
            if (StringUtils.isNotBlank(inpatientNo) || StringUtils.isNotBlank(idCard)) {
                int commomMaster = commomMapper.selectAllMaster(inpatientNo, idCard);
                int commom = commomMapper.isExistInpatientOrAdmissIdOridCard(inpatientNo, idCard, null, null);
                if (commom == 0 && commomMaster == 0) {
                    model.addAttribute("msg", "病案不存在!");
                    return "font/msg";
                }
            } else {
                model.addAttribute("msg", "参数病案号与参数身份证号不能全部为空!");
                return "font/msg";
            }
            //虚假登陆
            //验证shiro(有shiro才此操作)
            Power_User user = new Power_User();
            user.setUserName("第三方");
            user.setUserId(-999);
            user.setRoleId(-999);
            Set<String> menu = new TreeSet<>();
            user.setMenus(menu);
            UsernamePasswordToken userToken = new UsernamePasswordToken(user.getUserName(), "123456");
            Subject subject = SecurityUtils.getSubject();
            subject.login(userToken);
            request.getSession().setAttribute("CURRENT_USER", user);
            model.addAttribute("inpatientNo", inpatientNo);
            model.addAttribute("idCard", idCard);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "font/recordList";
    }

    /**
     * 南方医院接口方法
     *
     * @param inpatientNo
     * @param userName
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "recordListSouth")
    public String showRecordSouth(String inpatientNo, String userName, String deptName, Model model, HttpServletRequest request) {
        try {
            //根据病案号查看病案是否存在
            if (StringUtils.isNotBlank(inpatientNo)) {
                int commom = commomMapper.isExistInpatientOrAdmissId(inpatientNo, null, null);
                if (commom == 0) {
                    model.addAttribute("msg", "病案不存在!");
                    return "font/msg";
                }
            } else {
                model.addAttribute("msg", "参数病案号不能为空!");
                return "font/msg";
            }
            //虚假登陆
            //验证shiro(有shiro才此操作)
            Power_User user = new Power_User();
            user.setUserName(userName);
            user.setUserId(-999);
            user.setRoleId(-999);
            Set<String> menu = new TreeSet<>();
            //menu.add("/commom/printPdf");
            user.setMenus(menu);
            UsernamePasswordToken userToken = new UsernamePasswordToken(user.getUserName(), "123456");
            Subject subject = SecurityUtils.getSubject();
            subject.login(userToken);
            request.getSession().setAttribute("CURRENT_USER", user);
            request.getSession().setAttribute("userName", userName);
            request.getSession().setAttribute("deptName", deptName);
            model.addAttribute("inpatientNo", inpatientNo);
            Emr_Log emrLog = new Emr_Log();
            emrLog.setLogTitle("接口查看");
            emrLog.setLogContent("接口查询页面");
            logService.insertInterface(emrLog, userName);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "font/recordListSouth";
    }

    /**
     * 南方医院接口
     *
     * @param page
     * @param limit
     * @param inpatientNo
     * @param request
     * @return
     */
    @RequestMapping("getRecordListByInpatientNoSouth")
    @ResponseBody
    public String getRecordListByInpatientNoSouth(Integer page, Integer limit, String inpatientNo, HttpServletRequest request) {
        if (null != page && null != limit) {
            PageHelper.startPage(page, limit);
        }
        try {
            List<CommomVo> list = commomMapper.selectCommomByInpatientNo(inpatientNo);
            PageInfo pageInfo = new PageInfo<>(list);
            return JSON.toJSONString(pageInfo);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 南方医院接口无登录访问
     *
     * @param userName
     * @param deptName
     * @param request
     * @return
     */
    @RequestMapping(value = "commomListSouth")
    public String commomListSouth(String userName, String deptName, Model model, HttpServletRequest request) {
        //验证shiro(有shiro才此操作)
        UsernamePasswordToken userToken = new UsernamePasswordToken(userName, "123456");
        Subject subject = SecurityUtils.getSubject();
        subject.login(userToken);
        Power_User user = new Power_User();
        user.setUserName(userName);
        request.getSession().setAttribute("cuserName", userName);
        request.getSession().setAttribute("CURRENT_USER", user);
        request.getSession().setAttribute("cdeptName", deptName);
        model.addAttribute("cuserName", userName);
        return "font/commomListSouth";
    }

    /**
     * 接口保存借阅申请
     *
     * @param applyApprove
     * @param patientIds
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("addApplyApprove")
    @ResponseBody
    @OptionalLog(module = "接口保存", methods = "接口查询页面保存借阅申请")
    public ResultUtil addApplyApprove(Emr_Apply_Approve applyApprove, String patientIds, HttpServletRequest request) throws Exception {
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if (!flag) {
            return ResultUtil.error("请不要重复提交!");
        }
        List<CommomVo> commomtables = commomMapper.selectAllByPatients(patientIds.substring(0, patientIds.length() - 1));
        if (null != commomtables && !commomtables.isEmpty()) {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String userName = (String) request.getSession().getAttribute("cuserName");
            applyApprove.setApplyer(userName);
            applyApprove.setApplyTime(fmt.format(new Date()));
            List<Emr_Apply_Approve> list = new ArrayList<>();
            ///查询表列数
            int colCount = commomMapper.selectColByTableName("emr_apply_approve");
            int simpleInsertCount = 2100 / colCount;
            for (int i = 0; i < commomtables.size(); i++) {
                //处理批量添加sql太长问题，设定个数为180
                if (i > 0 && list.size() % simpleInsertCount == 0) {
                    list.clear();
                }
                Emr_Apply_Approve applyApproveInsert = new Emr_Apply_Approve();
                BeanUtils.copyProperties(applyApprove, applyApproveInsert);
                BeanUtils.copyProperties(commomtables.get(i), applyApproveInsert);
                if (StringUtils.isNotBlank(commomtables.get(i).getDisDate())) {
                    applyApproveInsert.setDisDate(DateUtils.strToDateLong(commomtables.get(i).getDisDate()));
                }
                list.add(applyApproveInsert);
                if (list.size() == 1 && list.get(0).getId() != null) {
                    applyApproveService.updateEmrApplyApprove(list.get(0));
                } else {
                    //是180的倍数或最后一个
                    if ((list.size() % simpleInsertCount == 0 || i == commomtables.size() - 1)) {
                        applyApproveService.SimpleInsert(list);
                    }
                }
            }
            sendPowerApproveInterface(applyApprove.getApplyType(), commomtables.size());
            return ResultUtil.ok();
        }
        return ResultUtil.error("请至少选中一个!");
    }

    //推送给权限系统下发审批人通知
    private void sendPowerApproveInterface(String applyType, Integer count) throws Exception {
        //查询申请类型
        List<Emr_Dictionary> dictionaryList = dictionaryMapper.selectDictionaryByTypeCode("apply_type");
        String applyTypeName = "";
        if (null != dictionaryList && !dictionaryList.isEmpty()) {
            for (Emr_Dictionary dictionary : dictionaryList) {
                if (dictionary.getCode().equals(applyType)) {
                    applyTypeName = dictionary.getName();
                    break;
                }
            }
        }
        //发送通知
        applyApproveService.sendNotice(applyTypeName, count);
    }

    @RequestMapping("getRecordListByInpatientNo")
    @ResponseBody
    public String getRecordListByInpatientNo(Integer page, Integer limit, String inpatientNo, String idCard) {
        if (null != page && null != limit) {
            PageHelper.startPage(page, limit);
        }
        PageInfo pageInfo;
        try {
            List<CommomVo> list = commomMapper.selectCommomByInpatientNo2(inpatientNo, idCard);
            pageInfo = new PageInfo<>(list);
            if (list.size() == 0) {
                List<CommomVo> commomVos = commomMapper.selectMasterByInpatientNo(inpatientNo, idCard);
                pageInfo = new PageInfo<>(commomVos);
            }
            return JSON.toJSONString(pageInfo);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 病案主键为空，通过病案号或与住院次数组合查询对应的病案主键
     *
     * @param patientId
     * @param inpatientNo
     * @param admissTimes
     * @return
     */
    private String getPatientIdByInpatientNoAndAdmissTimes(String patientId, String inpatientNo, Short admissTimes, Model model) {
        if (StringUtils.isBlank(patientId)) {
            List<String> patientIdList = commomMapper.selectPatientIdByAdmissTimesAndInpatientNoAndName(admissTimes, inpatientNo, null, null, null);
            if (!CollectionUtils.isEmpty(patientIdList)) {
                if (patientIdList.size() > 1) {
                    return "查询到数据不只一个";
                }
                patientId = patientIdList.get(0);
            } else {
                return "查询不到该数据";
            }
        }
        model.addAttribute("patientId", patientId);
        return null;
    }

    /**
     * 接口
     *
     * @MethodName: showRecordFont
     * @Description: 跳转到档案预览
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("showRecordFont")
    public String showRecordFont(String patientId, String inpatientNo, Short admissTimes, Model model, HttpServletRequest request) {
        //病案主键为空，通过病案号或与住院次数组合查询对应的病案主键
        String msg = getPatientIdByInpatientNoAndAdmissTimes(patientId, inpatientNo, admissTimes, model);
        if (StringUtils.isNotBlank(msg)) {
            return msg;
        }
        //加载登陆者
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        if (null != user) {
            model.addAttribute("user", user);
            model.addAttribute("roleId", user.getRoleId());
        }
        try {
            List<EmrPrintOrDownLoadInfoVo> printCount = printOrDownLoadInfoService.getPrintCount(patientId);
            if (null != printCount && !printCount.isEmpty()) {
                model.addAttribute("printCount", 1);
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "font/showRecordFont";
    }

    /**
     * 南方医院接口
     *
     * @param patientId
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("showRecordFontSouth")
    public String showRecordFontSouth(String patientId, String inpatientNo, Short admissTimes, Model model, HttpServletRequest request) {
        //病案主键为空，通过病案号或与住院次数组合查询对应的病案主键
        String msg = getPatientIdByInpatientNoAndAdmissTimes(patientId, inpatientNo, admissTimes, model);
        if (StringUtils.isNotBlank(msg)) {
            return msg;
        }
        try {
            List<EmrPrintOrDownLoadInfoVo> printCount = printOrDownLoadInfoService.getPrintCount(patientId);
            if (null != printCount && !printCount.isEmpty()) {
                model.addAttribute("printCount", 1);
            }
            String userName = (String) request.getSession().getAttribute("userName");
            Emr_Log emrLog = new Emr_Log();
            emrLog.setLogTitle("接口查看");
            emrLog.setLogContent("接口预览页面");
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "font/showRecordFontSouth";
    }


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

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


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


    @RequestMapping(value = "showRecordContentBlood")
    @ResponseBody
    public ResultUtil showRecordContentBlood(String patientId, String scanPages, String sources, String flag, HttpServletResponse response, HttpServletRequest request) {
        try {
            commomService.showRecordContentBloodFont(patientId, scanPages, sources, flag, response, request);
            return ResultUtil.ok();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return ResultUtil.error("showRecordContentBlood查询文件出错了");
        }
    }


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


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

    @RequestMapping(value = "getRecordContentBlood")
    @ResponseBody
    public void getRecordContentBlood(String patientId, HttpServletRequest request, HttpServletResponse response) {
        List<CommomTree> commomTrees = archiveDetailMapper.selectPdfPathByPatient2(patientId);
        if (commomTrees.size() == 0) {
            try {
                Map<String, Object> cacheMap = commomService.CACHE_MAP;
                String mapKey = "admin" + "_" + patientId;
                List<String> scanPages = (List<String>) cacheMap.get(mapKey);
                if (!CollectionUtils.isEmpty(scanPages)) {
                    String pdfName = "档案管理PDF";
                    //根据图片路径转换pdf
                    EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                    img2PdfUtil.imageToPdfUserEffective(response, scanPages, pdfName, emrPdfWaterSet);
                    //移除缓存
                    commomService.CACHE_MAP.clear();
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
        } else {
            Map<String, Object> cacheMap = commomService.CACHE_MAP;
            String pdfWater = "";
            String mapKey = "admin" + "_" + patientId;
            //获取图片路径集合
            List<String> filePaths = (List<String>) cacheMap.get(mapKey);
            if (!CollectionUtils.isEmpty(filePaths)) {
                //根据图片路径转换pdf
                EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1);
                Jpg2PdfUtil.mulFile2One2(response, filePaths, pdfWater, emrPdfWaterSet);
                //移除缓存
                commomService.CACHE_MAP.clear();
            }

        }
    }


    @RequestMapping("showRecordIframeBloodNewFont")
    public String showRecordIframeBlood(String patientId, String flag, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        //打印分类集合
        List<Emr_Type> emrTypes = null;
        List<Zd_Assort> zdAssorts = null;
        int isDownload = 0;
        model.addAttribute("emrTypes", emrTypes);
        model.addAttribute("zdAssorts", zdAssorts);
        model.addAttribute("isDownload", isDownload);
        //查询是否有打印权限
        int printFlag = 0;
        int moveFlag = 0;
        model.addAttribute("moveFlag", moveFlag);
        model.addAttribute("printFlag", printFlag);
        model.addAttribute("flag", flag);
        return "recordManage/commomSearch/showRecordIframeBloodFont";
    }

    /**
     * 跳转查看pdfiframe页
     *
     * @param patientId
     * @param model
     * @return
     */
    @RequestMapping("showRecordIframeBloodFont")
    public String showRecordIframeBloodFont(String patientId, String flag, Model model) {
        model.addAttribute("patientId", patientId);
        //查询是否有打印权限
        int printFlag = 0;
        model.addAttribute("printFlag", printFlag);
        model.addAttribute("flag", flag);
        return "font/showRecordIframeFont";
    }


    @RequestMapping("showRecordIframeFontSouth")
    public String showRecordIframeFontSouth(String patientId, String flag, Model model, HttpServletRequest request) {
        model.addAttribute("patientId", patientId);
        //查询是否有打印权限
        int printFlag = 0;
        model.addAttribute("printFlag", printFlag);
        model.addAttribute("flag", flag);
        model.addAttribute("userName", (String) request.getSession().getAttribute("userName"));
        model.addAttribute("deptName", (String) request.getSession().getAttribute("deptName"));
        return "font/showRecordIframeFontSouth";
    }

    /**
     * 脐血、祈福分类树
     *
     * @param patientId
     * @param request
     * @return
     */
    @RequestMapping(value = "getFontBloodRecordTree", produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getFontBloodRecordTree(String patientId, HttpServletRequest request) {
        List<Map<String, Object>> treeList = new ArrayList<>();
        //查询该有的权限分类
        try {
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            List<CommomTree> commomVos = new ArrayList<>();
            if (user.getRoleId() == 0 || user.getRoleId() == -100 || user.getRoleId() == -999) {
                commomVos = commomMapper.selectScanPathByPatientId(patientId, null, null);
            } else {
                commomVos = commomMapper.selectScanPathByPatientId(patientId, user.getRoleId(), user.getUserId());
            }
            //按打印分类id查询归属分类集合
            //第一级：全部影像资料
            Map<String, Object> map1 = new HashMap<>();
            map1.put("text", "全部影像资料");
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("opened", true);
            tempMap.put("checked", true);
            map1.put("state", tempMap);
            List<Map<String, Object>> children1 = new LinkedList<>();
            if (null != commomVos && !commomVos.isEmpty()) {
                //去重，取出不重复的分类集合
                Map<String, CommomTree> assortMap = new LinkedHashMap<>();
                for (CommomTree commomVo : commomVos) {
                    assortMap.put(commomVo.getAssortId(), commomVo);
                }
                for (Map.Entry<String, CommomTree> map : assortMap.entrySet()) {
                    String assortId = map.getValue().getAssortId();
                    Map<String, Object> children1Map = new HashMap<>();
                    children1Map.put("assortId", map.getValue().getAssortId());
                    Map<String, Object> tempMapChildren1 = new HashMap<>();
                    tempMapChildren1.put("checked", true);
                    children1Map.put("state", tempMapChildren1);
                    List<Map<String, Object>> children2 = new LinkedList<>();
                    //定义该类影像图片数量
                    int scanPathCount = 0;
                    //第二层 图片
                    for (CommomTree commomVo : commomVos) {
                        if (StringUtils.isNotBlank(assortId) && StringUtils.isNotBlank(commomVo.getAssortId()) &&
                                assortId.equals(commomVo.getAssortId())) {
                            Map<String, Object> children2Map = new HashMap<>();
                            children2Map.put("assortId", assortId);
                            scanPathCount++;
                            //图片名称
                            String name = commomVo.getScanPage();
                            children2Map.put("assortName", name);
                            //设置树图片节点的名称
                            children2Map.put("newName", name);
                            children2Map.put("text", "(第" + scanPathCount + "页)" + name);
                            children2Map.put("source", commomVo.getSource());
                            Map<String, Object> tempMapChildren2 = new HashMap<>();
                            tempMapChildren2.put("checked", true);
                            children2Map.put("state", tempMapChildren2);
                            //存储水印图片
                            children2.add(children2Map);
                        }
                    }
                    children1Map.put("text", map.getValue().getAssortName() + "(" + scanPathCount + ")");
                    children1Map.put("children", children2);
                    children1.add(children1Map);
                }
            }
            map1.put("children", children1);
            //判断分类是否全选，全选，父类跟着全选
            treeList.add(map1);
            return JSON.toJSONString(treeList);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 脐血库、祈福查看pdf
     *
     * @param patientId
     * @param scanPages
     * @param sources
     * @param flag
     */
    @RequestMapping(value = "showRecordContentBloodFont")
    public String showRecordContentBloodFont(String patientId, String scanPages, String sources, String flag, Model model) {
        String pdfTempRoot = "pdfTemp";
        //临时保存pdf的文件目录
        String fileOutRoot = WATERPICPATH + pdfTempRoot;
        //目录不存在则创建
        if (!new File(fileOutRoot).isDirectory()) {
            new File(fileOutRoot).mkdirs();
        }
        //文件相对路径
        String filePath = pdfTempRoot + "\\" + UUID.randomUUID() + ".pdf";
        //组织暂存pdf文件路径
        String fileOutPath = WATERPICPATH + filePath;
        //组织前台访问临时pdf路径
        String httpFilePath = EMRRECORDJSP + "\\reload\\" + filePath;
        try {
            commomService.showRecordContentBloodFont(patientId, scanPages, sources, flag, fileOutPath);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("httpFilePath", httpFilePath);
        return "font/showPdfFrameFont";
    }

    /**
     * 南方医院查看PDF
     *
     * @param patientId
     * @param scanPages
     * @param sources
     * @param flag
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "showRecordContentSouthFont")
    public String showRecordContentSouthFont(String patientId, String scanPages, String sources, String flag, Model model, HttpServletRequest request) {
        String pdfTempRoot = "pdfTemp";
        //临时保存pdf的文件目录
        String fileOutRoot = WATERPICPATH + pdfTempRoot;
        //目录不存在则创建
        if (!new File(fileOutRoot).isDirectory()) {
            new File(fileOutRoot).mkdirs();
        }
        //文件相对路径
        String filePath = pdfTempRoot + "\\" + UUID.randomUUID() + ".pdf";
        //组织暂存pdf文件路径
        String fileOutPath = WATERPICPATH + filePath;
        //组织前台访问临时pdf路径
        String httpFilePath = EMRRECORDJSP + "\\reload\\" + filePath;
        String userName = (String) request.getSession().getAttribute("userName");
        String deptName = (String) request.getSession().getAttribute("deptName");
        try {
            commomService.showRecordContentSouthFont(patientId, userName, deptName, scanPages, sources, flag, fileOutPath);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("httpFilePath", httpFilePath);
        return "font/showPdfFrameFont";
    }

    /**
     * 祈福
     *
     * @MethodName:
     * @Description: 登录权限系统
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "emrReordLoginByToken", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil emrReordLoginByToken(String token, String userName, HttpServletRequest request) throws Exception {
        if (StringUtils.isNoneBlank(token)) {
            //创建连接工厂
            JAXDynamicClientFactory dcf = JAXDynamicClientFactory.newInstance();
            //创建客户端
            Object[] objects = new Object[0];
            Client client = null;
            try {
                client = dcf.createClient(POWER_URLHEAD + "/WebService/PowerWebService?wsdl");
                //动态调用getInfosByUserId方法
                objects = client.invoke("getInfosByUserId", token, "emr_record");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != client) {
                    client.destroy();
                }
            }
            Power_User powerUser = JSON.parseObject(objects[0].toString(), Power_User.class);
            //返回用户为空跳转到登录权限系统界面
            //设置进session
            powerUser.setUserName(userName);
            request.getSession().setAttribute("CURRENT_USER", powerUser);
            request.getSession().setAttribute("power_menus", powerUser.getMenus());
            request.getSession().setAttribute("token", token);
            //验证shiro(有shiro才此操作)
            UsernamePasswordToken userToken = new UsernamePasswordToken(userName, "123456");
            Subject subject = SecurityUtils.getSubject();
            subject.login(userToken);
            //获取用户列表
            // 获得Http客户端
            if (StringUtils.isNotBlank(userName) && powerUser.getRoleId() == -100) {
                try {
                    commomService.getUserList(userName, request);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return ResultUtil.ok(powerUser);
        }
        return ResultUtil.ok();
    }

    /**
     * 祈福
     *
     * @MethodName:
     * @Description: 登录权限系统
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "emrReordLogin")
    @ResponseBody
    public ResultUtil emrReordLogin(String userName, HttpServletRequest request) throws Exception {
        ResultUtil resultUtil = powerLogin(userName);
        String token = resultUtil.getMsg();
        return emrReordLoginByToken(token, userName, request);
    }

    /**
     * 祈福
     *
     * @MethodName:
     * @Description: 跳转到档案预览
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value = "powerLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil powerLogin(String userName) throws Exception {
        if (StringUtils.isBlank(userName)) {
            return ResultUtil.error("用户名不能为空");
        }
        //请求权限系统登录
        Map<String, String> map = new HashMap<>();
        String url = POWER_URLHEAD + "/font/getToken1";
        map.put("userName", userName);
        String resultString = HttpClientUtils.doPost(url, map);
        // 判断返回状态是否为200
        if (StringUtils.isNoneBlank(resultString)) {
            JSONObject jsonObject = JSON.parseObject(resultString);
            String extend = jsonObject.getString("extend");
            JSONObject extendObject = JSONObject.parseObject(extend);
            String token = extendObject.getString("token");
            return ResultUtil.ok(token);
        }
        return null;
    }

    /**
     * 174医院、祈福
     *
     * @MethodName: showRecord174
     * @Description: 跳转到档案预览
     * @Param String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-29
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-29
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("showRecord")
    public String showRecord174(String patientId, String userName, Model model, HttpServletRequest request) throws Exception {
        model.addAttribute("patientId", patientId);
        //加载登陆者
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        if (null == user) {
            emrReordLogin(userName, request);
        }
        return "font/showRecord3To2";
    }

    @RequestMapping("showRecordPage")
    public String showRecordPage(String patientId, Model model, HttpServletRequest request) throws Exception {
        model.addAttribute("patientId", patientId);
        //加载登陆者
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        model.addAttribute("user", user);
        model.addAttribute("roleId", user.getRoleId());
        List<EmrPrintOrDownLoadInfoVo> printCount = null;
        try {
            printCount = printOrDownLoadInfoService.getPrintCount(patientId);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        if (null != printCount && !printCount.isEmpty()) {
            model.addAttribute("printCount", 1);
        }
        return "recordManage/commomSearch/showRecord174";
    }
}
