/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 14:39
 * Description:病案召回
 */
package com.emr.controller;

import com.emr.annotation.OptionalLog;
import com.emr.entity.*;
import com.emr.service.*;
import com.emr.util.ThreadExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@PropertySource(value = "classpath:config/jdbc.properties", encoding = "UTF-8")
@Controller
@RequestMapping("/medicalRecall")
public class MedicalRecallController {
    @Autowired
    private Emr_Fault_DetailService emrFaultDetailService;

    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @Autowired
    private Archive_MasterService archiveMasterService;

    @Autowired(required = false)
    private Archive_Master_FollowingService archive_master_followingService;

    @Value("${recallReason}")
    private String recallReason;

    @RequestMapping(value = "/recall")
    public String recall(Model model) {
        return "medicalRecallDir/medicalRecallList";
    }


    @ResponseBody
    @RequestMapping(value = "/recallList")
    public OffsetLimitPage recallList(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        OffsetLimitPage result = emrFaultDetailService.selectByCol(emrFaultVo, offset, limit);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Emr_Fault_Vo emrFaultVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id","住院号","住院次数","名字","性别","身份证","入院科室","入院日期","出院科室","出院日期","状态","归档状态"};
        String[] fileNames = {"archiveDetailId","inpNo","visitId","name","sex","idNo","deptAdmissionTo","admissionDateTime","deptName","dischargeDateTime","state","archivestate"};
        //文件名
        String fileName = "召回信息数据" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Emr_Fault_Vo> list = emrFaultDetailService.selectByCol(emrFaultVo);
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        //科室列表
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        for (int i = 0; i < list.size(); i++) {
            //替换科室
            for (int k = 0; k < dicList.size(); k++) {
                String deptName = list.get(i).getDeptName();
                String dept2 = list.get(i).getDeptAdmissionTo();
                if (deptName.equals(dicList.get(k).getCode())) {
                    //出院科室
                    deptName = deptName.replace(deptName, dicList.get(k).getName());
                    list.get(i).setDeptName(deptName);
                }
                if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                    //入院科室dept_admission_to
                    dept2 = dept2.replace(dept2, dicList.get(k).getName());
                    list.get(i).setDeptAdmissionTo(dept2);
                }
            }
        }
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result=utils.exportExcelToFilePath(response,utils.listConvert(list));
    }

    @Transactional
    @OptionalLog(methods = "病案召回")
    @ResponseBody
    @RequestMapping(value = "/updateState")
    public String updateState(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws UnsupportedEncodingException {
        boolean flag = FormTokenFlagUtil.isFlag(request);
        String result="";
        if (!flag) {
            result= "请不要重复提交!";
        }
        int bol=0;
        //判断是否已经召回
        if(StringUtils.isNotBlank(emrFaultDetail.getArchiveDetailId())){
            //判断病案是否已经召回
            Archive_Master_Following followingLastInfo=new Archive_Master_Following();
            followingLastInfo.setFollowingType("10");
            followingLastInfo.setMasterId(emrFaultDetail.getArchiveDetailId());
            List<Archive_Master_Following> followingLastList=archive_master_followingService.selLastByType(followingLastInfo);
            if(followingLastList==null || followingLastList.size()<=0){
                //最后一次存在召回
                String inpatientNo = emrFaultDetail.getContent();
                if(StringUtils.isBlank(inpatientNo)){
                    result= "召回失败!";
                }
                response.setCharacterEncoding("utf-8");
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                String handleName = user.getUserPosition();//姓名
                String username = user.getUserName();//获取登录的用户名
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = format1.format(new Date());
                emrFaultDetail.setUpdater(username);
                emrFaultDetail.setUpdateTime(nowTime);
                if(emrFaultDetail.getRecallReason()==null ||emrFaultDetail.getRecallReason()==""){
                    //医院需要这份病案
                    emrFaultDetail.setRecallReason( new String(recallReason.getBytes("iso-8859-1"),"utf-8"));
                }
                Archive_Master archiveMaster=new Archive_Master();
                archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
                archiveMaster.setCmtNurse(1);
                archiveMaster.setCmtDoctor(1);
                archiveMaster.setArchivestate("初审");
                bol=archiveMasterService.updateByClo(archiveMaster);
                if (bol == 1) {
                    //召回时删除commomtable对应数据
                    archiveMasterService.deleteRecordByInp(emrFaultDetail.getArchiveDetailId());
                    //删除该病案号和state不为空的记录
                    bol = emrFaultDetailService.delByArchiveId(emrFaultDetail);
                    //重新插入一条记录
                    //emrFaultDetail.setArchiveDetailId(null);+
                    if (bol == 1|| bol==0) {
                        emrFaultDetail.setCreater(username);
                        emrFaultDetail.setCreateTime(nowTime);
                        emrFaultDetail.setFirstTrial(null);
                        bol = emrFaultDetailService.insertSel(emrFaultDetail);
                    }
                    String lgFlag = inpatientNo.substring(0,2);
                    if(!"LG".equals(lgFlag)) {
                        //2021-01-30  初审成功日志
                        Archive_Master_Following archiveMasterFollowing = new Archive_Master_Following();
                        archiveMasterFollowing.setMasterId(emrFaultDetail.getArchiveDetailId());
                        //following表中添加病案室审核操作记录
                        archiveMasterFollowing.setFollowingType("10");
                        archiveMasterFollowing.setFollowingContent("病案召回");
                        archiveMasterFollowing.setHandleTime(nowTime);
                        archiveMasterFollowing.setHandleId(username);
                        archiveMasterFollowing.setHandleName(handleName);
                        archive_master_followingService.insertSelective(archiveMasterFollowing);
                    }else{
                        //留观号召回推送第三方
                        archiveMasterService.requestObservationRecord(inpatientNo,"RETURNED",emrFaultDetail.getRecallReason(),null);
                    }
                    result="召回成功!";
                }

            }else{
                result= "请不要重复召回!";
            }
        }
        return result;
    }
}
 

