/**
 * 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.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","病历清单id","住院号","住院次数","名字","性别","身份证","入院科室","入院日期","出院科室","出院日期","状态","归档状态"};
        String[] fileNames = {"id","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 int updateState(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws UnsupportedEncodingException {
        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("初审");
        int bol=archiveMasterService.updateByClo(archiveMaster);
        if (bol == 1) {
            //删除该病案号和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);
            }

            //2021-01-30  初审成功日志
            Archive_Master_Following archive_master_following = new Archive_Master_Following();
            archive_master_following.setMasterId(emrFaultDetail.getArchiveDetailId());
            //following表中添加病案室审核操作记录
            archive_master_following.setFollowingType("10");
            archive_master_following.setFollowingContent("病案召回");
            archive_master_following.setHandleTime(nowTime);
            archive_master_following.setHandleId(username);
            archive_master_following.setHandleName(handleName);
            archive_master_followingService.insertSelective(archive_master_following);
        }
        return bol;
    }
}
 

