package com.emr.controller;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.dto.PushStorageDto;
import com.emr.entity.*;
import com.emr.service.*;
import com.emr.util.Logger;
import com.emr.util.ThreadExcelUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
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.ArrayList;
import java.util.Date;
import java.util.List;
import static com.emr.util.HttpClientUtils.doPostJson;


@PropertySource(value = "classpath:config/jdbc.properties", encoding = "UTF-8")
@Controller
@RequestMapping("/storage")

public class storageController {
    private static Logger logger = new Logger();

    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @Autowired
    private Archive_MasterService archiveMasterService;
    @Autowired
    private Archive_Master_FollowingService archiveMasterFollowingService;

    @RequestMapping(value = "/MedicalRecordStorage")
    public String faults(Model model) {
        return "medicalRecordStorageDir/MedicalRecordStorage";
    }

    @Value("${MedicalRecordSealingUrl}")
    private String MedicalRecordUrl;
    @Value("${MedicalRecordSealingName}")
    private String MedicalRecordSealingName;



    @ResponseBody
    @RequestMapping(value = "/StorageList")
    public OffsetLimitPage recallList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        OffsetLimitPage result = archiveMasterService.selectStorageByCol(archiveMasterVo, offset, limit);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcelStorageList")
    public void exportExcelStorageList(HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id", "住院号", "住院次数", "名字", "性别", "入院科室", "入院日期", "出院科室", "出院日期", "状态", "封存人", "封存日期"};
        String[] fileNames = {"id", "inpNo", "visitId", "name", "sex", "deptAdmissionTo", "admissionDateTime", "deptName", "dischargeDateTime", "archivestate", "handleName", "handleTime"};
        //文件名
        String fileName = "病案封存列表" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Archive_Master_Vo> list = archiveMasterService.selectStorageByCol(archiveMasterVo);
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result = utils.exportExcelToFilePath(response, utils.listConvert(list));
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"住院号", "住院次数", "名字", "性别", "撤回人", "撤回时间", "归档状态", "状态"};
        String[] fileNames = {"inpNo", "visitId", "name", "sex", "handleName", "handleTime", "archivestate", "followingContent"};
        //文件名
        String fileName = "病案封存日志" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Archive_Master_Vo> list = archiveMasterService.selectByFollowinglog(archiveMasterVo);
        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);
        if (!flag) {
            return "请不要重复提交!";
        }
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        int bol = 0;
        String result = "";
        PushStorageDto pushStorageDto = new PushStorageDto();
        //判断是否已经封存
        if (StringUtils.isNotBlank(emrFaultDetail.getArchiveDetailId())) {
            //判断病案是否已经封存
            Archive_Master_Following followingLastInfo = new Archive_Master_Following();
            if (emrFaultDetail.getArchiveState().equals("已封存")) {
                followingLastInfo.setFollowingType("11");
                result = "请不要重复封装!";
            } else {
                followingLastInfo.setFollowingType("12");
                result = "请不要重复取消封装!";
            }
            followingLastInfo.setMasterId(emrFaultDetail.getArchiveDetailId());
            List<Archive_Master_Following> followingLastList = archiveMasterFollowingService.selLastByType(followingLastInfo);
            if (followingLastList == null || followingLastList.size() <= 0) {
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                String handleName = user.getUserPosition();//姓名
                String username = user.getUserName();//获取前面登录的用户名
                emrFaultDetail.setUpdater(username);
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = format1.format(new Date());
                emrFaultDetail.setUpdateTime(nowTime);
                Archive_Master archiveMaster = new Archive_Master();
                Archive_Master_Following archiveMasterFollowing = new Archive_Master_Following();
                archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
                archiveMaster.setArchivestate(emrFaultDetail.getArchiveState());
                archiveMaster.setCmtNurse(1);
                archiveMaster.setCmtDoctor(1);
                if (!emrFaultDetail.getArchiveStateFlag().equals("1")) {
                    bol = archiveMasterService.updateByClo(archiveMaster);
                }
                if (bol == 1) {
                    if (archiveMaster.getArchivestate().equals("已封存")) {
                        archiveMasterFollowing.setMasterId(emrFaultDetail.getArchiveDetailId());
                        archiveMasterFollowing.setFollowingContent("病案封存");
                        archiveMasterFollowing.setFollowingType("11");
                        archiveMasterFollowing.setHandleTime(nowTime);
                        archiveMasterFollowing.setHandleId(username);
                        archiveMasterFollowing.setHandleName(handleName);
                        archiveMasterFollowing.setSafekeepingName(emrFaultDetail.getSafekeepingName());
                        archiveMasterFollowing.setRemark(emrFaultDetail.getRecallReason());
                        archiveMasterFollowing.setRecallReason(emrFaultDetail.getSealedState());
                        bol = archiveMasterFollowingService.insertSelective(archiveMasterFollowing);
                        //向电子病历发送封存消息
                        pushStorageDto.setPATIENT_STATUS(1);
                        pushStorageDto.setINP_NO(emrFaultDetail.getInpNo());
                        pushStorageDto.setPATIENT_ID(emrFaultDetail.getPatientId());
                        pushStorageDto.setVISIT_ID(Integer.parseInt(emrFaultDetail.getVisitId()));
                        pushStorageDto.setPATIENT_NAME(emrFaultDetail.getName());
                        pushStorageDto.setOPERATOR(handleName);
                        pushStorageDto.setOPERATOR_ID(username);
                        pushStorageDto.setOperationTime(nowTime);
                        pushStorageDto.setSEQUESTRATION_RESION(emrFaultDetail.getRecallReason());
                        pushStorage(pushStorageDto);
                    } else if (archiveMaster.getArchivestate().equals("已归档")) {// if (archiveMaster.getArchivestate().equals("已归档"))
                        archiveMasterFollowing.setMasterId(emrFaultDetail.getArchiveDetailId());
                        archiveMasterFollowing.setFollowingContent("病案取消封存");
                        archiveMasterFollowing.setFollowingType("12");
                        archiveMasterFollowing.setHandleTime(nowTime);
                        archiveMasterFollowing.setHandleId(username);
                        archiveMasterFollowing.setHandleName(handleName);
                        archiveMasterFollowing.setRemark(emrFaultDetail.getRecallReason());
                        //取消封存恢复封存前病历状态
                        Archive_Master_Following following = new Archive_Master_Following();
                        following.setFollowingType("11");
                        following.setMasterId(emrFaultDetail.getArchiveDetailId());
                        List<Archive_Master_Following> list = archiveMasterFollowingService.selLastByType(following);
                        if (list.size()>0){
                            if (StringUtils.isNotBlank(list.get(0).getRecallReason())){
                                archiveMaster.setArchivestate(list.get(0).getRecallReason());
                                archiveMasterService.updateByClo(archiveMaster);
                            }
                        }
                        bol = archiveMasterFollowingService.insertSelective(archiveMasterFollowing);
                        //向电子病历发送取消封存消息
                        pushStorageDto.setPATIENT_STATUS(0);
                        pushStorageDto.setINP_NO(emrFaultDetail.getInpNo());
                        pushStorageDto.setPATIENT_ID(emrFaultDetail.getPatientId());
                        pushStorageDto.setVISIT_ID(Integer.parseInt(emrFaultDetail.getVisitId()));
                        pushStorageDto.setPATIENT_NAME(emrFaultDetail.getName());
                        pushStorageDto.setOPERATOR(handleName);
                        pushStorageDto.setOPERATOR_ID(username);
                        pushStorageDto.setOperationTime(nowTime);
                        pushStorageDto.setSEQUESTRATION_RESION(emrFaultDetail.getRecallReason());
                        pushStorage(pushStorageDto);
                    }
                }
                if (archiveMaster.getArchivestate().equals("再次封存")) {
                    archiveMasterFollowing.setMasterId(emrFaultDetail.getArchiveDetailId());
                    archiveMasterFollowing.setFollowingContent("病案再次封存");
                    archiveMasterFollowing.setFollowingType("11");
                    archiveMasterFollowing.setHandleTime(nowTime);
                    archiveMasterFollowing.setHandleId(username);
                    archiveMasterFollowing.setHandleName(handleName);
                    archiveMasterFollowing.setRemark(emrFaultDetail.getRecallReason());
                    bol = archiveMasterFollowingService.insertSelective(archiveMasterFollowing);
                    String url = "http://10.6.1.127:9295/api/NoViewCollect/generateTaskByPatientId";
                    List<String> list = new ArrayList<String>();
                    list.add(emrFaultDetail.getArchiveDetailId());
                    String json = JSON.toJSONString(list);
                    doPostJson(url, json);
                }
            } else {
                return result;
            }
        }
        return bol + "";
    }

    //向电子病历推送封存消息
    private void pushStorage(PushStorageDto pushStorageDto) {
        try {
        logger.log("开始封存:"+1);
        //组织xml参数
        String xmlContent =
//                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<REQUEST>"+
                "<PATIENT_STATUS>"+pushStorageDto.getPATIENT_STATUS()+"</PATIENT_STATUS>" +
                "<INP_NO>"+pushStorageDto.getINP_NO()+"</INP_NO>" +
                "<PATIENT_ID>"+pushStorageDto.getPATIENT_ID()+"</PATIENT_ID>" +
                "<VISIT_ID>"+pushStorageDto.getVISIT_ID()+"</VISIT_ID>"+
                "<PATIENT_NAME>"+pushStorageDto.getPATIENT_NAME()+"</PATIENT_NAME>"+
                "<OPERATOR>"+pushStorageDto.getOPERATOR()+"</OPERATOR>"+
                "<OPERATOR_ID>"+pushStorageDto.getOPERATOR_ID()+"</OPERATOR_ID>"+
                "<OperationTime>"+pushStorageDto.getOperationTime()+"</OperationTime>"+
                "<SEQUESTRATION_RESION>"+pushStorageDto.getSEQUESTRATION_RESION()+"</SEQUESTRATION_RESION>"+
                "</REQUEST>";
        String endpoint = MedicalRecordUrl;
        String method = MedicalRecordSealingName;
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
            Client client = dcf.createClient(endpoint);
            Object[] res = null;

            res = client.invoke(method, xmlContent);
            logger.log("封存返回:"+res);
        } catch (Exception e) {
            logger.log("异常处理:"+e.getMessage()+e);
        }
    }


    /*
     * 封存日志
     * */
    @RequestMapping(value = "/MedicalRecordStorageLog")
    public String faultsLog(Model model) {
        return "medicalRecordStorageDir/MedicalRecordStorageLog";
    }

    /*
     * 封存日志
     * */
    @ResponseBody
    @RequestMapping(value = "/storageLogList")
    public OffsetLimitPage storageLogList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        OffsetLimitPage result = archiveMasterService.selectByFollowinglog(archiveMasterVo, offset, limit);
        return result;
    }

    /**
     * @description: 获取封存类型下拉框
     * @author linjj
     * @date: 2023/7/13 15:48
     */
    @ResponseBody
    @RequestMapping(value = "getSafekeeping")
    public List<Emr_Dictionary> getSafekeeping() {
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("safekeeping");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        return dicList;
    }
}
 

