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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emr.dao.Archive_MasterMapper;
import com.emr.entity.*;
import com.emr.service.*;
import com.emr.util.IDHelper;
import com.emr.util.ThreadExcelUtils;
import com.emr.util.XMLUtil;
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.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.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.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@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;


    @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");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //签收日期没进行选择的话则默认显示的是当前日期的数据
        if (signListVo.getStartSignDate() == null || "".equals(signListVo.getStartSignDate())) {
            signListVo.setStartSignDate(sdf.format(new Date()));
        }
        if (signListVo.getEndSignDate() == null || "".equals(signListVo.getEndSignDate())) {
            signListVo.setEndSignDate(sdf.format(new Date()));
        }
        OffsetLimitPage result = signListService.selectSignList(signListVo, offset, limit);
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/addSignList")
    public String addSignList(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");
        List<Archive_Master> master = archiveMasterService.selectByCol(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());

                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()));
                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())) {
            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()));
            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 = "/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", "idNo", "deptName", "dischargeDateTime", "doctorInCharge", "archivestate", "cmtDoctor", "doctorName", "cmtDoctorDate", "cmtNurse", "nurseName", "cmtDurseDate", "emrDoctorCmt", "emrNureCmt", "deathFlag", "is_sign", "signer", "sign_time"};
        //文件名
        String fileName = "病案室终审" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Archive_Master_Vo> list = archiveMasterService.selectByLast(archiveMasterVo);
        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 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);
                }
            } 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.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();//工号
        String result = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        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");
            signListService.insertSignList(signList);
            return "采集计划已生成！";
        }
    }
}
 

