package com.emr.controller;

import com.alibaba.fastjson.JSON;
import com.emr.dao.Emr_DictionaryMapper;
import com.emr.entity.*;
import com.emr.service.Archive_DetailService;
import com.emr.service.Archive_MasterService;
import com.emr.service.Zd_AssortService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.Msg;
import org.apache.commons.lang3.StringUtils;
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 javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zwh
 * */
@Controller
@RequestMapping("font/")
public class FontController {
    @Value("${pdfWater}")
    private String pdfWater;
    @Value("${allAddortIds}")
    private String allAddortIds;
    @Value("${POWER_URLHEAD}")
    private String powerUrlHead;
    @Autowired
    private Archive_DetailService archiveDetailService;
    @Autowired
    private Archive_MasterService archiveMasterService;
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;
    @Autowired
    private Zd_AssortService assortService;

    /***************************提供第三方按多个分段id和记账号查询病历pdf***********************************/
    /**
     * 提供第三方按多个分段id和记账号查询病历pdf
     * */
    @RequestMapping("showRecordByPatientId")
    public String showRecordByPatientId( HttpServletResponse response, String assortIds, String patientId, String visitId, Model model){
        response.setCharacterEncoding("utf-8");
        //System.out.println(System.getProperty("file.encoding"));//当前文件的编码方式
        if(StringUtils.isBlank(assortIds)){
            return retrunErrorPage(model,"病案分类Id不能为空!");
        }
        if(StringUtils.isBlank(patientId)){
            return retrunErrorPage(model,"记账号不能为空!");
        }
        if(StringUtils.isBlank(visitId)){
            return retrunErrorPage(model,"住院次数不能为空!");
        }
        List<Archive_Master> list = new ArrayList<>();
        //判断工号是否存在
        try {
           /* String checkUserName = checkUserName(userName);
            if(StringUtils.isNotBlank(checkUserName)){
                return retrunErrorPage(model,checkUserName);
            }*/
            //判断分类id是否存在,协商assortIds = "00000000"为查询全部
            if(!allAddortIds.equals(assortIds)) {
                String checkAssortIds = checkAssortIds(assortIds);
                if (StringUtils.isNotBlank(checkAssortIds)) {
                    return retrunErrorPage(model, checkAssortIds);
                }
            }
            //判断记账号是否存在
            list = archiveMasterService.selectByObject(patientId,visitId);
            if(null == list || list.isEmpty()){
                return retrunErrorPage(model,"病历不存在!");
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        model.addAttribute("patientId",list.get(0).getId());
        model.addAttribute("accountNumber",list.get(0).getPatientId());
        model.addAttribute("assortIds",assortIds);
        return "font/showRecordIframe";
    }

    /**
     * 返回错误页面
     * */
    private String retrunErrorPage(Model model, String errorMsg){
        // System.out.println(System.getProperty("file.encoding"));//当前文件的编码方式
        model.addAttribute("errorMsg",errorMsg);
        return "font/error";
    }

    /**
     * 返回按需采集页面
     * */
    @RequestMapping("collection")
    private String retrunCollectionPage(Model model, String collectionID){
        // System.out.println(System.getProperty("file.encoding"));//当前文件的编码方式
        model.addAttribute("collectionID",collectionID);
        return "font/collection";
    }

    /**
     * 判断分类id是否存在
     * */
    private String checkAssortIds(String assortIds){
        // System.out.println(System.getProperty("file.encoding"));//当前文件的编码方式
        Zd_Assort assort = new Zd_Assort();
        assort.setPrintFlag("0");
        List<Zd_Assort> assortList = null;
        try {
            assortList = assortService.selectAll(assort);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        if(null != assortList && !assortList.isEmpty()){
            String[] split = assortIds.split(",");
            for (String s : split) {
                //定义分类存在
                boolean exist = false;
                if (StringUtils.isNotBlank(s)) {
                    for (Zd_Assort assort1 : assortList) {
                        if (s.equals(assort1.getAssortId())) {
                            exist = true;
                            break;
                        }
                    }
                }
                if (!exist) {
                    return "病案分类Id有误!";
                }
            }
        }else{
            return "病案分类Id有误!";
        }
        return null;
    }

    /**
     * 根据主键查询病案详情
     * @param masterId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRecord")
    public String getPdfToPdf(String masterId){
        try {
            Archive_Master archiveMaster = archiveMasterService.selectById(masterId);
            //转换科室数据字典
            if(StringUtils.isNotBlank(archiveMaster.getDeptName())){
                Emr_Dictionary dictionary = new Emr_Dictionary();
                dictionary.setCode(archiveMaster.getDeptName());
                dictionary.setTypecode("dept_code");
                List<Emr_Dictionary> dictionaries = dictionaryMapper.dicByTypeCode(dictionary);
                if(null != dictionaries && !dictionaries.isEmpty()){
                    archiveMaster.setDeptName(dictionaries.get(0).getName());
                }
                //判断出院日期
                String dischargeDateTime = archiveMaster.getDischargeDateTime();
                if(StringUtils.isNotBlank(dischargeDateTime)){
                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                    String time = fmt.format(fmt.parse(dischargeDateTime));
                    if("1801-02-03".equals(time)){
                        archiveMaster.setDischargeDateTime(null);
                    }
                }
            }
            return JSON.toJSONString(archiveMaster);
        } catch (ParseException e) {
            ExceptionPrintUtil.printException(e);
            //e.printStackTrace();
            return null;
        }
    }

    /**
     * 跳转到showRecordIframe页面
     * */
    /*@RequestMapping("showRecordIframe")
    public String showRecordIframe(){
        return "font/showRecordIframe";
    }*/

    /**
     * 根据master表的记账号和分类id集合组织分类树
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getRecordTypeTree")
    public String getRecordTypeTree(HttpServletResponse response,String patientId,String assortIds){
        response.setCharacterEncoding("utf-8");
        // System.out.println(System.getProperty("file.encoding"));//当前文件的编码方式
        List<AssortTypeTree> treeList = new ArrayList<>();
        if(StringUtils.isNotBlank(patientId) && StringUtils.isNotBlank(assortIds)){
            List<Archive_Detail> list = new ArrayList<>();
            //assortIds等于协商的全查的分类id，全查
            try {
                if(allAddortIds.equals(assortIds)){
                    list = archiveDetailService.selectTypeTreeByPatientIdAndAssortIds(patientId, null);
                }else{
                    //否则按条件查
                    //分类id分别以单引号隔开
                    StringBuilder assortIdStr = new StringBuilder();
                    String[] split = assortIds.split(",");
                    for (String s : split) {
                        assortIdStr.append("'").append(s).append("',");
                    }
                    //去掉最后一个逗号
                    assortIdStr = new StringBuilder(assortIdStr.substring(0, assortIdStr.length() - 1));
                    list = archiveDetailService.selectTypeTreeByPatientIdAndAssortIds(patientId, assortIdStr.toString());
                }
            } catch (Exception e) {
                ExceptionPrintUtil.printException(e);
                e.printStackTrace();
            }
            if(null != list && !list.isEmpty()){
                Set<String> assortList = new LinkedHashSet<>();
                //抽取首次病程记录
                String strTemp = "首次病程";
                String assortId = "11";
                //定义护理记录里的首次护理记录排前头
                String nurseTemp = "首次护理";
                String nurseAssortId = "7";
                Archive_Detail detailTemp = new Archive_Detail();
                Archive_Detail nurseDetailVoTemp = new Archive_Detail();
                //分类去重
                for(Archive_Detail detail : list){
                    assortList.add(detail.getSubassort());
                    //获取title
                    String title = detail.getTitle();
                    if(StringUtils.isNotBlank(title) && detail.getTitle().contains(strTemp)){
                        detailTemp = detail;
                    }
                    if(StringUtils.isNotBlank(title) && detail.getTitle().contains(nurseTemp)){
                        nurseDetailVoTemp = detail;
                    }
                }
                //组织树
                int id = 1;
                //定义第一层的id为第二层父id
                int oneParentId = 0;
                //定义第二层的id为第三层父id
                int twoParentId = 0;
                AssortTypeTree tree = new AssortTypeTree();
                //第一层,根目录全部影像资料
                tree.setId(id);
                tree.setParentId(0);
                tree.setName("全部影像资料");
                tree.setChecked("true");
                treeList.add(tree);
                oneParentId = id;
                id++;
                for(String assortName : assortList){
                    AssortTypeTree tree1 = new AssortTypeTree();
                    //第二层,分类名称
                    tree1.setId(id);
                    tree1.setParentId(oneParentId);
                    twoParentId = id;
                    id++;
                    //定义该类的数量
                    int count = 0;
                    //定义是否添加了首次病程
                    boolean flag = false;
                    boolean nurseflag = false;
                    for(Archive_Detail detail : list){
                        if(StringUtils.isNoneBlank(detail.getSubassort()) && assortName.equals(detail.getSubassort())){
                            String assortid = detail.getAssortid();
                            if(StringUtils.isNotBlank(assortid) && assortid.equals(assortId)){
                                //是病程记录
                                if(!flag && StringUtils.isNotBlank(detailTemp.getTitle())){
                                    AssortTypeTree tree2 = new AssortTypeTree();
                                    //第三层,资料名称
                                    count++;
                                    tree2.setId(id);
                                    tree2.setParentId(twoParentId);
                                    tree2.setName(detailTemp.getTitle());
                                    tree2.setSelfId(detailTemp.getId());
                                    tree2.setChecked("true");
                                    treeList.add(tree2);
                                    id++;
                                    flag = true;
                                }
                            }
                            if(StringUtils.isNotBlank(assortid) && assortid.equals(nurseAssortId)){
                                //是护理记录
                                if(!nurseflag && StringUtils.isNotBlank(nurseDetailVoTemp.getTitle())){
                                    AssortTypeTree tree2 = new AssortTypeTree();
                                    //第三层,资料名称
                                    count++;
                                    tree2.setId(id);
                                    tree2.setParentId(twoParentId);
                                    tree2.setName(nurseDetailVoTemp.getTitle());
                                    tree2.setSelfId(nurseDetailVoTemp.getId());
                                    tree2.setChecked("true");
                                    treeList.add(tree2);
                                    id++;
                                    nurseflag = true;
                                }
                            }
                            if(!detail.equals(detailTemp) && !detail.equals(nurseDetailVoTemp)) {
                                AssortTypeTree tree2 = new AssortTypeTree();
                                //第三层,资料名称
                                count++;
                                tree2.setId(id);
                                tree2.setParentId(twoParentId);
                                tree2.setName(detail.getTitle());
                                tree2.setSelfId(detail.getId());
                                tree2.setChecked("true");
                                treeList.add(tree2);
                                id++;
                            }
                        }
                    }
                    tree1.setName(assortName + "("+count+")");
                    tree1.setChecked("true");
                    treeList.add(tree1);
                }
            }
        }
        return JSON.toJSONString(treeList);
    }

    /**
     * 根据病案号或类别或图片id获取图片列表，并生成PDF并返回pdf文件名
     * @param response
     * @param detailIds
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getPdfToPdf",method = RequestMethod.POST)
    public Msg getPdfToPdf(HttpServletResponse response, String detailIds, HttpSession session){
        response.setCharacterEncoding("utf-8");
        try {
            Archive_Detail detail = new Archive_Detail();
            if(StringUtils.isNotBlank(detailIds)){
                detail.setTitle(detailIds);
                archiveDetailService.selectByIdStrFont(response,session,detail);
            }else{
                //存至session
                session.setAttribute("showRecord",null);
            }
            return Msg.success();
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            return Msg.fail("查看出错了,请联系系统管理员");
            //e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "showPdf")
    public void showPdf(HttpServletResponse response, HttpSession session){
        response.setCharacterEncoding("utf-8");
        try {
            archiveDetailService.showPdf(response,session,pdfWater);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "getCollectionDetail")
    public void getCollectionDetail(HttpServletResponse response,Archive_Detail_Vo ArchiveDetailVo){
        response.setCharacterEncoding("utf-8");
        try {
            archiveDetailService.getCollectionDetail(ArchiveDetailVo);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
        }
    }
}
