/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/8/8 12:46
 * Description:
 */
package com.emr.controller;

import com.emr.dao.ArchiveDetailCaCopyMapper;
import com.emr.dao.Archive_Detail_ca_reqParamMapper;
import com.emr.dao.CaDepartIdMapper;
import com.emr.dao.CaSignatureMapper;
import com.emr.dto.Archive_DetailPdfPathDto;
import com.emr.entity.*;
import com.emr.service.*;
import com.emr.service.ipml.Archive_Detai_CaSignServiceImpl;
import com.emr.util.*;
import com.emr.vo.CaDepartIdVo;
import com.emr.webservice.MedicalRecordShowBackContent.MR_FILE_CALLBACK_RECORD;
import com.emr.webservice.MedicalRecordShowBackContent.MR_FILE_INDEX_CALLBACK;
import com.lowagie.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import java.io.*;
import java.nio.file.Files;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("lastVerify")
@Slf4j
public class lastVerifyController {



    @Value("${EMRQualityControl}")
    private String EMRQualityControl;
    @Value("${EMRQualityControlParamName}")
    private String EMRQualityControlParamName;
    @Autowired
    private Archive_MasterService archiveMasterService;

    @Autowired
    private Emr_Fault_TypeService emrFaultTypeService;

    @Autowired
    private Emr_Fault_DetailService emrFaultDetailService;

    @Autowired(required = false)
    private Archive_Master_FollowingService archive_master_followingService;
    @Value("${isCaOpen}")
    private int isCaOpen;
    @Value("${newPdfPath}")
    private String newPdfPath;
    @Autowired
    private Archive_DetailService archiveDetailService;
    @Autowired
    private Archive_Detai_CaSignServiceImpl archiveDetaiCaSignService;
    @Autowired
    private Archive_Detail_ca_reqParamMapper archiveDetailCaReqParamMapper;
    @Autowired
    private CaSignatureMapper caSignatureMapper;
    @Autowired
    private ArchiveDetailCaCopyMapper archiveDetailCaCopyMapper;
    @Autowired
    private CaDepartIdMapper caDepartIdMapper;
    @Value("${synDepartUrl}")
    private String synDepartUrl;
    @Value("${signUrl}")
    private String signUrl;

    @Value("${clientId}")
    private String clientId;
    @Value("${clientSecret}")
    private String clientSecret;
    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    private static final Logger log = LoggerFactory.getLogger(lastVerifyController.class);

    @RequestMapping(value = "/lastVerifys")
    public String faults(Model model) {
        return "lastVerifyDir/lastVerifyList";
    }

