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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emr.entity.*;
import com.emr.service.*;
import com.emr.util.HttpClientTool;
import com.emr.util.IDHelper;
import com.emr.util.ThreadExcelUtils;
import com.emr.util.XMLUtil;
import com.emr.vo.CollectionVo;
import com.emr.webservice.MedicalRecordShowBackContent.MR_FILE_CALLBACK_RECORD;
import com.emr.webservice.MedicalRecordShowBackContent.MR_FILE_INDEX_CALLBACK;
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.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.*;



@Controller
@RequestMapping("signList")
public class signListController {
    @Value("${EMRQualityControl}")
    private String EMRQualityControl;
    @Value("${EMRQualityControlParamName}")
    private String EMRQualityControlParamName;

    @Autowired
    private Sign_ListService signListService;

    @Autowired
    private Archive_MasterService archiveMasterService;

    @Autowired
    private Emr_Fault_TypeService emrFaultTypeService;

    @Autowired
    private PowerUserService powerUserService;

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).build();
    }


    @Autowired
    private Emr_Fault_DetailService emrFaultDetailService;

    @Autowired(required = false)
    private Archive_Master_FollowingService archive_master_followingService;



    @RequestMapping(value = "/signLists")
    public String faults(Model model) {
        return "signListDir/signList";
    }

    @ResponseBody
    @RequestMapping(value = "/signList")
    public OffsetLimitPage signList(HttpServletRequest request, HttpServletResponse response, Sign_List_Vo signListVo, Integer offset, Integer limit) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        OffsetLimitPage result = signListService.selectSignList(signListVo, offset, limit);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Sign_List_Vo signListVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id", "住院号", "住院次数", "名字", "出院科室", "出院日期", "签收状态", "是否有纸质病历送病案室", "签收人", "签收日期", "签收次数"};
        String[] fileNames = {"id", "inpNo", "visitId", "name", "deptName", "dischargeDateTime", "c5", "isscaned", "c1", "dTime", "num"};
        //文件名
        String fileName = "纸质病历签收列表" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Sign_List_Vo> list = signListService.selectSignList(signListVo);
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result = utils.exportExcelToFilePath(response, utils.listConvert(list));
    }

    @ResponseBody
    @RequestMapping(value = "/selSignByColm")
    public OffsetLimitPage selSignByColm(HttpServletRequest request, HttpServletResponse response, SignList signList, Integer offset, Integer limit) {
        OffsetLimitPage result = signListService.selSignByColm(signList, offset, limit);
        return result;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/delotherId")
    public String delotherId(HttpServletRequest request, HttpServletResponse response, String id) {
        signListService.deleteSignListById(id);
        return "取消签收成功!";
    }


    @ResponseBody
    @RequestMapping(value = "/addSignList")
    public String addSignList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if (!flag) {
            return "请不要重复提交!";
        }
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String result = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Archive_Master> master = archiveMasterService.selectByInpAndVisitId(archiveMasterVo);
        Sign_List signList = new Sign_List();
        if (master != null && master.size() > 0) {
            if (!"0".equals(master.get(0).getIsscaned())) {
                //判断master表里纸质病历已经提交，且有医生提交记录，则取医生数据作为提交人，否则护士为提交人
                signList.setC2("".equals(master.get(0).getDoctorName()) && master.get(0).getDoctorName() != null ? master.get(0).getDoctorName() : master.get(0).getNurseName());
                //送纸质病历者所在科室
                JSONArray powerUsers = powerUserService.getPowerUserList("1");
                List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
                ln:
                for (JSONObject jsonObjectNew : powerUserList) {
                    if (jsonObjectNew.getString("userName").equals(signList.getC2())) {
                        signList.setC3(jsonObjectNew.getString("deptId"));
                        break ln;
                    }
                }
                //signList.setC3()
                signList.setSysFlag(1);
                signList.setMasterID(master.get(0).getId());
                signList.setPid(master.get(0).getPatientId());
                signList.setOperateName(archiveMasterVo.getOperateName());
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                String username = user.getUserName();
                signList.setC1(username);
                signList.setC5("1");

                signList.setId(IDHelper.NewID());
            /*signList.setC2(master.get(0).getSigner());
            signList.setC3(master.get(0).getDeptName());*/
                signList.setCreatedtime(sdf.format(new Date()));
                signList.setdTime(sdf.format(new Date()));
                signList.setT1(sdf.format(new Date()));
                Archive_Master archiveMaster = new Archive_Master();
                archiveMaster.setIsSign(1);
                archiveMaster.setId(master.get(0).getId());
                int bol = archiveMasterService.updateByClo(archiveMaster);
                int z = signListService.insertSignList(signList);
                result = "签收成功";
            } else {
                result = "该病历归档医生或护士尚未提交，是否强制签收？";
            }
        } else {
            result = "未查询到住院号为:" + archiveMasterVo.getInpNo() + "的患者住院病历信息";
        }
        //OffsetLimitPage result = archiveMasterService.selectByLast(archiveMasterVo);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/addSignListForce")
    public String addSignListForce(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String result = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if ((StringUtils.isNotBlank(archiveMasterVo.getInpNo()) && StringUtils.isNotBlank(archiveMasterVo.getVisitId())) || (StringUtils.isNotBlank(archiveMasterVo.getPatientId()) && StringUtils.isNotBlank(archiveMasterVo.getVisitId()))) {
            List<Archive_Master> master = archiveMasterService.selectByCol(archiveMasterVo);
            Sign_List signList = new Sign_List();
            signList.setOtherInfo("强制签收");
            //判断master表里纸质病历已经提交，且有医生提交记录，则取医生数据作为提交人，否则护士为提交人
            signList.setC2("".equals(master.get(0).getDoctorName()) && master.get(0).getDoctorName() != null ? master.get(0).getDoctorName() : master.get(0).getNurseName());
            //送纸质病历者所在科室
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
            ln:
            for (JSONObject jsonObjectNew : powerUserList) {
                if (jsonObjectNew.getString("userName").equals(signList.getC2())) {
                    signList.setC3(jsonObjectNew.getString("deptId"));
                    break ln;
                }
            }
            signList.setSysFlag(1);
            signList.setMasterID(master.get(0).getId());
            signList.setPid(master.get(0).getPatientId());
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String username = user.getUserName();
            signList.setC1(username);
            signList.setC5("1");
            signList.setId(IDHelper.NewID());
            signList.setCreatedtime(sdf.format(new Date()));
            signList.setdTime(sdf.format(new Date()));
            signList.setT1(sdf.format(new Date()));
            Archive_Master archiveMaster = new Archive_Master();
            archiveMaster.setIsSign(1);
            int bol = archiveMasterService.updateByClo(archiveMaster);
            signListService.insertSignList(signList);
            result = "签收成功";
        } else {
            result = "缺少患者住院号及住院次数";
        }
        return result;
    }

   /* @ResponseBody
    @RequestMapping(value = "/signList")
    public OffsetLimitPage signList(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 = "/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 int updateDetailByArchivId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int bol = 0;
        //修改病案归档状态：复审退回或主任退回
        Archive_Master archiveMaster = archiveMasterService.selectById(emrFaultDetail.getArchiveDetailId());
        if (archiveMaster != null) {
            archiveMaster.setArchivestate(emrFaultDetail.getState());
            //查询该病案号缺陷，如果有医生就退回医生如果有护士则退回护士否则不退回提示
            Emr_Fault_Detail entityFault = new Emr_Fault_Detail();
            entityFault.setArchiveDetailId(emrFaultDetail.getArchiveDetailId());
            List<Emr_Fault_Detail> list = emrFaultDetailService.selectByArchiveId(entityFault);
            int doctorFlagNum = 0;
            int nurseFlagNum = 0;
            if (list != null && list.size() > 0) {
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = format1.format(new Date());

                //2021-01-30
                Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
                String handleName = user.getUserPosition();//姓名
                String username = user.getUserName();//获取前面登录的用户名
                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) {
                        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) {
                        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);
                }
            } else {
                bol = 2;
            }
        }
        return bol;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/updateStateByArchivId")
    public int updateStateByArchivId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //修改病案归档状态
        Archive_Master archiveMaster = new Archive_Master();
        archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
        archiveMaster.setArchivestate("已归档");
        archiveMaster.setCmtDoctor(1);
        archiveMaster.setCmtNurse(1);
        int bol = archiveMasterService.updateByClo(archiveMaster);

        //添加初审内容
        if (bol == 1) {
            // 从session获取用户名
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            String username = user.getUserName();//获取前面登录的用户名

            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = format1.format(new Date());

            //参数输入
            emrFaultDetail.setCreater(username);
            emrFaultDetail.setCreateTime(nowTime);
            emrFaultDetail.setState("未召回");
            //判断是否已经有召回记录
            Emr_Fault_Vo vo = new Emr_Fault_Vo();
            vo.setArchiveDetailId(emrFaultDetail.getArchiveDetailId());
            List<Emr_Fault_Vo> list = emrFaultDetailService.selectByCol(vo);
            if (list.size() > 0) {
                bol = emrFaultDetailService.delbyCol(emrFaultDetail);
                if (bol == 1) {
                    bol = emrFaultDetailService.insertSel(emrFaultDetail);
                }
            } else {
                bol = emrFaultDetailService.insertSel(emrFaultDetail);
            }

            //初审成功日志
            String handleName = user.getUserPosition();//姓名
            Archive_Master_Following archive_master_following = new Archive_Master_Following();
            archive_master_following.setMasterId(emrFaultDetail.getArchiveDetailId());
            //following表中添加病案室审核操作记录
            archive_master_following.setFollowingType("8");
            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;
    }

    @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.setIsSign(0);
                        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 = "/collection")
//    public String collection(HttpServletRequest request, HttpServletResponse response, int flagNum, String id, String pid) throws Exception {
//        response.setCharacterEncoding("utf-8");
//        request.setCharacterEncoding("utf-8");
//        // 从session获取用户名
//        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
//        String username = user.getUserName();//工号
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date_1801 = sdf.parse("1801-02-03 00:00:00");
//
//        //新增ext表数据逻辑
//        Archive_Master archive_master = archiveMasterService.selectById(id);
//        if (archive_master != null) {
//            //查ext表有无任务
//            ArchiveOtherExt archiveOtherExtParm = new ArchiveOtherExt();
//            archiveOtherExtParm.setMid(id);
//            archiveOtherExtParm.setSysflag(-300);
//            List<ArchiveOtherExt> extList = archiveOtherExtService.selectExtTaskIsExistOrNot(archiveOtherExtParm);
//            if (!extList.isEmpty() && extList.size() == 1) {
//                //有任务，则ext表更新statusFlag=0，对应C3-C8置空，T1-T6置空，其他不变
//                //1.statusFlag=0
//                extList.get(0).setStatusflag(0);
//                //2.对应C3-C8置空，T1-T6置空
//                switch (flagNum) {
//                    //体温单
//                    case 1:
//                        extList.get(0).setC5("");
//                        extList.get(0).setT3(date_1801);
//                        break;
//                    //护理记录
//                    case 2:
//                        extList.get(0).setC6("");
//                        extList.get(0).setT4(date_1801);
//                        break;
//                    //首页
//                    case 3:
//                        extList.get(0).setC3("");
//                        extList.get(0).setT1(date_1801);
//                        break;
//                    //医生文书
//                    case 4:
//                        extList.get(0).setC4("");
//                        extList.get(0).setT2(date_1801);
//                        break;
//                    //评估单
//                    case 5:
//                        extList.get(0).setC8("");
//                        extList.get(0).setT6(date_1801);
//                        break;
//                    //护士文书
//                    case 6:
//                        extList.get(0).setC7("");
//                        extList.get(0).setT5(date_1801);
//                        break;
//                }
//                archiveOtherExtService.updateByPrimaryKeySelective(extList.get(0));
//            } else if (extList.isEmpty() || extList.size() < 0) {
//                //无任务，则新增
//                OracleDateVo doctorNurseFinishedDatetime = finishedDateTimeService.findByID(archive_master.getInpNo(), archive_master.getVisitId());
//                //V6医生最后完成时间
//                String doctorFinishedDateTime = sdf.format(doctorNurseFinishedDatetime.getFinishedDateTime());
//                //V6护士最后完成时间
//                String nurseFinishedDateTime = sdf.format(doctorNurseFinishedDatetime.getMrCommitNurseDateTime());
//                ArchiveOtherExt archiveOtherExt = new ArchiveOtherExt(IDHelper.NewID(), new Date(), "按需采集", 0L, -300, date_1801, pid,
//                        archive_master.getInpNo(), date_1801, date_1801, 0, "", id, archive_master.getVisitId(),
//                        doctorFinishedDateTime, nurseFinishedDateTime, "Done", "Done", "Done", "Done", "Done", "Done", "", archive_master.getName(),
//                        BigDecimal.valueOf(0.0000), BigDecimal.valueOf(0.0000), BigDecimal.valueOf(0.0000),
//                        date_1801, date_1801, date_1801, date_1801, date_1801, date_1801);
//                //对应C3-C8置空,T无需置空
//                switch (flagNum) {
//                    //体温单
//                    case 1:
//                        archiveOtherExt.setC5("");
//                        break;
//                    //护理记录
//                    case 2:
//                        archiveOtherExt.setC6("");
//                        break;
//                    //首页
//                    case 3:
//                        archiveOtherExt.setC3("");
//                        break;
//                    //医生文书
//                    case 4:
//                        archiveOtherExt.setC4("");
//                        break;
//                    //评估单
//                    case 5:
//                        archiveOtherExt.setC8("");
//                        break;
//                    //护士文书
//                    case 6:
//                        archiveOtherExt.setC7("");
//                        break;
//                }
//                archiveOtherExtService.insertSelective(archiveOtherExt);
//            } else {
//                //archive_Other_Ext表已经存在记录,且不只1条,删除多余或采集接口那边需要调整
//                return "同一个病案ID,ext表只允许1条数据!";
//            }
//        }
//
//        //新增other表数据逻辑
//        Sign_List signList = new Sign_List();
//        signList.setPid(pid);
//        signList.setMasterID(id);
//        int num = 0;
//        switch (flagNum) {
//            //体温单
//            case 1:
//                num = -401;
//                break;
//            //护理记录
//            case 2:
//                num = -402;
//                break;
//            //首页
//            case 3:
//                num = -403;
//                break;
//            //医生文书
//            case 4:
//                num = -404;
//                break;
//            //评估单
//            case 5:
//                num = -405;
//                break;
//            //护士文书
//            case 6:
//                num = -406;
//                break;
//        }
//        signList.setSysFlag(num);
//        signList.setC5("0");
//        List<Sign_List> list = signListService.selectSignListWith(signList);
//        if (list != null && list.size() > 0) {
//            return "当前采集计划已存在，请勿重复发起!";
//        } else {
//            signList.setId(IDHelper.NewID());
//            signList.setCreatedtime(sdf.format(new Date()));
//            signList.setC1(username);
//            signList.setIsFullText("0");
//            signList.setOtherInfo("");
//            signList.setDetailID("");
//            signList.setdTime(sdf.format(sdf.parse("1801-02-03 00:00:00")));
//            signList.setC2("");
//            signList.setC3("");
//            signList.setC4("");
//            signList.setN1(BigDecimal.valueOf(0.0000));
//            signList.setN2(BigDecimal.valueOf(0.0000));
//            signList.setN3(BigDecimal.valueOf(0.0000));
//            signList.setT1(sdf.format(sdf.parse("1801-02-03 00:00:00")));
//            signList.setT2(sdf.format(sdf.parse("1801-02-03 00:00:00")));
//            signList.setT3(sdf.format(sdf.parse("1801-02-03 00:00:00")));
//            signListService.insertSignList(signList);
//            return "采集计划已生成!";
//        }
//    }


    @ResponseBody
    @RequestMapping(value = "/collection")
    public JSONObject collection(HttpServletRequest request, HttpServletResponse response, String flagNum, String id) throws Exception {
//        String taskId = afCollectTaskService.getTaskId(flagNum, id);
//        String url="http://127.0.0.1:9296/api/noviewtask/UrgentMakeUp";
//        String s = sendGet(url, taskId);
        CollectionVo collectionVo = new CollectionVo();
        List<String> patientIds=new ArrayList<>();
        patientIds.add(id);
        collectionVo.setPatientIds(patientIds);
        collectionVo.setSysCodes(flagNum);
        String url="http://10.6.1.127:9295/api/NoViewCollect/generateTaskByPatientIdAndSysCodes";
        JSONObject jsonParam= (JSONObject) JSONObject.toJSON(collectionVo);
        JSONObject jsonObject = httpPost(url, jsonParam);
        //查询新任务表id
        return jsonObject;
    }

    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    System.out.println("post请求提交失败");
                }
            }
        } catch (IOException e) {
            System.out.println("post请求提交失败");
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?taskid=" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}
 