    @ResponseBody
    @RequestMapping(value = "/lastVerifyList")
    public OffsetLimitPage lastVerifyList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        OffsetLimitPage result = archiveMasterService.selectByLast(archiveMasterVo, offset, limit);
        return result;
    }

    @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 = {"病案清单id","住院号","住院次数","名字","性别","出院科室","出院日期","主管医生","状态","医生是否提交","医生","医生提交日期","护士是否提交","护士","护士提交日期","电子病历医生提交","电子病历护士提交","是否死亡","是否有纸质补充资料送病案室","是否签收","是否扫描","是否打印","初审人"};
        String[] fileNames = {"id","inpNo","visitId","name","sex","deptName","dischargeDateTime","doctorInCharge","archivestate","cmtDoctor","doctorName","cmtDoctorDate","cmtNurse","nurseName","cmtNurseDate","emrDoctorCmt","emrNureCmt","deathFlag","isscaned","isSign","isScanning","printNum","firstInstance"};
        //文件名
        String fileName = "病案室终审" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Archive_Master_Vo> list = archiveMasterService.selectByLastByColumn(archiveMasterVo,null,null);
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result=utils.exportExcelToFilePath(response,utils.listConvert(list));
    }


    @ResponseBody
    @RequestMapping(value = "/getFaultType")
    public List<Emr_Fault_Type> getFaultType(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Type emrFaultType) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        List<Emr_Fault_Type> result = emrFaultTypeService.selectByCol(emrFaultType);
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/getDetailByArchId")
    public Emr_Fault_Detail getDetailByArchId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        Emr_Fault_Detail result = emrFaultDetailService.selectByArchiveDetailId(emrFaultDetail);
        return result;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/updateDetailByArchivId")
    public String updateDetailByArchivId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail,Integer returnFlag) throws UnsupportedEncodingException {
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if (!flag) {
            return "请不要重复提交!";
        }
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int bol=0;
       //修改病案归档状态：复审退回或主任退回
        Archive_Master archiveMaster = archiveMasterService.selectById(emrFaultDetail.getArchiveDetailId());
        if(archiveMaster!=null) {
            String inpatientNo = archiveMaster.getInpNo();
            //获取留观标识，“LG”
            String lgFlag = inpatientNo.substring(0,2);
            //查询该病案号缺陷，如果有医生就退回医生如果有护士则退回护士否则不退回提示
            Emr_Fault_Detail entityFault=new Emr_Fault_Detail();
            entityFault.setArchiveDetailId(emrFaultDetail.getArchiveDetailId());
            List<Emr_Fault_Detail> list=emrFaultDetailService.selectByArchiveId(entityFault);
//            //退回给emr
//            if(!"LG".equals(lgFlag)) {
//                String result = archiveMasterService.returnEmr(list,emrFaultDetail, archiveMaster, request);
//                if (StringUtils.isNotBlank(result)) {
//                    return result;
//                }
//            }
            archiveMaster.setArchivestate(emrFaultDetail.getState());
            int doctorFlagNum=0;
            int nurseFlagNum=0;
            if(list!=null && list.size()>0){
                // 从session获取用户名
                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());

                //2021-01-30
                Archive_Master_Following archive_master_following = new Archive_Master_Following();
                archive_master_following.setMasterId(emrFaultDetail.getArchiveDetailId());
                if (emrFaultDetail.getState().equals("主任退回")) {
                    //1医生 ，2护士
                    for (int k = 0; k < list.size(); k++) {
                        if ("1".equals(list.get(k).getBackFlag()) || "5".equals(list.get(k).getBackFlag())) {
                            doctorFlagNum=1;
                        }
                        if ("2".equals(list.get(k).getBackFlag()) || "6".equals(list.get(k).getBackFlag())) {
                            nurseFlagNum=1;
                        }
                    }
                    if(doctorFlagNum>0){
                        if (returnFlag!=1){
                            archiveMaster.setCmtDoctor(0);
                            archiveMaster.setDoctorName("");
                            archiveMaster.setCmtDoctorDate("");
                        }
                        //2021-01-30 following表中添加科主任退回主管医生操作记录
                        archive_master_following.setFollowingType("7");
                        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);
                    }
                    if(nurseFlagNum>0){
                        if (returnFlag!=1){
                            archiveMaster.setCmtNurse(0);
                            archiveMaster.setNurseName("");
                            archiveMaster.setCmtNurseDate("");
                        }
//                        if (returnFlag!=1){
//                            archiveMaster.setCmtDoctor(0);
//                            archiveMaster.setDoctorName("");
//                            archiveMaster.setCmtDoctorDate("");
//                        }
//                        archiveMaster.setCmtNurse(0);
//                        archiveMaster.setNurseName("");
//                        archiveMaster.setCmtNurseDate("");
                        //2021-01-30 following表中添加科主任退回护士长操作记录
                        archive_master_following.setFollowingType("6");
                        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);
                    }
                    //修改复审内容
                    if (bol == 1) {
                        //判断缺陷记录是否有医生或护士（有则退回状态改1）
                        //参数输入
                        emrFaultDetail.setCreater(username);
                        emrFaultDetail.setCreateTime(nowTime);
                        //插入缺陷记录
                        bol = emrFaultDetailService.insertSel(emrFaultDetail);
                    }
                }
                if(doctorFlagNum==0 && nurseFlagNum==0){
                    archiveMaster.setCmtDoctor(1);
                    archiveMaster.setCmtNurse(1);
                }
                bol = archiveMasterService.updateByClo(archiveMaster);
                if (emrFaultDetail.getState().equals("复审退回")) {
                    //2021-01-30 following表中添加病案室退回操作记录
                    archive_master_following.setFollowingType("9");
                    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);
                    archiveMasterService.updateByClo2(archiveMaster);
                    //退回给emr
                    if(!"LG".equals(lgFlag)) {
                        String result = archiveMasterService.returnEmr(list,emrFaultDetail, archiveMaster, request);
                        if (StringUtils.isNotBlank(result)) {
                            return result;
                        }
                    }
                }
                if("LG".equals(lgFlag)) {
                    //留观号审核推送第三方
                    archiveMasterService.requestObservationRecord(inpatientNo, "RETURNED",null,list);
                }

            }else{
                bol=2;
            }
        }
        return bol + "";
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/updateStateByArchivId")
    public Msg updateStateByArchivId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws UnsupportedEncodingException {
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if (!flag) {
            return Msg.fail("请不要重复提交!");
        }
        String inpatientNo = emrFaultDetail.getContent();
        if(StringUtils.isBlank(inpatientNo)){
            Archive_Master archiveMaster = archiveMasterService.selectById(emrFaultDetail.getArchiveDetailId());
            inpatientNo = archiveMaster.getInpNo();
        }
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String handleName = user.getUserPosition();//姓名
        String username = user.getUserName();//工号
        //调用ca签章接口
        if (isCaOpen==1){
            Msg msg = caSignByMasterId(emrFaultDetail.getArchiveDetailId(), user);
            if (msg.getCode()==200){
                return Msg.fail(msg.getMsg());
            }
        }
        //修改病案归档状态
        Archive_Master archiveMaster = new Archive_Master();
        archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
        archiveMaster.setArchivestate("已归档");
        archiveMaster.setCmtDoctor(1);
        int bol = archiveMasterService.updateByClo(archiveMaster);
        //归档记录添加到commomtable表
        CommomVo commomVo = new CommomVo();
        archiveMaster.setCmtNurse(1);
        List<Archive_Master> archiveMasters = archiveMasterService.selectCommonlyUsed(emrFaultDetail.getArchiveDetailId());
        for (Archive_Master list : archiveMasters) {
            commomVo.setPatientId(list.getId());
            commomVo.setAdmissTimes(list.getVisitId());
            commomVo.setInpatientNo(list.getInpNo());
            commomVo.setName(list.getName());
            commomVo.setAdmissId(list.getPatientId());
            commomVo.setSex(list.getSex());
            commomVo.setAdmissDate(list.getAdmissionDateTime());
            commomVo.setDisDate(list.getDischargeDateTime());
            commomVo.setDisDept(list.getDeptName());
            commomVo.setAttending(list.getDoctorInCharge());
            archiveMasterService.insertCommonlyUsed(commomVo);
        }
        //添加初审内容
        if (bol == 1) {
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = format1.format(new Date());
            emrFaultDetail.setCreater(username);
            emrFaultDetail.setCreateTime(nowTime);
            emrFaultDetail.setState("未召回");
            emrFaultDetailService.delbyCol(emrFaultDetail);
            emrFaultDetailService.insertSel(emrFaultDetail);
            //初审成功日志
            Archive_Master_Following archiveMasterFollowing = new Archive_Master_Following();
            archiveMasterFollowing.setMasterId(emrFaultDetail.getArchiveDetailId());
            //following表中添加病案室审核操作记录
            archiveMasterFollowing.setFollowingType("8");
            archiveMasterFollowing.setFollowingContent("病案室审核（已归档）");
            archiveMasterFollowing.setHandleTime(nowTime);
            archiveMasterFollowing.setHandleId(username);
            archiveMasterFollowing.setHandleName(handleName);
            archive_master_followingService.insertSelective(archiveMasterFollowing);
            //获取留观标识，“LG”
            String lgFlag = inpatientNo.substring(0,2);
            if("LG".equals(lgFlag)) {
                //留观号审核推送第三方
                archiveMasterService.requestObservationRecord(inpatientNo,"AUDITED",null,null);
            }
        }
        return Msg.success();
    }

    public Msg caSignByMasterId(String masterId, Power_User user) {
        if (isCaOpen == 0) {
            return Msg.success();
        }
        //根据masterId查询文件集合
        try {
            List<Archive_DetailPdfPathDto> pdfPathList = archiveDetailService.getPdfPathByMasterId(masterId);
            if (!CollectionUtils.isEmpty(pdfPathList)) {

                //判断该部门是否存在签章
                CaDepartIdVo caDepartIdVo = caDepartIdMapper.getDepartId(user.getRemark());
                //没有保存部门签章id时需要请求获取一个新的departId
                if (caDepartIdVo==null){
                    //请求医院科室在医网信标识id
                    String departId = getDepartId(user);
                    caDepartIdMapper.addDepartId(user.getRemark(),departId);
                    return Msg.fail("该用户科室没有在医信网平台申请部门签章请联系医信网人员");
                }
                if (StringUtils.isBlank(caDepartIdVo.getDataId())) {
                    return Msg.fail("部门标识为空");
                }
                String dataId = caDepartIdVo.getDataId();
                System.out.println("dataId:"+dataId);
                //保存文件表数据list
                List<Archive_DetailPdfPathDto> list = new ArrayList<>();
                //签章后保存目录
                String newPath = newPdfPath + File.separator + masterId;
                //没有目录创建目录
                if (!new File(newPath).isDirectory()) {
                    new File(newPath).mkdirs();
                }
                //查询签章位置比例
                Archive_Detail_ca_reqParam caReqParam = archiveDetailCaReqParamMapper.selectAll();
                //定义此次需要签章的文件id集合
                List<String> idList = new ArrayList<>();
                //签章失败文件id集合
                List<String> failIdList = new ArrayList<>();
                System.out.println("11");
                //遍历文件集合
                for (Archive_DetailPdfPathDto dto : pdfPathList) {
                    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    //获取今天日期
                    String todayDate = fmt.format(new Date());
                    //签章后地址
                    String newPdfPath = newPath + File.separator + todayDate+".pdf";
                    //获取文件路径
                    String pdfPath = dto.getPdfPath();
                    File file = new File(pdfPath);
                    System.out.println("22:");
                    if (file.isFile()) {
                        String pdfPathString = pdfToBase64(pdfPath);
                        PdfReader pdfReader = new PdfReader(pdfPath);
                        System.out.println("44");
                        int pageCount = pdfReader.getNumberOfPages();
                        Msg msg = sign(pdfPathString, dataId,caReqParam,pageCount);
                        if (msg.getCode()!=100){
                            return Msg.fail();
                        }
                        String newPdfPathBase64 = msg.getMsg();
                        if (!convertBase64ToPdf(newPdfPathBase64, newPdfPath)){
                            return Msg.fail();
                        }
                        dto.setPdfPath(newPdfPath);
                    } else {
                        return Msg.fail();
                    }
                    list.add(dto);
                }
                //添加签章记录
                updateCaFileState(idList, failIdList, masterId);
                //判断是否存在，存在在先删除
                int caMasterId = caSignatureMapper.getCaMasterId(masterId, 1);
                if (caMasterId > 0) {
                    archiveDetailCaCopyMapper.updateByMasterID(masterId);
                    caSignatureMapper.delCaMasterId(masterId);
                }
                //签章完后保存新的文件表
                archiveDetailCaCopyMapper.addArchiveDetailCaCopyMapper(list);
                //签章完成后保存状态
                caSignatureMapper.addCaSignature(masterId, 1);
            }
        } catch (Exception e) {
            System.out.println(e+e.getMessage());
            e.printStackTrace();
            return Msg.fail("请求失败");
        }
        return Msg.success();
    }


    @ResponseBody
    @RequestMapping(value = "/updateSignState")
    public String updateSignState(HttpServletRequest request, HttpServletResponse response, Archive_Master archiveMaster) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String result="";
        int isSign=archiveMaster.getIsSign();
        List<Archive_Master> list = archiveMasterService.selByCol(archiveMaster);
        if(list.size()>0){
            //修改
            archiveMaster=list.get(0);
            if(archiveMaster.getIsSign()!=isSign) {
                // 从session获取用户名
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                String username = user.getUserName();//获取前面登录的用户名
                //参数输入
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = format.format(new Date());
                archiveMaster.setIsSign(isSign);
                if (isSign == 0) {
                    archiveMaster.setSigner("");
                    archiveMaster.setSignTime("");
                } else if (isSign == 1) {
                    System.out.println((archiveMaster.getIsscaned().equals("1"))+"===="+archiveMaster.getIsscaned()!="1");
                    if(archiveMaster.getIsscaned().equals("0")) {
                        result = "无纸质，无需签收!";
                        return  result;
                    }else {
                        archiveMaster.setSigner(username);
                        archiveMaster.setSignTime(nowTime);
                    }
                }
                int bol = archiveMasterService.updateByClo(archiveMaster);
                if (bol == 1) {
                    String followingContent="";
                    String followingType="";
                    if(isSign == 1) {
                        result = "该份病案签收成功!";
                        followingContent="病案签收成功";
                        followingType="13";
                    }else{
                        result = "该份病案取消签收成功!";
                        followingContent="病案取消签收成功";
                        followingType="14";
                    }
                    //2021-05-13 following表中添加签收操作记录
                    String handleName = user.getUserPosition();//姓名
                    Archive_Master_Following archive_master_following = new Archive_Master_Following();
                    archive_master_following.setMasterId(archiveMaster.getId());
                    archive_master_following.setFollowingType(followingType);
                    archive_master_following.setFollowingContent(followingContent);
                    archive_master_following.setHandleTime(nowTime);
                    archive_master_following.setHandleId(username);
                    archive_master_following.setHandleName(handleName);
                    archive_master_followingService.insertSelective(archive_master_following);
                } else {
                    result = "该份病案签收失败!";
                }
            }else{
                if(isSign==1) {
                    result = "该份病案已经签收!";
                }else if(isSign==0){
                    result = "该份病案已经取消签收!";
                }
            }
        }else{
            result="该份病案并不存在!";
        }
        return result;
    }


    @RequestMapping("getImg2")
    public void getImg2(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(path);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/updateScore")
    public int updateScore(Archive_Master archive_master){
        return archiveMasterService.updateByClo(archive_master);
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/emrShowBackReason")
    public String emrShowBackReason(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws Exception {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String nowTime = format1.format(new Date());
        //退回原因
        StringBuffer assortName = new StringBuffer();
        List<Emr_Fault_Vo> list = emrFaultDetailService.selectByColumn(emrFaultDetail);
        for (Emr_Fault_Vo emr_fault_vo:list) {
            assortName.append(emr_fault_vo.getAssortName()+";");
        }
        Archive_Master archive_master = archiveMasterService.selectById(emrFaultDetail.getArchiveDetailId());
        String result="false";
        if (archive_master!=null){
            result = emrWebServiceShowBackReason(archive_master.getPatientId(),
                    Integer.parseInt(archive_master.getVisitId()),
                    nowTime,
                    assortName.toString(),
                    archive_master.getInpNo());
            if (result.contains("true")){
                result = "true";
            }
        }
        return result;
    }

    public String emrWebServiceShowBackReason(String PATIENT_ID,int VISIT_ID,String nowTime,String APPLY_REASON,String INP_NO) throws Exception {
        String MR_FILE_CALLBACK_RECORD="";//入参1
        String MR_FILE_INDEX_CALLBACK="";//入参2

        com.emr.webservice.MedicalRecordShowBackContent.MR_FILE_CALLBACK_RECORD inputParam1 = new MR_FILE_CALLBACK_RECORD();
        inputParam1.setPATIENT_ID(PATIENT_ID);
        inputParam1.setVISIT_ID(VISIT_ID);
        inputParam1.setFILE_UNIQUE_ID("1");
        inputParam1.setAPPLY_DATE_TIME(nowTime);
        inputParam1.setAPPLY_TIME_LIMIT(nowTime);
        inputParam1.setAPPLY_REASON(APPLY_REASON);
        inputParam1.setEXPIRY_TIME(nowTime);
        //其他为""参数
        inputParam1.setAPPLY_USER_ID("1");
        inputParam1.setAPPLY_USER_NAME("1");
        inputParam1.setAPPLY_DEPT_CODE("1");
        inputParam1.setSTATUS(0);
        inputParam1.setAPPROVE_USER_ID("1");
        inputParam1.setAPPROVE_USER_NAME("1");
        inputParam1.setAPPROVE_DEPT_CODE("1");
        inputParam1.setAPPROVE_DATE_TIME(nowTime);
        inputParam1.setCLINIC_TYPE(0);
        inputParam1.setAPPROVE_REASON("1");
        inputParam1.setAPPROVE_USER_ID_DIRECTOR("1");
        inputParam1.setAPPLY_USER_NAME_DIRECTOR("1");
        inputParam1.setAPPROVE_DEPT_CODE_DIRECTOR("1");
        inputParam1.setAPPROVE_DATE_TIME_DIRECTOR(nowTime);
        inputParam1.setAPPLY_REASON_DIRECTOR("1");
        inputParam1.setAPPROVE_USER_ID_MEDICAL("1");
        inputParam1.setAPPLY_USER_NAME_MEDICAL("1");
        inputParam1.setAPPROVE_DEPT_CODE_MEDICAL("1");
        inputParam1.setAPPROVE_DATE_TIME_MEDICAL(nowTime);
        inputParam1.setAPPLY_REASON_MEDICAL("1");
        inputParam1.setRECEIVE_USERID("1");

        com.emr.webservice.MedicalRecordShowBackContent.MR_FILE_INDEX_CALLBACK inputParam2 = new MR_FILE_INDEX_CALLBACK();
        inputParam2.setPATIENT_ID(PATIENT_ID);
        inputParam2.setVISIT_ID(VISIT_ID);
        inputParam2.setAPPLY_DATE_TIME(nowTime);
        inputParam2.setAPPLY_TIME_LIMIT(nowTime);
        inputParam2.setAPPLY_USER_NAME("1");
        inputParam2.setAPPLY_DEPT_CODE("1");
        inputParam2.setSTATUS(1);
        inputParam2.setAPPROVE_USER_ID("1");
        inputParam2.setAPPROVE_USER_NAME("1");
        inputParam2.setAPPROVE_DEPT_CODE("1");
        inputParam2.setAPPROVE_DATE_TIME(nowTime);
        inputParam2.setAPPLY_REASON(APPLY_REASON);
        inputParam2.setCLINIC_TYPE(0);
        inputParam2.setOPERATOR_TYPE(0);
        inputParam2.setLIMIT_DATE(nowTime);
        //其他为""参数
        inputParam2.setAPPROVE_REASON("1");
        inputParam2.setISCOPYBACK(0);
        inputParam2.setIS_FIRSTPAGE(0);
        inputParam2.setMRBACK_STATUS(0);
        inputParam2.setIS_APPROVE(1);
        inputParam2.setINP_NO(INP_NO);
        inputParam2.setBACK_TYPE(0);
        inputParam2.setFINISH_DATE_TIME(nowTime);
        inputParam2.setAPPROVE_USER_ID_DIRECTOR("1");
        inputParam2.setAPPLY_USER_NAME_DIRECTOR("1");
        inputParam2.setAPPROVE_DEPT_CODE_DIRECTOR("1");
        inputParam2.setAPPROVE_DATE_TIME_DIRECTOR(nowTime);
        inputParam2.setAPPLY_REASON_DIRECTOR("1");
        inputParam2.setAPPROVE_USER_ID_MEDICAL("1");
        inputParam2.setAPPLY_USER_NAME_MEDICAL("1");
        inputParam2.setAPPROVE_DEPT_CODE_MEDICAL("1");
        inputParam2.setAPPROVE_DATE_TIME_MEDICAL(nowTime);
        inputParam2.setAPPLY_REASON_MEDICAL("1");
        inputParam2.setAPPROVE_HOST_IP("1");
        inputParam2.setAPPROVE_HOST_NAME("1");
        inputParam2.setAPPROVE_HOST_MAC_ADD("1");
        inputParam2.setHOSPITAL_NO("12440000455858169P");

        MR_FILE_CALLBACK_RECORD = XMLUtil.convertToXml(inputParam1);
        MR_FILE_INDEX_CALLBACK = XMLUtil.convertToXml(inputParam2);

        StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>\n<root>\n");
        sb.append(MR_FILE_CALLBACK_RECORD);
        sb.append("\n");
        sb.append(MR_FILE_INDEX_CALLBACK);
        sb.append("\n");
        sb.append("</root>");

        String result="";
        try {
            String endpoint = EMRQualityControl;
            String[] subStrs = endpoint.split("=");
            String url = "";
            String subStr ="";
            url = subStrs[0];
            if(subStrs.length>1){
                subStr = getURLEncoderString(subStrs[1]);
            }
            endpoint = url+"="+subStr;
            Service service = new Service();
            Call call = null;
            try {
                call = (Call) service.createCall();
            } catch (ServiceException e) {

            }
            call.setTargetEndpointAddress(endpoint);
            call.setOperationName(new QName("http://bjgoodwillcis.com", "XMLMessageServer"));
            call.addParameter(EMRQualityControlParamName, XMLType.XSD_STRING, ParameterMode.IN);//接口的参数
            call.setReturnType(XMLType.XSD_STRING);//设置返回类型
            try {
                result = (String) call.invoke(new Object[]{sb.toString()});
            } catch (RemoteException e) {
                e.printStackTrace();
                result = e.getMessage();
                System.err.println(result);
            }
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return result;
    }

    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "/getUserInfn")
    public Power_User getUserInfn(HttpServletRequest request){
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        return user;
    }



    @ResponseBody
    @RequestMapping(value = "/getPatientInfn")
    public Archive_Master getPatientInfn(String id){
        Archive_Master archiveMaster = archiveMasterService.selectById(id);
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //转换科室
        Map<String, Emr_Dictionary> codeMap = ListUtil.toMap(dicList, Emr_Dictionary::getCode);
            String deptCode = archiveMaster.getDeptName();
            if(StringUtils.isNotBlank(deptCode) && codeMap.containsKey(deptCode)){
                String deptName = codeMap.get(deptCode).getName();
                archiveMaster.setDeptNameCode(deptName);
            }

        return archiveMaster;
    }



    //将pdf文件base64方法
    public static String pdfToBase64(String filePath) throws IOException {
        File file = new File(filePath);
        // 读取文件内容到字节数组
        byte[] fileContent = Files.readAllBytes(file.toPath());
        // 将字节数组编码为Base64字符串
        System.out.println("33");
        return Base64.getEncoder().encodeToString(fileContent);

    }
    //将base64转为pdf方法
    public Boolean convertBase64ToPdf(String base64String, String filePath) {
        try {
            // 解码Base64字符串
            byte[] decodedBytes = Base64.getDecoder().decode(base64String);

            // 将解码后的数据写入PDF文件
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                fos.write(decodedBytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }



    //签章接口
    private Msg sign(String pdfPathString,String departId,Archive_Detail_ca_reqParam caReqParam,int pageCount) {
        try {
            System.out.println("55");
            // 创建OkHttpClient实例
            OkHttpClient client = HttpClientUtil.getClient();
            System.out.println("10");
            // 定义请求的URL
            String url = signUrl;
            String pdfSignBase64="";
            // 创建请求体
            String json = "{"
                    + "\"head\": {"
                    + "\"clientId\": \"" + clientId + "\","
                    + "\"clientSecret\": \"" + clientSecret + "\","
                    + "},"
                    + "\"body\": {"
                    + "\"pdfBase64\":  \"" + pdfPathString + "\","
                    + "\"departId\":  \"" + departId + "\","
    //                + "\"keyword\": \"医师签名\","
    //                + "\"moveType\": \"1\","
    //                + "\"searchOrder\": \"2\","
    //                + "\"scale\": \"0.4\","
    //                + "\"fileType\": \"2\","
                    + "\"positionType\": \"1\","
                    + "\"x\": \"" + caReqParam.getSignTop() + "\","
                    + "\"y\":  \"" + caReqParam.getSignLeft() + "\","
                    + "}"
                    + "}";
            // 创建RequestBody

            log.info("签章传参“："+json);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
            System.out.println("77");
            // 创建Request
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 检查响应状态码
                if (response.isSuccessful()) {
                    // 获取响应体
                    String responseData = response.body().string();

                    // 解析JSON响应
                    JSONObject jsonResponse = new JSONObject(responseData);
                    // 获取返回的参数
                    pdfSignBase64 = jsonResponse.getJSONObject("data").getString("pdfSignBase64");
                    String status = jsonResponse.getString("status");
                    if (!status.equals("0")){
                        return Msg.fail("请求失败");
                    }
                } else {
                    System.out.println("请求失败，状态码：" + response.code());
                }
            } catch (Exception e) {
                System.out.println(e+e.getMessage());
                e.printStackTrace();
                return Msg.fail("请求失败，状态码：");
            }
            return Msg.success(pdfSignBase64);
        } catch (Exception e) {
            System.out.println(e+e.getMessage());
        }
        return Msg.success("成功");
    }

    //请求医信网标识id
    public String getDepartId(Power_User user) {
        // 创建OkHttpClient实例
        OkHttpClient client = HttpClientUtil.getClient();

        // 定义请求的URL
        String url = synDepartUrl;
        String dataId = "";
        // 创建请求体
        String json = "{"
                + "\"head\": {"
                + "\"clientId\": \"" + clientId + "\","
                + "\"clientSecret\": \"" + clientSecret + "\","
                + "},"
                + "\"body\": {"
                + "\"thirdDepartId\": \"3040000\","
                + "\"departName\": \"病案室\","
                + "\"departPhone\":  \"" + user.getUserEmail() + "\","
                + "\"departPerson\": \"" + user.getUserPosition() + "\","
                + "\"clientOrgCode\": \"BAS\","
                + "\"clientOrgType\": \"ORG\""
                + "}"
                + "}";

        // 创建RequestBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        // 创建Request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try {
            // 执行请求
            Response response = client.newCall(request).execute();

            // 检查响应状态码
            if (response.isSuccessful()) {
                // 获取响应体
                String responseData = response.body().string();

                // 解析JSON响应
                JSONObject jsonResponse = new JSONObject(responseData);

                // 获取返回的参数
                dataId = jsonResponse.getJSONObject("data").getString("departId");
                String message = jsonResponse.getString("message");
                String status = jsonResponse.getString("status");
                boolean successful = jsonResponse.getBoolean("successful");

                // 输出解析结果
                System.out.println("DepartId: " + dataId);
                System.out.println("Message: " + message);
                System.out.println("Status: " + status);
                System.out.println("Successful: " + successful);
            } else {
                System.out.println("请求失败，状态码：" + response.code());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataId;
    }

    /**
     * @Description: updateCaFileState方法是更新ca签章
     * @param: [idList, masterId]
     * @return: void
     * @author 曾文和
     * @createTime 2023/7/25 16:19
     */
    public void updateCaFileState(List<String> idList, List<String> failIdList, String masterId) {
        if (!CollectionUtils.isEmpty(idList)) {
            //先删除原有签章记录
            archiveDetaiCaSignService.deletesFromMasterId(masterId);
            //后新增
            List<Archive_Detail_caSign> list = new ArrayList<>();
            Date date = new Date();
            for (String id : idList) {
                Archive_Detail_caSign obj = new Archive_Detail_caSign();
                obj.setArchiveDetailId(id);
                obj.setMasterId(masterId);
                obj.setSignTime(date);
                obj.setCaStatic(1);
                list.add(obj);
            }
            if (!CollectionUtils.isEmpty(failIdList)) {
                for (String id : failIdList) {
                    Archive_Detail_caSign obj = new Archive_Detail_caSign();
                    obj.setArchiveDetailId(id);
                    obj.setMasterId(masterId);
                    obj.setSignTime(date);
                    obj.setCaStatic(2);
                    list.add(obj);
                }
            }
            //批量新增
            archiveDetaiCaSignService.insertBatchCaSign(list);
        }
    }
}
 

