package com.yihu.jw.hospital.prescription.service.entrance;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.dict.WlyyChargeDictDO;
import com.yihu.jw.entity.hospital.doctor.BaseDoctorZsInfoDO;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.hospital.dict.WlyyChargeDictDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.prescription.dao.DoctorZsInfoDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionEmrDao;
import com.yihu.jw.hospital.prescription.service.entrance.util.ConvertUtil;
import com.yihu.jw.hospital.prescription.service.entrance.util.MqSdkUtil;
import com.yihu.jw.hospital.prescription.service.entrance.util.WebserviceUtil;
import com.yihu.jw.restmodel.hospital.archive.ArchiveVO;
import com.yihu.jw.restmodel.hospital.prescription.*;
import com.yihu.jw.util.common.PwdUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.idcard.IdCardUtil;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
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.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 互联网医院对外服务
 * Created by zdm on 2019/5/20.
 */
@Service
@Transactional
public class EntranceService {
    private Logger logger = LoggerFactory.getLogger(EntranceService.class);
    //门诊余额查询
    private static String BS15017 = "BS15017";
    //门诊就诊卡列表
    private static String BS15018 = "BS15018";
    //门诊处方信息（所有处方）
    private static String BS16017 = "BS16017";
    //患者门诊就诊记录
    private static String BS30025 = "BS30025";
    //医院药品字典
    private static String MS30001 = "MS30001";
    //门诊给药方式接口
    private static String BS10110 = "BS10110";
    //线上挂号接口
    private static String BS10111 = "BS10111";
    //线上退号接口
    private static String BS10138 = "BS10138";
    //查询待结算费用
    private static String BS15054 = "BS15054";
    //线上处方接口
    private static String BS10112 = "BS10112";
    //医生挂号权限查询接口
    private static String BS10114 = "BS10114";
    //科室字典
    private static String MS02001 = "MS02001";
    //号别字典接口
    private static String MS02013 = "MS02013";
    //医院频次字典表
    private static String MS30012 = "MS30012";

    private String orgCode = "350211A1002";
    private String orgName = "350211A1002";
    @Value("${hospital.mqUser}")
    private String mqUser;
    @Value("${hospital.mqPwd}")
    private String mqPwd;
    @Value("${hospital.SourceSysCode}")
    private String sourceSysCode;
    @Value("${hospital.TargetSysCode}")
    private String targetSysCode;
    @Value("${hospital.url}")
    private String serverUrl;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;

    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;
    @Autowired
    private PatientMappingDao patientMappingDao;
    @Autowired
    private WlyyChargeDictDao wlyyChargeDictDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private DoctorZsInfoDao doctorZsInfoDao;
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private PrescriptionEmrDao prescriptionEmrDao;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private WlyyHttpLogDao wlyyHttpLogDao;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;

    private static String entranceUrl="http://172.16.100.240:10023/mqsdk/";
//    private static String entranceUrl="http://localhost:10023/mqsdk/";

    /**
     * 获取本地示例返参
     *
     * @param fid 服务id
     * @return
     * @throws Exception
     */
    public String getJosnFileResullt(String fid) throws Exception {
        String contentStr = null;
        Resource resource = new ClassPathResource("mqConfig/mqdata/" + fid + ".json");
        if (resource.exists()) {
            InputStream is = resource.getInputStream();
            contentStr = new BufferedReader(new InputStreamReader(is, "utf-8"))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
//            contentStr =  replaceSpecialStr(contentStr);
        } else {
            throw new Exception("文件不存在");
        }
        return contentStr;
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符等
     *
     * @param str
     * @return
     */
    public static String replaceSpecialStr(String str) {
        String repl = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            repl = m.replaceAll("");
        }
        return repl;
    }

    /**
     * 查询门诊余额
     *
     * @param cardNo   卡号，必传参数
     * @param demoFlag 是否使用demo.不请求接口。true代表获取本地数据，false代表获取his数据
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject qutpatientBalance(String cardNo, boolean demoFlag) throws Exception {
        String resp = "";
        String fid = BS15017;
        logger.info("EntranceService " + fid + " cardNo :" + cardNo);


        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            //先调用银医通获取下载余额到his，再查询his中卡余额
            net.sf.json.JSONObject jsonObject = callYYTServerService(cardNo);
            if (null != jsonObject && "1".equals(jsonObject.get("code").toString())) {
                JSONObject msg = new JSONObject();
                msg.put("endNum", "20000");
                msg.put("Msg", new net.sf.json.JSONArray());
                JSONObject query = new JSONObject();
                query.put("@compy", "=");
                query.put("@item", "CARD_NO");
                query.put("@splice", "and");
                query.put("@value", cardNo);
                msg.put("query", query);
                msg.put("startNum", 1);
                List<String> stringList = new ArrayList<>();
                stringList.add(cardNo);
                //获取消息
                resp = MqSdkUtil.putReqAndGetResp(msg.toString(), fid, "1", stringList);
                logger.info("获取消息xml resp===" + resp);
                //解析
                resp = MqSdkUtil.xml2jsonObject(resp);
                logger.info("获取消息json resp===" + resp);
            } else {
                return jsonObject;
            }

        }
        return ConvertUtil.convertObjectEnvelopByString(resp);
    }

    /**
     * 门诊就诊卡列表
     *
     * @param SOCIAL_NO 身份证号
     * @param CARD_NO   就诊卡号
     * @return
     * @throws Exception
     */
    public JSONArray BS15018(String SOCIAL_NO, String CARD_NO, boolean demoFlag) throws Exception {
        String fid = BS15018;
        logger.info("EntranceService " + fid + " SOCIAL_NO :" + SOCIAL_NO + "CARD_NO:" + CARD_NO);

        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            if (StringUtils.isNotBlank(SOCIAL_NO)) {
                sbs.append("<query compy=\"=\" item=\"SOCIAL_NO\" splice=\"and\" value=\"'" + SOCIAL_NO + "'\"/>");
            }
            if (StringUtils.isNotBlank(CARD_NO)) {
                sbs.append("<query compy=\"=\" item=\"card_no\" splice=\"and\" value=\"'" + CARD_NO + "'\"/>");
            }
            sbs.append("<query compy=\"=\" item=\"CARD_STAT\" splice=\"and\" value=\"'激活'\"/>");
            //查询信息结束
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");

            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }

        //剔除非激活的卡
        JSONArray res = ConvertUtil.convertListEnvelopByString(resp);
        if (res != null && res.size() > 0) {
            Iterator it = res.iterator();
            if (it.hasNext()) {
                net.sf.json.JSONObject rs = (net.sf.json.JSONObject) it.next();
                String stat = rs.getString("CARD_STAT");
                if (!"激活".equals(stat)) {
                    it.remove();
                }
            }
        }
        return res;
    }

    /**
     * 处方（处方主体+诊断+药品）适配
     *
     * @param obj 接口返回参数
     * @return
     * @throws Exception
     */
    public List<WlyyPrescriptionVO> convertWlyyPrescriptionVOInBodyRow(String obj) throws Exception {
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(obj);
        if (null != jsonObject && "1".equals(jsonObject.get("code").toString())) {
            JSONArray jsonObjectMgsInfo = (JSONArray) jsonObject.get("MsgInfo");
            if (null != jsonObjectMgsInfo) {
                //处方实体
                WlyyPrescriptionVO wlyyPrescriptionVO = new WlyyPrescriptionVO();
                //用于存放已解析的处方
                Map<String, WlyyPrescriptionVO> wlyyPrescriptionVOMap = new HashMap<>();
                //用于存放已解析的诊断
                Map<String, String> wlyyPrescriptionDiagnosisVOHashMap = new HashMap<>();
                //诊断list
                List<WlyyPrescriptionDiagnosisVO> wlyyPrescriptionDiagnosisVOS = new ArrayList<>();
                //药品实体list
                List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
                //药品
                WlyyPrescriptionInfoVO wlyyPrescriptionInfoVO;
                for (Object object : jsonObjectMgsInfo) {
                    net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) object;
                    jsonObjectBody = (net.sf.json.JSONObject) jsonObjectBody.get("body");
                    if (null != jsonObjectBody) {
                        jsonObjectBody = (net.sf.json.JSONObject) jsonObjectBody.get("row");
                        if (null != jsonObjectBody) {
                            //诊断
                            WlyyPrescriptionDiagnosisVO wlyyPrescriptionDiagnosisVO;
                            //是否为药品：0否，1是
                            String ypFlag = null != jsonObjectBody.get("YP_FLAG") ? jsonObjectBody.get("YP_FLAG").toString() : "";
                            Set<String> stringSet = new HashSet<>();
                            if ("1".equals(ypFlag)) {
                                //处方号
                                String realOrder = null != jsonObjectBody.get("real_order") ? jsonObjectBody.get("real_order").toString() : "";
                                if (!(null != stringSet && stringSet.contains(realOrder))) {
                                    //初始化处方
                                    wlyyPrescriptionVO = initWlyyPrescriptionVo(new WlyyPrescriptionVO(), jsonObjectBody, realOrder);
                                    wlyyPrescriptionVO.setHospital("350211A1002");
                                    wlyyPrescriptionVO.setHospitalName("厦门大学附属中山医院");
                                    String doasgeTime = null != jsonObjectBody.get("DISP_DATE") ? jsonObjectBody.get("DISP_DATE").toString() : "";
                                    wlyyPrescriptionVO.setDosageTime(DateUtil.strToDate((doasgeTime + " 00:00:00"), DateUtil.YYYY_MM_DD_HH_MM_SS));
                                    wlyyPrescriptionVOMap.put(realOrder, wlyyPrescriptionVO);
                                    //主诊断 毒蛇咬伤&T63.001
                                    String[] icdName = jsonObjectBody.get("icd_name").toString().split("&");
                                    String[] diagTwo = jsonObjectBody.get("diag_two").toString().toString().split("&");
                                    String[] diagThree = jsonObjectBody.get("diag_three").toString().toString().split("&");
                                    String[] diagFour = jsonObjectBody.get("diag_four").toString().toString().split("&");
                                    String[] diagFive = jsonObjectBody.get("diag_five").toString().toString().split("&");

                                    if (null != icdName && icdName.length > 1 && !wlyyPrescriptionDiagnosisVOHashMap.containsKey(icdName[1].toString())) {
                                        //主诊断
                                        wlyyPrescriptionDiagnosisVO = initWlyyPrescriptionDiagnosisVO(realOrder, icdName[0].toString(), icdName[1].toString(), 1);
                                        wlyyPrescriptionDiagnosisVOS.add(wlyyPrescriptionDiagnosisVO);
                                        wlyyPrescriptionDiagnosisVOHashMap.put(icdName[1].toString(), icdName[0].toString());
                                    }
                                    if (null != diagTwo && diagTwo.length > 1 && !wlyyPrescriptionDiagnosisVOHashMap.containsKey(diagTwo[1].toString())) {
                                        //第二诊断
                                        wlyyPrescriptionDiagnosisVO = initWlyyPrescriptionDiagnosisVO(realOrder, diagTwo[0].toString(), diagTwo[1].toString(), 2);
                                        wlyyPrescriptionDiagnosisVOS.add(wlyyPrescriptionDiagnosisVO);
                                        wlyyPrescriptionDiagnosisVOHashMap.put(icdName[1].toString(), icdName[0].toString());
                                    }
                                    if (null != diagThree && diagThree.length > 1 && !wlyyPrescriptionDiagnosisVOHashMap.containsKey(diagThree[1].toString())) {
                                        //第三诊断
                                        wlyyPrescriptionDiagnosisVO = initWlyyPrescriptionDiagnosisVO(realOrder, diagThree[0].toString(), diagThree[1].toString(), 2);
                                        wlyyPrescriptionDiagnosisVOS.add(wlyyPrescriptionDiagnosisVO);
                                    }
                                    if (null != diagFour && diagFour.length > 1 && !wlyyPrescriptionDiagnosisVOHashMap.containsKey(diagFour[1].toString())) {
                                        //第四诊断
                                        wlyyPrescriptionDiagnosisVO = initWlyyPrescriptionDiagnosisVO(realOrder, diagFour[0].toString(), diagFour[1].toString(), 2);
                                        wlyyPrescriptionDiagnosisVOS.add(wlyyPrescriptionDiagnosisVO);
                                        wlyyPrescriptionDiagnosisVOHashMap.put(icdName[1].toString(), icdName[0].toString());
                                    }
                                    if (null != diagFive && diagFive.length > 1 && !wlyyPrescriptionDiagnosisVOHashMap.containsKey(diagFive[1].toString())) {
                                        //第五诊断
                                        wlyyPrescriptionDiagnosisVO = initWlyyPrescriptionDiagnosisVO(realOrder, diagFive[0].toString(), diagFive[1].toString(), 2);
                                        wlyyPrescriptionDiagnosisVOS.add(wlyyPrescriptionDiagnosisVO);
                                        wlyyPrescriptionDiagnosisVOHashMap.put(icdName[1].toString(), icdName[0].toString());
                                    }
                                    stringSet.add(realOrder);
                                } else {
                                    wlyyPrescriptionVO = wlyyPrescriptionVOMap.get(realOrder);
                                }

                                //封装药品
                                wlyyPrescriptionInfoVO = new WlyyPrescriptionInfoVO();
                                wlyyPrescriptionInfoVO.setPrescriptionId(realOrder);
                                wlyyPrescriptionInfoVO.setDrugNo(null != jsonObjectBody.get("DRUG_CODE") ? jsonObjectBody.get("DRUG_CODE").toString() : "");
                                wlyyPrescriptionInfoVO.setDrugName(null != jsonObjectBody.get("DRUG_NAME") ? jsonObjectBody.get("DRUG_NAME").toString() : "");
                                wlyyPrescriptionInfoVO.setDispDeposite(null != jsonObjectBody.get("DISP_DEPOSITE") ? jsonObjectBody.get("DISP_DEPOSITE").toString() : "");
                                wlyyPrescriptionInfoVO.setDosage(null != jsonObjectBody.get("YPYL00") ? jsonObjectBody.get("YPYL00").toString() : "");
                                wlyyPrescriptionInfoVO.setQuantity(null != jsonObjectBody.get("DRUG_QTY") ? jsonObjectBody.get("DRUG_QTY").toString() : "");
                                wlyyPrescriptionInfoVO.setUnit(null != jsonObjectBody.get("UNIT") ? jsonObjectBody.get("UNIT").toString() : "");
                                wlyyPrescriptionInfoVO.setUnitName(null != jsonObjectBody.get("DCYYDW") ? jsonObjectBody.get("DCYYDW").toString() : "");
                                wlyyPrescriptionInfoVO.setUsageName(null != jsonObjectBody.get("YPPL00") ? jsonObjectBody.get("YPPL00").toString() : "");
                                wlyyPrescriptionInfoVO.setSupplyName(null != jsonObjectBody.get("YPYF00") ? jsonObjectBody.get("YPYF00").toString() : "");
                                wlyyPrescriptionInfoVO.setUsageCode(null != jsonObjectBody.get("YPPLCODE") ? jsonObjectBody.get("YPPLCODE").toString() : "");
                                wlyyPrescriptionInfoVO.setSupplyCode(null != jsonObjectBody.get("YPYFCODE") ? jsonObjectBody.get("YPYFCODE").toString() : "");
                                wlyyPrescriptionInfoVO.setDays(null != jsonObjectBody.get("drug_win") ? jsonObjectBody.get("drug_win").toString() : "");
                                wlyyPrescriptionInfoVO.setFrequency(null != jsonObjectBody.get("frequency") ? jsonObjectBody.get("frequency").toString() : "");
                                wlyyPrescriptionInfoVO.setGroupNo(null != jsonObjectBody.get("DISP_DEPOSITE") ? jsonObjectBody.get("DISP_DEPOSITE").toString() : "");
                                //规格
                                wlyyPrescriptionInfoVO.setSpecification(null != jsonObjectBody.get("DRUG_SPEC") ? jsonObjectBody.get("DRUG_SPEC").toString() : "");
                                wlyyPrescriptionInfoVO.setSerial(null!=jsonObjectBody.get("serial")? jsonObjectBody.get("serial").toString() : "");
                                wlyyPrescriptionInfoVO.setDel(1);
                                wlyyPrescriptionInfoVOS.add(wlyyPrescriptionInfoVO);
                            }
                        }
                    }
                    wlyyPrescriptionVO.setDiagnosisVOs(wlyyPrescriptionDiagnosisVOS);
                    wlyyPrescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
                }
                Collection<WlyyPrescriptionVO> wlyyPrescriptionVOCollection = wlyyPrescriptionVOMap.values();
                return new ArrayList<WlyyPrescriptionVO>(wlyyPrescriptionVOCollection);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 门诊处方信息（所有处方）根据处方信息封装到实体中
     *
     * @param REGISTER_SN 流水号，选择输入参数，该参数输入时获取该病人的此次就诊的所有处方
     * @param realOrder   处方号 ，选择输入参数，该参数输入时获取到处方号为realOrder的处方
     * @param PAT_NO      病人id ，必传参数，只传病人id时，获取该病人的所有处方
     * @param ADM_NO      就诊唯一号 ，选择输入参数，该参数输入时获取该病人的此次就诊的所有处方
     * @param demoFlag    是否获取demo数据
     * @return
     * @throws Exception
     */
    public List<WlyyPrescriptionVO> BS16017(String REGISTER_SN, String realOrder, String PAT_NO, String ADM_NO, boolean demoFlag) throws Exception {
        String fid = BS16017;
        String resp = "";
        logger.info("BS16017： REGISTER_SN:" + REGISTER_SN + " realOrder" + realOrder + " PAT_NO:" + PAT_NO + " ADM_NO:" + ADM_NO);

        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            if (StringUtils.isNotBlank(REGISTER_SN)) {
                sbs.append("<query compy=\"=\" item=\"REGISTER_SN\" splice=\"and\" value=\"'" + REGISTER_SN + "'\"/>");
            }
            if (StringUtils.isNotBlank(realOrder)) {
                sbs.append("<query compy=\"=\" item=\"DISP_NO\" splice=\"and\" value=\"'" + realOrder + "'\"/>");
            }
            if (StringUtils.isNotBlank(PAT_NO)) {
                sbs.append("<query compy=\"=\" item=\"PAT_NO\" splice=\"and\" value=\"'" + PAT_NO + "'\"/>");
            }
            if (StringUtils.isNotBlank(ADM_NO)) {
                sbs.append("<query compy=\"=\" item=\"ADM_NO\" splice=\"and\" value=\"'" + ADM_NO + "'\"/>");
            }
            //查询信息结束
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
//            logger.info("resp "+resp);

            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return convertWlyyPrescriptionVOInBodyRow(resp);
    }

    /**
     * 初始化处方接口
     *
     * @param wlyyPrescriptionVO
     * @param jsonObjectBody
     * @param realOrder
     * @return
     */
    public WlyyPrescriptionVO initWlyyPrescriptionVo(WlyyPrescriptionVO wlyyPrescriptionVO, net.sf.json.JSONObject jsonObjectBody, String realOrder) {
        wlyyPrescriptionVO.setAdmNo(null != jsonObjectBody.get("ADM_NO") ? jsonObjectBody.get("ADM_NO").toString() : "");
        wlyyPrescriptionVO.setRealOrder(realOrder);
        wlyyPrescriptionVO.setSerialNo(null != jsonObjectBody.get("REGISTER_SN") ? jsonObjectBody.get("REGISTER_SN").toString() : "");
        wlyyPrescriptionVO.setType(1);
        String patNo = null != jsonObjectBody.get("PAT_NO") ? jsonObjectBody.get("PAT_NO").toString() : "";
        String patientName = null != jsonObjectBody.get("UOM") ? jsonObjectBody.get("UOM").toString() : "";
        PatientMappingDO patientMappingDo = new PatientMappingDO();
        if (StringUtils.isNotBlank(patNo)) {
            patientMappingDo = patientMappingDao.findByMappingCodeAndSource(patNo.trim(), "1");
            patNo = null == patientMappingDo ? null : patientMappingDo.getPatient();
            patientName = null == patientMappingDo ? null : patientMappingDo.getPatientName();
        }

        wlyyPrescriptionVO.setPatientCode(patNo);
        wlyyPrescriptionVO.setPatientName(patientName);
        wlyyPrescriptionVO.setIdcard(null == patientMappingDo ? null : patientMappingDo.getIdcard());
        wlyyPrescriptionVO.setSsc("");
        wlyyPrescriptionVO.setHisDoctorCode(null != jsonObjectBody.get("PRESC_DOC") ? jsonObjectBody.get("PRESC_DOC").toString() : "");
        wlyyPrescriptionVO.setHisDeptCode(null != jsonObjectBody.get("PRESC_SPEC") ? jsonObjectBody.get("PRESC_SPEC").toString() : "");
        //中山医院处方状态
        String status = null != jsonObjectBody.get("PAY_MARK") ? jsonObjectBody.get("PAY_MARK").toString() : "";
        /**互联网医院处方状态字典：
         续方取消：-3 支付过期取消，-2 患者自己取消 ，-1 医生取消
         候诊中：0 候诊中
         就诊中：10 诊断中，11 药师审核失败 / 调整中，12  药师审核完成，13  开方失败/调整中
         开方成功：20 诊断完成/开方成功/待支付，21 支付失败/待支付中
         待取药：30 支付成功/等待配药，31 配药成功/等待取药，32 配送中
         已完成：100 已完成
         中山医院处方状态字典：0-正常已收费 1-退费 5-正常未收费 a-皮试后用药 c-作废处方
         */
        //互联网医院处方状态
        Integer hlwyyStatus = 10;
        switch (status) {
            case "0":
                hlwyyStatus = 30;
                break;
            case "1":
                hlwyyStatus = 13;
                break;
            case "5":
                hlwyyStatus = 20;
                break;
            case "a":
                hlwyyStatus = 100;
                break;
            case "c":
                hlwyyStatus = 13;
                break;
        }
        //发药时间
        String dispDate = null != jsonObjectBody.get("DISP_DATE") ? jsonObjectBody.get("DISP_DATE").toString() : "";

        if (StringUtils.isNotBlank(dispDate)) {
            //根据处方号获取处方
            WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findByRealOrder(realOrder);
            if (null != wlyyPrescriptionDO && 1 == wlyyPrescriptionDO.getDispensaryType()) {
                //自取
                hlwyyStatus = 31;
            } else {
                //快递配送
                hlwyyStatus = 32;
            }
            //发药医生编码-中山医院
            String dispUser = null != jsonObjectBody.get("DISP_USER") ? jsonObjectBody.get("DISP_USER").toString() : "";
            wlyyPrescriptionVO.setDispDate(DateUtil.strToDate(dispDate));
            //转换为本地医生编码
            List<DoctorMappingDO> mappingDOs = doctorMappingDao.findByOrgCodeAndMappingCode(orgCode, dispUser);
            String dispUserName = "";
            if (mappingDOs != null && mappingDOs.size() > 0) {
                dispUser = mappingDOs.get(0).getDoctor();
                dispUserName = mappingDOs.get(0).getDoctorName();
            }
            wlyyPrescriptionVO.setDispUser(dispUser);
            wlyyPrescriptionVO.setDispUserName(dispUserName);
        }

        wlyyPrescriptionVO.setStatus(hlwyyStatus);
        return wlyyPrescriptionVO;
    }

    /**
     * 初始化处方诊断信息
     *
     * @param icdCode
     * @param icdName
     * @param type
     * @return
     * @throws Exception
     */
    public WlyyPrescriptionDiagnosisVO initWlyyPrescriptionDiagnosisVO(String realOrder, String icdName, String icdCode, Integer type) throws Exception {
        WlyyPrescriptionDiagnosisVO wlyyPrescriptionDiagnosisVO = new WlyyPrescriptionDiagnosisVO();
        wlyyPrescriptionDiagnosisVO.setPrescriptionId(realOrder);
        wlyyPrescriptionDiagnosisVO.setCode(icdCode);
        wlyyPrescriptionDiagnosisVO.setName(icdName);
        wlyyPrescriptionDiagnosisVO.setCreateTime(new Date());
        wlyyPrescriptionDiagnosisVO.setType(type);

        return wlyyPrescriptionDiagnosisVO;
    }

    /**
     * 患者门诊就诊记录
     * 使用时间查询的话，很可能会超时。时间没有索引，所以超时时间需要加长
     *
     * @param PAT_NO    居民唯一号 一个居民在该医院只有一个号，该接口必须输入的参数
     * @param conNo     就诊次数，使用居民唯一号+就诊次数获取唯一一条就诊记录
     *                  // *  @param admNo 就诊唯一号 每一次就诊都有一个唯一号：居民号+就诊次数，查询确定的一条就诊记录时需要传，否则传null
     *                  // *  @param registerSn 挂号流水号，查询确定的一条就诊记录时需要传，否则传null
     * @param startTime 开始时间 （查询一段时间内就诊记录开始时间，查询就诊记录列表时需要传，否则传null）
     * @param endTime   结束时间 （查询一段时间内就诊记录结束时间，查询就诊记录列表时需要传，否则传null）
     * @return
     * @throws Exception
     */
    public List<WlyyOutpatientVO> BS30025(String PAT_NO, String conNo, String startTime, String endTime, boolean demoFlag ,String ksdm) throws Exception {
        System.out.println("ksdm="+ksdm);
        String fid = BS30025;
        logger.info("EntranceService " + fid + " PAT_NO :" + PAT_NO + " conNo:" + conNo + " startTime:" + startTime + " endTime:" + endTime);

        String resp = "";
        String orgCode = "350211A1002";
        String orgName = "厦门大学附属中山医院";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><onceFlag>1</onceFlag><startNum>1</startNum><endNum>50000</endNum><Msg/>");
            if (StringUtils.isNotBlank(PAT_NO)) {
                sbs.append("<query compy=\"=\" item=\"PAT_NO\" splice=\"and\" value=\"'" + PAT_NO + "'\"/>");
            }
            if (StringUtils.isNotBlank(conNo)) {
                sbs.append("<query compy=\"=\" item=\"CON_NO\" splice=\"and\" value=\"'" + conNo + "'\"/>");
            }
            if (StringUtils.isNotBlank(startTime)) {
                sbs.append("<query compy=\"&gt;=\" item=\"CON_DATE\" splice=\"and\" value=\"'" + startTime + "'\"/>");
            }
            if (StringUtils.isNotBlank(endTime)) {
                sbs.append("<query compy=\"&lt;\" item=\"CON_DATE\" splice=\"and\" value=\"'" + endTime + "'\"/>");
            }
            if (StringUtils.isNotBlank(ksdm)) {
                sbs.append("<query compy=\"=\" item=\"ADM_SPEC\" splice=\"and\" value=\"'" + ksdm + "'\"/>");
            }
            sbs.append("<query compy=\"\" item=\"icd_name\" splice=\"and\" value=\"is not null\"/>");
            sbs.append("<order item=\"CON_DATE\" sort=\"desc\"/>");
            //查询信息结束
            sbs.append("</MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            logger.info("resp===" + resp);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        JSONArray jsonArray = ConvertUtil.convertListEnvelopInRow(resp);
        if (null == jsonArray) {
            return null;        }
        List<WlyyOutpatientVO> wlyyOutpatientVOS = new ArrayList<>();
        WlyyOutpatientVO wlyyOutpatientVO;
        for (Object object : jsonArray) {
            net.sf.json.JSONObject jsonObjectMgsInfo = (net.sf.json.JSONObject) object;
            if (null != jsonObjectMgsInfo) {
                wlyyOutpatientVO = new WlyyOutpatientVO();
                //中山医院固定入参
                wlyyOutpatientVO.setHospital(orgCode);
                wlyyOutpatientVO.setHospitalName(orgName);
                wlyyOutpatientVO.setWinNo("6");
                wlyyOutpatientVO.setAdmNo(null == jsonObjectMgsInfo.get("ADM_NO") ? "" : jsonObjectMgsInfo.get("ADM_NO") + "");
                wlyyOutpatientVO.setRegisterNo(null == jsonObjectMgsInfo.get("REGISTER_SN") ? "" : jsonObjectMgsInfo.get("REGISTER_SN") + "");
                wlyyOutpatientVO.setDept(null == jsonObjectMgsInfo.get("ADM_SPEC") ? "" : jsonObjectMgsInfo.get("ADM_SPEC") + "");
                wlyyOutpatientVO.setDeptName(null == jsonObjectMgsInfo.get("ADM_SPEC_NAME") ? "" : jsonObjectMgsInfo.get("ADM_SPEC_NAME") + "");
                String patNo = null != jsonObjectMgsInfo.get("PAT_NO") ? jsonObjectMgsInfo.get("PAT_NO").toString() : "";
                String patientName = null != jsonObjectMgsInfo.get("PAT_NAME") ? jsonObjectMgsInfo.get("PAT_NAME").toString() : "";
                PatientMappingDO patientMappingDo = new PatientMappingDO();
                if (StringUtils.isNotBlank(patNo)) {
                    patientMappingDo = patientMappingDao.findByMappingCodeAndSource(patNo.trim(), "1");
                    patNo = null == patientMappingDo ? null : patientMappingDo.getPatient();
                    patientName = null == patientMappingDo ? null : patientMappingDo.getPatientName();
                }
                wlyyOutpatientVO.setPatient(patNo);
                wlyyOutpatientVO.setPatientName(patientName);
                wlyyOutpatientVO.setConNo(null == jsonObjectMgsInfo.get("CON_NO") ? "" : jsonObjectMgsInfo.get("CON_NO") + "");
                String doctor = null == jsonObjectMgsInfo.get("CON_DOC") ? "" : jsonObjectMgsInfo.get("CON_DOC") + "";

                //转化医生
                String mappingCode = doctor.trim();
                String doctorCode = "";
                if (StringUtils.isNotBlank(mappingCode)) {
                    List<DoctorMappingDO> mappingDOs = doctorMappingDao.findByOrgCodeAndMappingCode(orgCode, mappingCode);
                    if (mappingDOs != null && mappingDOs.size() > 0) {
                        doctorCode = mappingDOs.get(0).getDoctor();
                    }
                }
                wlyyOutpatientVO.setDoctor(doctorCode);
                wlyyOutpatientVO.setDoctorName(null == jsonObjectMgsInfo.get("CON_DOC_NAME") ? "" : jsonObjectMgsInfo.get("CON_DOC_NAME") + "");

//                wlyyOutpatientVO.setIdcard(null == jsonObjectMgsInfo.get("social_no") ? "" : jsonObjectMgsInfo.get("social_no") + "");
                wlyyOutpatientVO.setMjz(null == jsonObjectMgsInfo.get("MJZ") ? "" : jsonObjectMgsInfo.get("MJZ") + "");

                //主诊断 毒蛇咬伤&T63.001
                String[] icdName = jsonObjectMgsInfo.get("icd_name").toString().split("&");
                String[] diagTwo = jsonObjectMgsInfo.get("diag_two").toString().split("&");
                String[] diagThree = jsonObjectMgsInfo.get("diag_three").toString().split("&");
                String[] diagFour = jsonObjectMgsInfo.get("diag_four").toString().split("&");
                String[] diagFive = jsonObjectMgsInfo.get("diag_five").toString().split("&");

                String icdcodes = "";
                String icdNames = "";
                if (icdName.length > 1) {
                    icdcodes += icdName[1];
                    icdNames += icdName[0];
                }
                if (diagTwo.length > 1) {
                    icdcodes += "," + diagTwo[1];
                    icdNames += "," + diagTwo[0];
                }
                if (diagThree.length > 1) {
                    icdcodes += "," + diagThree[1];
                    icdNames += "," + diagThree[0];
                }
                if (diagFour.length > 1) {
                    icdcodes += "," + diagFour[1];
                    icdNames += "," + diagFour[0];
                }
                if (diagFive.length > 1) {
                    icdcodes += "," + diagFive[1];
                    icdNames += "," + diagFive[0];
                }

//                String icds = null == jsonObjectMgsInfo.get("icd_name") ? "" : jsonObjectMgsInfo.get("icd_name") + "";
//                String[] icdcodeAndName = icds.split("&");
//                wlyyOutpatientVO.setIcd10(icdcodeAndName.length > 1 ? icdcodeAndName[1].toString() : "");
//                wlyyOutpatientVO.setIcd10Name(icdcodeAndName.length > 0 ? icdcodeAndName[0].toString() : "");
                wlyyOutpatientVO.setIcd10(icdcodes);
                wlyyOutpatientVO.setIcd10Name(icdNames);

                String admDate = null == jsonObjectMgsInfo.get("ADM_DAT") ? "" : jsonObjectMgsInfo.get("ADM_DAT") + "";
                String conDate = null == jsonObjectMgsInfo.get("CON_DATE") ? "" : jsonObjectMgsInfo.get("CON_DATE") + "";
                wlyyOutpatientVO.setAdmDate(DateUtil.strToDate(admDate, DateUtil.YYYY_MM_DD_HH_MM_SS_));
                wlyyOutpatientVO.setConDate(DateUtil.strToDate(conDate, DateUtil.YYYY_MM_DD_HH_MM_SS_));
                wlyyOutpatientVOS.add(wlyyOutpatientVO);

            }
        }
        return wlyyOutpatientVOS;
    }

    /**
     * 医院药品字典(所有字典一次返回)
     *
     * @return
     * @throws Exception
     */
    public String MS30001() throws Exception {
        String fid = MS30001;
        StringBuffer sbs = new StringBuffer();
        //AccessControl ：用户、密码、服务id
        sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
        //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
        sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
        //查询信息拼接
        sbs.append("<MsgInfo><endNum>1000</endNum><Msg></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
        String resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
        resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        logger.info(fid + " resp:" + resp);
        return resp;
    }

    /**
     * 医院药品字典(所有字典一次返回)
     *
     * @param charge_code  药品收费码 非必传
     * @param py_code      药品拼音码 非必传
     * @param stock_amount 库存 非必传
     * @param win_no       分部 必传 6总部7金榜8夏禾
     * @param visible_flag 是否可用 必传 可用标志(0可用1不可用)
     * @return
     * @throws Exception
     */
    public JSONArray MS53001(String charge_code, String py_code, String stock_amount, String win_no, String visible_flag, String groupNo, boolean demoFlag) throws Exception {
        String fid = "MS53001";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>10</endNum><Msg/>");
            if (StringUtils.isNotBlank(charge_code)) {
                sbs.append("<query compy=\"=\" item=\"charge_code\" splice=\"and\" value=\"'" + charge_code + "'\"/>");
            }
            if (StringUtils.isNotBlank(py_code)) {
                py_code = py_code.toUpperCase();
                logger.info("py_code=" + py_code);
                sbs.append("<query compy=\"like\" item=\"py_code\" splice=\"and\" value=\"'%" + py_code + "%'\"/>");
            }
            if (StringUtils.isNotBlank(stock_amount)) {
                sbs.append("<query compy=\"&gt;\" item=\"stock_amount\" splice=\"and\" value=\"'" + stock_amount + "'\"/>");
            }
            if (StringUtils.isNotBlank(win_no)) {
                sbs.append("<query compy=\"=\" item=\"win_no\" splice=\"and\" value=\"'" + win_no + "'\"/>");
            }
            if (StringUtils.isNotBlank(groupNo)) {
                String groups[] = groupNo.split(",");
                String inSql = "";
                for (String group : groups) {
                    inSql += "'" + group + "'" + ",";
                }
                inSql = inSql.substring(0, inSql.length() - 1);
                sbs.append("<query compy=\"in\" item=\"group_no\" splice=\"and\" value=\"(" + inSql + ")\"/>");
            }
            if (StringUtils.isNotBlank(visible_flag)) {
                sbs.append("<query compy=\"=\" item=\"visible_flag\" splice=\"and\" value=\"'" + visible_flag + "'\"/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            //logger.info(fid+" resp:"+resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 门诊给药方式
     *
     * @param supply_code 药品编码，非必传参数
     * @param py_code     药品拼音码，非必传参数
     * @return
     * @throws Exception
     */
    public JSONArray BS10110(String supply_code, String py_code, boolean demoFlag) throws Exception {
        String fid = BS10110;
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            if (StringUtils.isNotBlank(supply_code)) {
                sbs.append("<query compy=\"=\" item=\"supply_code\" splice=\"and\" value=\"'" + supply_code + "'\"/>");
            }
            if (StringUtils.isNotBlank(py_code)) {
                py_code = py_code.toUpperCase();
//                logger.info("py_code="+py_code);
                sbs.append("<query compy=\"like\" item=\"py_code\" splice=\"and\" value=\"'%" + py_code + "%'\"/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
//            logger.info(fid+" resp:"+resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    /**
     * 线上挂号
     *
     * @param card_no     卡号 必传
     * @param doctor      医生工号 必传
     * @param dept        科室编码 必传
     * @param charge_type 号别，现已和医生绑定，一个医生一个号别可随意传
     * @param win_no      分部号 必传
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject BS10111(String card_no, String doctor, String dept, String charge_type, String win_no, boolean demoFlag) throws Exception {
        String fid = BS10111;
        logger.info("EntranceService " + fid + " card_no :" + card_no + " doctor:" + doctor + " dept:" + dept + " charge_type:" + charge_type + " win_no:" + win_no);

        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
            sbs.append("<resquest card_no=\"" + card_no + "\" doctor=\"" + doctor + "\" dept=\"" + dept + "\" charge_type=\"" + charge_type + "\"   win_no=\"" + win_no + "\" >");
            sbs.append("</resquest></root>]]></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            //超时等待时间150s
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid + " resp:" + resp);
        }
        return ConvertUtil.convertListEnvelopInRequest(resp);
    }


    /**
     * 线上退号
     *
     * @param card_no     卡号 必传
     * @param doctor      医生工号 必传
     * @param dept        科室编码 必传
     * @param serial_no  挂号流水号
     * @param win_no      分部号 必传
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject BS10138(String card_no, String doctor, String dept, String serial_no, String win_no, boolean demoFlag) throws Exception {
        String fid = BS10138;
        logger.info("EntranceService " + fid + " card_no :" + card_no + " doctor:" + doctor + " dept:" + dept + " serial_no:" + serial_no + " win_no:" + win_no);

        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg><as_xml><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
            sbs.append("<resquest card_no=\"" + card_no + "\" doctor=\"" + doctor + "\" dept=\"" + dept + "\" serial_no=\"" + serial_no + "\"   win_no=\"" + win_no + "\" >");
            sbs.append("</resquest></root>]]></as_xml></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            //超时等待时间150s
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid + " resp:" + resp);
        }
        return ConvertUtil.convertListEnvelopInRequest(resp);
    }


    public net.sf.json.JSONObject BS15054(String pid, String realorder,  boolean demoFlag) throws Exception {
        String fid = BS15054;
        logger.info("EntranceService " + fid +pid+realorder);

        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg><as_xml><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
            sbs.append("<resquest pid=\"" + pid + "\" realorder=\"" + realorder + "\" >");
            sbs.append("</resquest></root>]]></as_xml></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            //超时等待时间150s
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid + " resp:" + resp);
        }
        return ConvertUtil.convertListEnvelopInRequest(resp);
    }


    /**
     * 线上处方
     *
     * @param jsonData 处方实体数组，实体注释见WlyyHisPrescriptionVO
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject BS10112(String jsonData, boolean demoFlag) throws Exception {
        String fid = BS10112;
        logger.info("EntranceService" + fid + " jsonData :" + jsonData);
        ObjectMapper objectMapper = new ObjectMapper();
        List<WlyyHisPrescriptionVO> patientSubscribeJkedus = objectMapper.readValue(jsonData, new TypeReference<List<WlyyHisPrescriptionVO>>() {
        });
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
            for (WlyyHisPrescriptionVO vo : patientSubscribeJkedus) {
                //必输字段
                sbs.append("<resquest card_no=\"" + vo.getCardNo() + "\" doctor=\"" + vo.getDoctor() + "\" dept=\"" + vo.getDept() + "\" win_no=\"" + vo.getWinNo() + "\" charge_flag=\"" + vo.getChargeFlag() + "\" ");
                if (StringUtils.isNotBlank(vo.getRealOrder())) {
                    sbs.append(" real_order=\"" + vo.getRealOrder() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getChargeCode())) {
                    sbs.append(" charge_code=\"" + vo.getChargeCode() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getIcdCode())) {
                    sbs.append(" icd_code=\"" + vo.getIcdCode() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getSerial())) {
                    sbs.append(" serial=\"" + vo.getSerial() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getSerialNo())) {
                    sbs.append(" serial_no=\"" + vo.getSerialNo() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getQuantity())) {
                    sbs.append(" quantity=\"" + vo.getQuantity() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getGroupNo())) {
                    sbs.append(" group_no=\"" + vo.getGroupNo() + "\"");
                }
                //选填字段
                if (StringUtils.isNotBlank(vo.getDiagTwo())) {
                    sbs.append(" diag_two=\"" + vo.getDiagTwo() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getDiagThree())) {
                    sbs.append(" diag_three=\"" + vo.getDiagThree() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getDiagFour())) {
                    sbs.append(" diag_four=\"" + vo.getDiagFour() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getDiagFive())) {
                    sbs.append(" diag_five=\"" + vo.getDiagFive() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getDosage())) {
                    sbs.append(" dosage=\"" + vo.getDosage() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getUnit())) {
                    sbs.append(" unit=\"" + vo.getUnit() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getUsage())) {
                    sbs.append(" usage=\"" + vo.getUsage() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getSupplyCode())) {
                    sbs.append(" supply_code=\"" + vo.getSupplyCode() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getDays())) {
                    sbs.append(" days=\"" + vo.getDays() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getFrequency())) {
                    sbs.append(" frequency=\"" + vo.getFrequency() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getComm())) {
                    sbs.append(" comm=\"" + vo.getComm() + "\"");
                }
                //检查检验
                /**
                 *  name;//(检查方法)',
                 *  information;//病史与体征',
                 *  checkEquip;//类别',
                 *  checkPart;//部位',
                 *  adresult;//辅助检查治疗',
                 *  goal;//检查目的',
                 *  opview;//手术所见-病理申请单必填',
                 *  specimenName;//标本名称-病理申请单必填',
                 *  specimenNum;//标本数量-病理申请单必填',
                 *  ywjcResult;//以往检查结果-病理申请单选填',
                 *  ywjcDate;//以往检查时间-病理申请单选填 格式：yyyy-mm-dd',
                 *  blzd;//病理诊断-病理申请单选填'
                 *  fixationfluid;//固定液
                 */
                if (StringUtils.isNotBlank(vo.getParentCode())) {
                    sbs.append(" parent_code=\"" + vo.getParentCode() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getName())) {
                    sbs.append(" group_name=\"" + vo.getName() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getInformation())) {
                    sbs.append(" information=\"" + vo.getInformation() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getCheckEquip())) {
                    sbs.append(" check_equip=\"" + vo.getCheckEquip() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getCheckPart())) {
                    sbs.append(" check_part=\"" + vo.getCheckPart() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getAdresult())) {
                    sbs.append(" adresult=\"" + vo.getAdresult() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getGoal())) {
                    sbs.append(" goal=\"" + vo.getGoal() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getOpview())) {
                    sbs.append(" opview=\"" + vo.getOpview() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getSpecimenName())) {
                    sbs.append(" specimenName=\"" + vo.getSpecimenName() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getSpecimenNum())) {
                    sbs.append(" specimenNum=\"" + vo.getSpecimenNum() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getYwjcResult())) {
                    sbs.append(" ywjc_result=\"" + vo.getYwjcResult() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getYwjcDate())) {
                    sbs.append(" ywjc_date=\"" + vo.getYwjcDate() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getBlzd())) {
                    sbs.append(" blzd=\"" + vo.getBlzd() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getFixationfluid())) {
                    sbs.append(" fixationfluid=\"" + vo.getFixationfluid() + "\"");
                }

                /**
                 * 补充患者信息
                 * social_no 身份证、tell_phone 手机号、address1联系地址、address2、address3、address4、address5 area区、target职称类别
                 */

                if (StringUtils.isNotBlank(vo.getSocialNo())) {
                    sbs.append(" social_no=\"" + vo.getSocialNo() + "\"");
                }

                if (StringUtils.isNotBlank(vo.getTellPhone())) {
                    sbs.append(" tell_phone=\"" + vo.getTellPhone() + "\"");
                }

                if (StringUtils.isNotBlank(vo.getAddress1())) {
                    sbs.append(" address1=\"" + vo.getAddress1() + "\"");
                }

                if (StringUtils.isNotBlank(vo.getAddress2())) {
                    sbs.append(" address2=\"" + vo.getAddress2() + "\"");
                }

                if (StringUtils.isNotBlank(vo.getAddress3())) {
                    sbs.append(" address3=\"" + vo.getAddress3() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getAddress4())) {
                    sbs.append(" address4=\"" + vo.getAddress4() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getAddress5())) {
                    sbs.append(" address5=\"" + vo.getAddress5() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getArea())) {
                    sbs.append(" area=\"" + vo.getArea() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getIdnoType())) {
                    sbs.append(" idno_type=\"" + vo.getIdnoType() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getTarget())) {
                    sbs.append(" target=\"" + vo.getTarget() + "\"");
                }
                if (StringUtils.isNotBlank(vo.getTargetChild())) {
                    sbs.append(" target_child=\"" + vo.getTargetChild() + "\"");
                }
                logger.info("判断自取或者快递标识"+vo.getSelfDelivered());
                if (StringUtils.isNotBlank(vo.getSelfDelivered())){
                    sbs.append(" self_delivered=\"" + vo.getSelfDelivered() + "\"");
                }
                sbs.append("/>");
            }
            sbs.append("</root>]]></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid + " resp:" + resp);
        }
        return ConvertUtil.convertListEnvelopInRequestBS10112(resp);
    }

    /**
     * 医生挂号权限查询接口
     *
     * @param doctor_code 医生工号 必传
     * @param dept        科室编码 必传
     * @param charge_type 号别 必传
     * @param win_no      分部号 必传
     * @return
     * @throws Exception
     */
    public JSONArray BS10114(String doctor_code, String dept, String charge_type, String win_no, boolean demoFlag) throws Exception {
        String fid = BS10114;
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            if (StringUtils.isNotBlank(doctor_code)) {
                sbs.append("<query compy=\"=\" item=\"doctor_code\" splice=\"and\" value=\"'" + doctor_code + "'\"/>");
            }
            if (StringUtils.isNotBlank(dept)) {
                sbs.append("<query compy=\"=\" item=\"dept\" splice=\"and\" value=\"'" + dept + "'\"/>");
            }
            if (StringUtils.isNotBlank(charge_type)) {
                sbs.append("<query compy=\"=\" item=\"charge_type\" splice=\"and\" value=\"'" + charge_type + "'\"/>");
            }
            if (StringUtils.isNotBlank(win_no)) {
                sbs.append("<query compy=\"=\" item=\"win_no\" splice=\"and\" value=\"'" + win_no + "'\"/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 科室字典同步
     *
     * @return
     * @throws Exception
     */
//    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public List<DictHospitalDeptDO> MS02001(boolean demoFlag) throws Exception {
        String fid = MS02001;
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg></Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        JSONArray jsonArray = ConvertUtil.convertListEnvelopInBody(resp);
        List<DictHospitalDeptDO> hospitalDeptMappingDOS = new ArrayList<>();
        DictHospitalDeptDO hdmDo;
        String orgCode = "350211A1002";
        Map<String, String> orgCodeMap = new HashMap<>();
        //6总部7金榜8夏禾
        orgCodeMap.put("6", orgCode);
        orgCodeMap.put("7", "");
        orgCodeMap.put("8", "");
        //删除旧数据
        List<String> strings = new ArrayList<>(orgCodeMap.values());
        for (String s : strings) {
            if (StringUtils.isNotBlank(s)) {
                dictHospitalDeptDao.deleteByOrgCode(s);
            }
        }
        for (Object object : jsonArray) {
            hdmDo = new DictHospitalDeptDO();
            net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) object;
            String deptTypeCode = null == jsonObjectBody.get("Dept_Type_Code") ? "" : jsonObjectBody.get("Dept_Type_Code").toString();
            //是否为会诊科室
            String consultDeptFlag = null == jsonObjectBody.get("Consult_Dept_Flag") ? "" : jsonObjectBody.get("Consult_Dept_Flag").toString();
            if (StringUtils.isNotBlank(orgCodeMap.get(deptTypeCode))) {
                hdmDo.setOrgCode(orgCode);
                hdmDo.setCode(null == jsonObjectBody.get("Dept_Code") ? "" : jsonObjectBody.get("Dept_Code").toString());
                hdmDo.setName(null == jsonObjectBody.get("Dept_Name") ? "" : jsonObjectBody.get("Dept_Name").toString());
                hdmDo.setDeptTypeCode(deptTypeCode);
                hdmDo.setFatherDeptCode(null == jsonObjectBody.get("Father_Dept_Code") ? "" : jsonObjectBody.get("Father_Dept_Code").toString());
                hdmDo.setFatherDeptName(null == jsonObjectBody.get("Father_Dept_Name") ? "" : jsonObjectBody.get("Father_Dept_Name").toString());
                hdmDo.setCreateTime(new Date());
                hdmDo.setDeptType(null == jsonObjectBody.get("Dept_Type") ? "" : jsonObjectBody.get("Dept_Type").toString());
                hdmDo.setDeptPosition(null == jsonObjectBody.get("Dept_Position") ? "" : jsonObjectBody.get("Dept_Position").toString());
//                DictHospitalDeptDao.save(hdmDo);
                hospitalDeptMappingDOS.add(hdmDo);
            }

        }

        dictHospitalDeptDao.save(hospitalDeptMappingDOS);
        return hospitalDeptMappingDOS;
    }

    /**
     * 科室字典更新同步
     *
     * @return
     * @throws Exception
     */
//    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public Boolean updateMS02001(boolean demoFlag) throws Exception {
        String fid = MS02001;
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg></Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        JSONArray jsonArray = ConvertUtil.convertListEnvelopInBody(resp);
        List<DictHospitalDeptDO> hospitalDeptMappingDOS = new ArrayList<>();
        DictHospitalDeptDO hdmDo;
        String orgCode = "350211A1002";
        Map<String, String> orgCodeMap = new HashMap<>();
        //6总部7金榜8夏禾
        orgCodeMap.put("6", orgCode);
        orgCodeMap.put("7", "");
        orgCodeMap.put("8", "");

        List<DictHospitalDeptDO> oriDict = dictHospitalDeptDao.findByOrgCode(orgCode);

        for (Object object : jsonArray) {
            hdmDo = new DictHospitalDeptDO();
            net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) object;
            String deptCode = null == jsonObjectBody.get("Dept_Code") ? "" : jsonObjectBody.get("Dept_Code").toString();

            if(!checkDeptExist(oriDict,deptCode)){
                String deptTypeCode = null == jsonObjectBody.get("Dept_Type_Code") ? "" : jsonObjectBody.get("Dept_Type_Code").toString();
                if (StringUtils.isNotBlank(orgCodeMap.get(deptTypeCode))) {
                    hdmDo.setOrgCode(orgCode);
                    hdmDo.setCode(null == jsonObjectBody.get("Dept_Code") ? "" : jsonObjectBody.get("Dept_Code").toString());
                    hdmDo.setName(null == jsonObjectBody.get("Dept_Name") ? "" : jsonObjectBody.get("Dept_Name").toString());
                    hdmDo.setDeptTypeCode(deptTypeCode);
                    hdmDo.setFatherDeptCode(null == jsonObjectBody.get("Father_Dept_Code") ? "" : jsonObjectBody.get("Father_Dept_Code").toString());
                    hdmDo.setFatherDeptName(null == jsonObjectBody.get("Father_Dept_Name") ? "" : jsonObjectBody.get("Father_Dept_Name").toString());
                    hdmDo.setCreateTime(new Date());
                    hdmDo.setDeptType(null == jsonObjectBody.get("Dept_Type") ? "" : jsonObjectBody.get("Dept_Type").toString());
                    hdmDo.setDeptPosition(null == jsonObjectBody.get("Dept_Position") ? "" : jsonObjectBody.get("Dept_Position").toString());
                    hdmDo.setConsultDeptFlag("0");
                    hospitalDeptMappingDOS.add(hdmDo);
                }
            }
        }
        if(hospitalDeptMappingDOS!=null&&hospitalDeptMappingDOS.size()>0){
            logger.info("dept:"+hospitalDeptMappingDOS.size());
        }
        dictHospitalDeptDao.save(hospitalDeptMappingDOS);
        return true;
    }

    public Boolean checkDeptExist(List<DictHospitalDeptDO> oriDict,String code){
        for(DictHospitalDeptDO dept:oriDict){
            if(code.equals(dept.getCode())){
                return true;
            }
        }
        return false;
    }

    /**
     * 号别字典
     *
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONArray MS02013(String code) throws Exception {
        String fid = MS02013;
        StringBuffer sbs = new StringBuffer();
        //AccessControl ：用户、密码、服务id
        sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>JKZL</UserName><Password>123456</Password></AccessControl>");
        //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
        sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>S60</SourceSysCode><TargetSysCode>S01</TargetSysCode></MessageHeader>");
        //查询信息拼接
        sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
        if (StringUtils.isNotBlank(code)) {
            sbs.append("<query compy=\"=\" item=\"code\" splice=\"and\" value=\"'" + code + "'\"/>");
        }
        sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
        String resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
        resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 医院频次字典表
     *
     * @return
     * @throws Exception
     */
    public JSONArray MS30012(boolean demoFlag) throws Exception {
        String fid = MS30012;
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/><startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBody(resp);
    }

    /**
     * 诊断编码
     *
     * @param py_code 拼音码 非必传、 flag=1为旧的ICD10 3为ICD9 4为2012-8月份ICD10
     * @return
     * @throws Exception
     */
    public JSONArray MS25001(String py_code, boolean demoFlag) throws Exception {
        String fid = "MS25001";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg/>");
            if (StringUtils.isNotBlank(py_code)) {
                py_code = py_code.toUpperCase();
                logger.info("py_code=" + py_code);
                sbs.append("<query compy=\"like\" item=\"py_code\" splice=\"and\" value=\"'%" + py_code + "%'\"/>");
            }

            sbs.append("<query compy=\"=\" item=\"flag\" splice=\"and\" value=\"'5'\"/>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 检查检验
     *
     * @param py_code 拼音码 非必传
     * @return
     * @throws Exception
     */
    public JSONArray MS25002(String py_code, String codes, String win_no, Boolean demoFlag) throws Exception {
        String fid = "MS25002";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg/>");
            if (StringUtils.isNotBlank(py_code)) {
                py_code = py_code.toUpperCase();
                logger.info("py_code=" + py_code);
                sbs.append("<query compy=\"like\" item=\"py_code\" splice=\"and\" value=\"'%" + py_code + "%'\"/>");
            }
            if (StringUtils.isNotBlank(codes)) {
                String groups[] = codes.split(",");
                String inSql = "";
                for (String group : groups) {
                    inSql += "'" + group + "'" + ",";
                }
                inSql = inSql.substring(0, inSql.length() - 1);
                sbs.append("<query compy=\"in\" item=\"code\" splice=\"and\" value=\"(" + inSql + ")\"/>");
            }

            if (StringUtils.isNotBlank(win_no)) {
                String wins[] = win_no.split(",");
                String inSql = "";
                for (String win : wins) {
                    inSql += "'" + win + "'" + ",";
                }
                inSql = inSql.substring(0, inSql.length() - 1);
                sbs.append("<query compy=\"in\" item=\"win_no\" splice=\"and\" value=\"(" + inSql + ")\"/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");

            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }

        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 银医通下载
     *
     * @param cardNo 待查询的卡号
     **/
    public net.sf.json.JSONObject callYYTServerService(String cardNo) throws Exception {
        String re = "";
        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
        String action = "CallYYTServerService";
        String info_xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
                "<root><ip>172.16.50.40</ip><port>5516</port></root>";
        String reqmsg_xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
                "<root><sick_id>" + cardNo + "</sick_id><cus_card_no>" + cardNo + "</cus_card_no>" +
                "<req_type>2001</req_type><trade_type>2001</trade_type><req_oper>8644</req_oper><req_term>192001019019</req_term><win_no>6</win_no></root>";
        Map<String, String> params = new HashMap<>();
        params.put("ServerInfo", info_xml);
        params.put("RegMsg", reqmsg_xml);
        String urlString = "http://172.16.50.40:80/ZyXmyytRequestService/ZyXmyytRequestServiceWs.dll?Handler=ZyXmyytRequestServiceWsService";
        String namespace = "zysoft";
        String s = params.toString();
        re = WebserviceUtil.post(urlString, namespace, action, params);
        logger.info("银医通下载: " + re);
        try {
            XMLSerializer xmlSerializer = new XMLSerializer();
            JSON json = xmlSerializer.read(re);
//        Object errorCode = ((net.sf.json.JSONObject) json).get("error_code");

            //由于新建档的居民没有银医通，数据没办法同步。调用接口，暂时不判断返回结果，由诊间支付统一推送消息让居民支付
//        JSON json2 = xmlSerializer.read(((net.sf.json.JSONObject) json).get("response").toString());
//        System.out.println("银医通下载response:" + json2.toString(1));
            jsonObject.element("code", "1");
            jsonObject.element("obj", json);
//        if ("ok".equals(errorCode)) {
//            JSON json2 = xmlSerializer.read(((net.sf.json.JSONObject) json).get("response").toString());
//            System.out.println("银医通下载response:" + json2.toString(1));
//            jsonObject.element("code", "1");
//            jsonObject.element("obj", json);
//        } else {
//            Object errorMsg = ((net.sf.json.JSONObject) json).get("error_msg");
//            jsonObject.element("code", "-1");
//            jsonObject.element("obj", "银医通下载失败，" + errorMsg);
//            //{"error_type":"0","error_code":"10002","error_msg":"卡号无效"}
//        }
            if (StringUtils.isEmpty(re)) {
                throw new Exception("返回为空！");
            } else {
                if (re.startsWith("error")) {
                    throw new Exception(re);
                }
            }
            return jsonObject;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 患者门诊就诊记录
     * 按照患者唯一号、科室、医生、获取当前时间往前24小时的挂号记录。获取最新一条判断是否有效(医保当天有效，自费24小时有效)
     * 若是自费，则有效
     * 若是医保，判断日期是否和当前时间同一天，否则无效
     *
     * @param patNo  居民唯一号 必传参数
     * @param dept   挂号科室 必传参数
     * @param doctor 挂号医生 必传参数
     * @return true 已挂号 ，false 未挂号
     * @throws Exception
     */
    public boolean guahao(String patNo, String dept, String doctor, boolean demoFlag) throws Exception {
        String fid = BS30025;
        StringBuffer sbs = new StringBuffer();
        String resp;
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><onceFlag>1</onceFlag><startNum>1</startNum><endNum>50000</endNum><Msg/>");
            if (StringUtils.isNotBlank(patNo)) {
                sbs.append("<query compy=\"=\" item=\"PAT_NO\" splice=\"and\" value=\"'" + patNo + "'\"/>");
            }
            if (StringUtils.isNotBlank(dept)) {
                sbs.append("<query compy=\"=\" item=\"ADM_SPEC\" splice=\"and\" value=\"'" + dept + "'\"/>");
            }
            if (StringUtils.isNotBlank(doctor)) {
                sbs.append("<query compy=\"=\" item=\"CON_DOC\" splice=\"and\" value=\"'" + doctor + "'\"/>");
            }
            //获取当前时间 查询当前时间往前推24小时是否有挂号 （医保当天有效，自费24小时有效）
            String now = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD_HH_MM_SS);
            String preday = DateUtil.dateToStr(DateUtil.getPreDays(DateUtil.getNowDate(), -1), DateUtil.YYYY_MM_DD_HH_MM_SS);
            if (StringUtils.isNotBlank(preday)) {
                sbs.append("<query compy=\"&gt;\" item=\"ADM_DAT\" splice=\"and\" value=\"'" + preday + "'\"/>");
            }
            if (StringUtils.isNotBlank(now)) {
                sbs.append("<query compy=\"&lt;\" item=\"ADM_DAT\" splice=\"and\" value=\"'" + now + "'\"/>");
            }
            sbs.append("<query compy=\"\" item=\"icd_name\" splice=\"and\" value=\"is not null\"/>");
            sbs.append("<order item=\"ADM_DAT\" sort=\"desc\"/>");
            //查询信息结束
            sbs.append("</MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);

        }
        //解析返回结果
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(resp);
        if (null != jsonObject.get("MsgInfo")) {
            net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) jsonObject.get("MsgInfo");
            //获取第一条
            net.sf.json.JSONObject object = (net.sf.json.JSONObject) jsonArray.get(0);
            if (null != object) {
                object = (net.sf.json.JSONObject) object.get("row");
            }
            String ybFlag = null != object.get("yb_flag") ? object.get("yb_flag").toString() : "";
            //市医保，1； 省医保，2； 自费，4；其他医保，99）
            if ("4".equals(ybFlag)) {
                return true;
            } else if (("1".equals(ybFlag) || "2".equals(ybFlag) || "99".equals(ybFlag))) {
                String admDateStr = object.get("ADM_DAT") + "";
                //挂号时间
                Date admDate = DateUtil.strToDate(admDateStr + "", DateUtil.YYYY_MM_DD_);
                SimpleDateFormat format = new SimpleDateFormat(DateUtil.YYYY_MM_DD_);
                //获取当前时间
                String dateString = format.format(new Date());
                Date nowDate = DateUtil.strToDate(dateString, DateUtil.YYYY_MM_DD_);
                if (0 == nowDate.compareTo(admDate)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }


    /**
     * 诊断编码
     *
     * @param patNo    居民唯一号 必传参数
     * @param conNo    就诊次数 必传次数
     * @param demoFlag 是否获取本地示例数据 true 是，false 否
     * @return
     * @throws Exception
     */
    public JSONArray BS25017(String patNo, String conNo, boolean demoFlag) throws Exception {
        String fid = "BS25017";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg/>");
            if (StringUtils.isNotBlank(patNo)) {
                sbs.append("<query compy=\"=\" item=\"inpatient_no\" splice=\"and\" value=\"'" + patNo + "'\"/>");
            }
            if (StringUtils.isNotBlank(conNo)) {
                sbs.append("<query compy=\"=\" item=\"times\" splice=\"and\" value=\"'" + conNo + "'\"/>");
            }
            sbs.append("<order item=\"apply_date\" sort=\"desc\"/>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 检验送检信息查询
     *
     * @param patNo    患者唯一号 必传参数
     * @param conNo    就诊次数 必传参数
     * @param demoFlag 是否获取测试数据
     * @return
     * @throws Exception
     */
    public JSONArray BS20010(String patNo, String conNo, boolean demoFlag) throws Exception {
        String fid = "BS20010";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg/>");
            if (StringUtils.isNotBlank(patNo)) {
                sbs.append("<query compy=\"=\" item=\"CureNo\" splice=\"and\" value=\"'" + patNo + "'\"/>");
            }
            if (StringUtils.isNotBlank(conNo)) {
                sbs.append("<query compy=\"=\" item=\"patientid\" splice=\"and\" value=\"'" + conNo + "'\"/>");
            }
            sbs.append("<order item=\"receiveTime\" sort=\"desc\"/>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 检验的是通过BS20010先查出applyno 这个，然后去查BS20019
     *
     * @param patNo    居民唯一号 必传参数
     * @param conNo    就诊次数 必传次数
     * @param demoFlag 是否获取本地示例数据 true 是，false 否
     * @return
     * @throws Exception
     */
    public JSONArray BS20019(String patNo, String conNo, boolean demoFlag) throws Exception {
        String fid = "BS20019";
        String resp = "";
        net.sf.json.JSONArray jsonArrayLast = new net.sf.json.JSONArray();
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
            net.sf.json.JSONArray jsonArray1 = ConvertUtil.convertListEnvelopInBodyRow(resp);
            jsonArrayLast.add(jsonArray1);
        } else {
            //获取检验送检记录
            JSONArray jsonArray = BS20010(patNo, conNo, demoFlag);
            for (Object object : jsonArray) {
                net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) object;
                if (null != jsonObjectBody) {
                    String applyno = null == jsonObjectBody.get("applyno") ? "" : jsonObjectBody.get("applyno").toString();
                    if (StringUtils.isNotBlank(applyno)) {
                        StringBuffer sbs = new StringBuffer();
                        //AccessControl ：用户、密码、服务id
                        sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
                        //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
                        sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
                        //查询信息拼接
                        sbs.append("<RequestOption><onceFlag>0</onceFlag></RequestOption><MsgInfo><startNum>1</startNum><endNum>20000</endNum><Msg/>");
                        if (StringUtils.isNotBlank(applyno)) {
                            sbs.append("<query compy=\"=\" item=\"applyno\" splice=\"and\" value=\"'" + applyno + "'\"/>");
                        }
                        sbs.append("<order item=\"ResultTime\" sort=\"desc\"/>");
                        sbs.append("</MsgInfo></ESBEntry>");
                        resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
                        resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
                        net.sf.json.JSONArray jsonArray1 = ConvertUtil.convertListEnvelopInBodyRow(resp);
                        jsonArrayLast.add(jsonArray1);
                    }
                }
            }


        }
        return jsonArrayLast;
    }

    /**
     * 微生物的是先查BS20018，也是查出applyno 再去查BS20011
     *
     * @param patNo    居民唯一号 必传参数
     * @param conNo    就诊次数 必传次数
     * @param demoFlag 是否获取本地示例数据 true 是，false 否
     * @return
     * @throws Exception
     */
    public JSONArray BS20011(String patNo, String conNo, boolean demoFlag) throws Exception {
        String fid = "BS20011";
        String resp = "";
        net.sf.json.JSONArray jsonArrayLast = new net.sf.json.JSONArray();
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
            net.sf.json.JSONArray jsonArray1 = ConvertUtil.convertListEnvelopInBodyRow(resp);
            jsonArrayLast.add(jsonArray1);
        } else {
            //获取微生物送检记录
            JSONArray jsonArray = BS20018(patNo, conNo, demoFlag);
            for (Object object : jsonArray) {
                net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) object;
                jsonObjectBody = (net.sf.json.JSONObject) jsonObjectBody.get("body");
                jsonObjectBody = null == jsonObjectBody ? jsonObjectBody : (net.sf.json.JSONObject) jsonObjectBody.get("row");
                if (null != jsonObjectBody) {
                    String applyno = null == jsonObjectBody.get("applyno") ? "" : jsonObjectBody.get("applyno").toString();
                    if (StringUtils.isNotBlank(applyno)) {
                        StringBuffer sbs = new StringBuffer();
                        //AccessControl ：用户、密码、服务id
                        sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
                        //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
                        sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
                        //查询信息拼接
                        sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
                        if (StringUtils.isNotBlank(applyno)) {
                            sbs.append("<query compy=\"=\" item=\"applyno\" splice=\"and\" value=\"'" + applyno + "'\"/>");
                        }
                        sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
                        resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
                        resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
                        net.sf.json.JSONArray jsonArray1 = ConvertUtil.convertListEnvelopInBodyRow(resp);
                        jsonArrayLast.add(jsonArray1);
                    }
                }
            }
        }
        return jsonArrayLast;
    }

    /**
     * 获取微生物检查记录
     *
     * @param patNo    居民唯一号 必传
     * @param conNo    就诊次数 必传
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS20018(String patNo, String conNo, boolean demoFlag) throws Exception {
        String fid = "BS20018";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            if (StringUtils.isNotBlank(patNo)) {
                sbs.append("<query compy=\"=\" item=\"CureNo\" splice=\"and\" value=\"'" + patNo + "'\"/>");
            }
            if (StringUtils.isNotBlank(conNo)) {
                sbs.append("<query compy=\"=\" item=\"patientid\" splice=\"and\" value=\"'" + conNo + "'\"/>");
            }
            sbs.append("<order item=\"receiveTime\" sort=\"desc\"/>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    /**
     * 诊查费字典同步
     *
     * @param windowsNo  分部号
     * @param code       医生code
     * @param chargeType 号别
     * @param demoFlag   是否获取demo数据
     * @return
     * @throws Exception
     */
    public List<WlyyChargeDictDO> chargeDict(String windowsNo, String code, String chargeType, boolean demoFlag) throws Exception {
        String resp = "";
        Map<String, Object> map = new HashMap<>();
        List<WlyyChargeDictDO> wlyyChargeDictDOS = new ArrayList<>();
        net.sf.json.JSONArray jsonArray = new JSONArray();
        if (demoFlag) {
            String fid = "BS55010";
            resp = getJosnFileResullt(fid);
            jsonArray = ConvertUtil.convertListEnvelopInBodyRow(resp);
        } else {
            jsonArray = BS55010(windowsNo, code, chargeType, demoFlag);
        }
        if (null != jsonArray) {
            for (Object object : jsonArray) {
                net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) object;
                String chareName = "";
                if (null != jsonObjectBody) {
                    String chareCode = null == jsonObjectBody.get("charge_type") ? "" : jsonObjectBody.get("charge_type").toString();
                    String winNo = null == jsonObjectBody.get("windows_no") ? "" : jsonObjectBody.get("windows_no").toString();
                    //WlyyChargeDictDO
                    if (!map.containsKey(chareCode + "_" + winNo)) {
                        //查询号别
                        net.sf.json.JSONArray chares = MS02013(chareCode);
                        for (Object object1 : chares) {
                            net.sf.json.JSONObject jsonObjectBody1 = (net.sf.json.JSONObject) object1;
                            chareName = null == jsonObjectBody1.get("name") ? "" : jsonObjectBody1.get("name").toString();
                            System.out.println(chareCode + chareName);
                            WlyyChargeDictDO wlyyChargeDictDO = new WlyyChargeDictDO();
                            wlyyChargeDictDO.setChargeType(chareCode);
                            wlyyChargeDictDO.setChargeName(chareName);

                            wlyyChargeDictDO.setDeptTypeCode(winNo);
                            Double free = null == jsonObjectBody.get("req_fee") ? 0 : Double.parseDouble(jsonObjectBody.get("req_fee").toString());
                            wlyyChargeDictDO.setReqFee(free);
                            wlyyChargeDictDO.setIsDel("1");
                            wlyyChargeDictDO.setCreateTime(new Date());
                            map.put(chareCode + "_" + winNo, chareName);
                            wlyyChargeDictDO = wlyyChargeDictDao.save(wlyyChargeDictDO);
                            wlyyChargeDictDOS.add(wlyyChargeDictDO);
                        }
                    }
                }
            }
        }
        return wlyyChargeDictDOS;
    }

    public net.sf.json.JSONArray BS55010(String windowsNo, String code, String chargeType, boolean demoFlag) throws Exception {
        String fid = "BS55010";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            if (StringUtils.isNotBlank(windowsNo)) {
                sbs.append("<query compy=\"=\" item=\"windows_no\" splice=\"and\" value=\"'" + windowsNo + "'\"/>");
            }
            if (StringUtils.isNotBlank(chargeType)) {
                sbs.append("<query compy=\"=\" item=\"charge_type\" splice=\"and\" value=\"'" + chargeType + "'\"/>");
            }
            if (StringUtils.isNotBlank(code)) {
                sbs.append("<query compy=\"=\" item=\"code\" splice=\"and\" value=\"'" + code + "'\"/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    /**
     * 获取五级地址
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray MS02019(boolean demoFlag) throws Exception {
        String fid = "MS02019";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg/>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            logger.info("sbs"+sbs.toString());
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info("resp"+resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     *  核酸预约列表接口
     * @param deptCode
     * @param docCode
     * @param chargeType
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS10142(String deptCode,String docCode,String chargeType,boolean demoFlag) throws Exception {
        String fid = "BS10142";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg>");
            sbs.append("<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root><resquest DeptCode=\""+deptCode+"\" DocCode=\""+docCode+"\" ChargeType=\""+chargeType+"\" ></resquest></root>]]>");
            sbs.append("</Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    /**
     * 核酸号源查询
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS10143(String day,String pm,boolean demoFlag) throws Exception {
        String fid = "BS10143";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg>");
            if (StringUtils.isNotBlank(day)) {
                sbs.append("<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root><resquest request_day=\""+day+"\" ampm=\""+pm+"\" ></resquest></root>]]>");
            }
            sbs.append("</Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    /**
     * 核酸预约
     * @param deptCode 科室code
     * @param docCode 医生code
     * @param startTime 预约时间
     * @param sSID 社保卡
     * @param patientName 患者姓名
     * @param patientID 身份证
     * @param patientPhone 手机号
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public String BS10144(String deptCode,String docCode,String startTime,String sSID,String patientName,String patientID,String patientPhone,String pm, boolean demoFlag) throws Exception {
        String fid = "BS10144";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg>");
            sbs.append("<as_xml><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root><resquest DeptCode=\""+deptCode+"\" DocCode=\""+docCode+"\" ampm=\""+pm+"\" StartTime=\""+startTime+"\" SSID=\""+sSID+"\" PatientName=\""+patientName+"\" PatientID=\""+patientID+"\" PatientPhone=\""+patientPhone+"\"></resquest></root>]]></as_xml>");
            sbs.append("</Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowBS10144(resp);
        }
        return resp;
    }

    /**
     * 核酸预约取消
     * @param deptCode 科室code
     * @param docCode 医生code
     * @param startTime 预约时间
     * @param sSID 社保卡
     * @param patientName 患者姓名
     * @param patientID 身份证
     * @param patientPhone 手机号
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public String BS10145(String deptCode,String docCode,String startTime,String sSID,String patientName,String patientID,String patientPhone,String pm, boolean demoFlag) throws Exception {
        String fid = "BS10145";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum><Msg>");
            sbs.append("<as_xml><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root><resquest DeptCode=\""+deptCode+"\" DocCode=\""+docCode+"\" ampm=\""+pm+"\" StartTime=\""+startTime+"\" SSID=\""+sSID+"\" PatientName=\""+patientName+"\" PatientID=\""+patientID+"\" PatientPhone=\""+patientPhone+"\"></resquest></root>]]></as_xml>");
            sbs.append("</Msg><startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowBS10144(resp);

        }
        return resp;
    }






    /**
     * 同步医生到本地库，获取到医生的时候需要调用BS55010 查询医生的诊查费
     *
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public int MS02003(boolean demoFlag) throws Exception {
        int i = 0;
        String fid = "MS02003";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>10000</endNum><Msg></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");

            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);
        }
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(resp);
        logger.info("获取医生数据"+jsonObject.toString());
        if (null != jsonObject && "1".equals(jsonObject.get("code").toString())) {
            JSONArray jsonObjectMgsInfo = (JSONArray) jsonObject.get("MsgInfo");
            if (null != jsonObjectMgsInfo) {
                for (Object object : jsonObjectMgsInfo) {

                    JSONArray jsonArray = JSONArray.fromObject(object);
                    net.sf.json.JSONObject jsonArraySub = jsonArray.getJSONObject(0);
//                    net.sf.json.JSONObject jsonArraySub = (net.sf.json.JSONObject) object;
                    jsonObjectMgsInfo = (JSONArray) jsonArraySub.get("body");
                    if (jsonObjectMgsInfo instanceof JSONArray) {
                        for (Object objectSub : jsonObjectMgsInfo) {
                            net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) objectSub;
                            String doctorCode = "";
                            String doctorName = "";
                            if (null != jsonObjectBody) {
                                //获取中山医院的医生
                                String winNo = "6";
                                doctorCode = null == jsonObjectBody.get("Emp_Code") ? "" : jsonObjectBody.get("Emp_Code").toString();
                                //根据医生及分部，获取医生号别
                                net.sf.json.JSONArray jsonArrayCharge = BS55010(winNo, doctorCode, null, false);
                                String chareType = null;
                                if (null != jsonArrayCharge) {
                                    for (Object objectCharge : jsonArrayCharge) {
                                        net.sf.json.JSONObject jsonObjectBodyCharge = (net.sf.json.JSONObject) objectCharge;
                                        if (null != jsonObjectBodyCharge) {
                                            chareType = null == jsonObjectBodyCharge.get("charge_type") ? null : jsonObjectBodyCharge.get("charge_type").toString();
                                        }
                                    }
                                }
                                //保存医生信息
                                BaseDoctorDO baseDoctorDO = new BaseDoctorDO();
                                String idCard = null == jsonObjectBody.get("Card_Id") ? "" : jsonObjectBody.get("Card_Id").toString();
                                List<BaseDoctorDO> baseDoctorDOS = baseDoctorDao.findByIdcard(idCard);
                                if (baseDoctorDOS!=null&&baseDoctorDOS.size()!=0){
                                    baseDoctorDO=baseDoctorDOS.get(0);

                                }else {
                                    baseDoctorDO.setIdcard(idCard);
                                    baseDoctorDO.setBirthday(IdCardUtil.getBirthdayForIdcard(idCard));
                                    baseDoctorDO.setSex(Integer.valueOf(IdCardUtil.getSexForIdcard(idCard)));
                                    baseDoctorDO.setLocked(0);
                                    baseDoctorDO.setEnabled(1);
                                    String disableFlag = null == jsonObjectBody.get("Disable_Flag") ? "" : jsonObjectBody.get("Disable_Flag").toString();
                                    //互联网医院：1停用，0使用  转 i健康：1正常，0作废
                                    baseDoctorDO.setDel("1".equals(disableFlag) ? "0" : "1");
                                    baseDoctorDO.setMobile("0");
                                    baseDoctorDO.setName(doctorName);
                                    baseDoctorDO.setIsFamous(0);
                                    baseDoctorDO.setCreateTime(new Date());
                                    baseDoctorDO.setUpdateTime(new Date());
                                    if (StringUtils.isNotBlank(idCard)) {
                                        baseDoctorDO.setSalt(PwdUtil.randomString(5));
                                        try {
                                            baseDoctorDO.setPassword(com.yihu.utils.security.MD5.md5Hex(baseDoctorDO.getIdcard().substring(baseDoctorDO.getIdcard().length() - 6) + "{" + baseDoctorDO.getSalt() + "}"));
                                        } catch (Exception e) {
                                            logger.error(e.getMessage() + "docotr=" + doctorCode + ";idcard=" + baseDoctorDO.getIdcard());
                                        }
                                    } else {
                                        baseDoctorDO.setPassword(com.yihu.utils.security.MD5.md5Hex("123456" + "{" + baseDoctorDO.getSalt() + "}"));
                                    }
                                }
                                //拼音码
                                baseDoctorDO.setSpell(null == jsonObjectBody.get("PinYin_Code") ? "" : jsonObjectBody.get("PinYin_Code").toString());
                                //姓名
                                doctorName = null == jsonObjectBody.get("Emp_Name") ? "" : jsonObjectBody.get("Emp_Name").toString();
                                //号别
                                baseDoctorDO.setChargeType(chareType);

                                baseDoctorDO = baseDoctorDao.save(baseDoctorDO);
                                //根据医生和机构判断数据是否存在，若不存在则在mapping中追加记录
                                List<DoctorMappingDO> doctorMappingDOS = doctorMappingDao.findByDoctorAndOrgCode(baseDoctorDO.getId(), "350211A1002");
                                if (!(null != doctorMappingDOS && doctorMappingDOS.size() > 0)) {
                                    DoctorMappingDO doctorMappingDO = new DoctorMappingDO();
                                    doctorMappingDao.delete(doctorMappingDOS);
                                    doctorMappingDO.setDoctor(baseDoctorDO.getId());
                                    doctorMappingDO.setDoctorName(doctorName);
                                    doctorMappingDO.setMappingCode(doctorCode);
                                    doctorMappingDO.setMappingName(doctorName);
                                    doctorMappingDO.setOrgCode("350211A1002");
                                    doctorMappingDO.setOrgName("厦门大学附属中山医院");
                                    doctorMappingDao.save(doctorMappingDO);
                                }
                                // 用医生和机构id、部门判断数据是否存在，若不存在则保存医生机构关联关系
                                String deptCode = null == jsonObjectBody.get("Dept_Code") ? "" : jsonObjectBody.get("Dept_Code").toString();
                                List<BaseDoctorHospitalDO> baseDoctorHospitalDOS = baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode("350211A1002", deptCode, baseDoctorDO.getId());
                                if (!(null != baseDoctorHospitalDOS && baseDoctorHospitalDOS.size() > 0)) {
                                    baseDoctorHospitalDao.delete(baseDoctorHospitalDOS);
                                    BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                                    baseDoctorHospitalDO.setOrgCode("350211A1002");
                                    baseDoctorHospitalDO.setOrgName("厦门大学附属中山医院");
                                    baseDoctorHospitalDO.setDoctorCode(baseDoctorDO.getId());
                                    baseDoctorHospitalDO.setDeptCode(deptCode);
                                    //根据机构编码获取机构名称
                                    List<DictHospitalDeptDO> dictHospitalDeptDOS = dictHospitalDeptDao.findByOrgCodeAndCode("350211A1002", deptCode);
                                    if (null != dictHospitalDeptDOS && dictHospitalDeptDOS.size() > 0) {
                                        DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDOS.get(0);
                                        baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                                    }
                                    baseDoctorHospitalDO.setDel("1");
                                    baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                                }
                                i++;
                            }

                        }
                    }

                }
            }
        }
//            net.sf.json.JSONArray jsonArray = ConvertUtil.convertListEnvelopInBodyRowMS02003(resp);
//            for (Object object : jsonArray) { }
//        }
        return i;
    }

    public Map<String, Object> MS02014(boolean demoFlag) throws Exception {
        Map<String, Object> rs = new HashedMap();
        int i = 0;
        int sc = 0;
        logger.info("MS02014 start:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        String fid = "MS02014";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>10000</endNum><Msg></Msg><startNum>1</startNum></MsgInfo></ESBEntry>");

            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);
            //getJson("MS02014",resp);
        }
//        resp ="<ESBEntry><MessageHeader><Fid>MS02014</Fid><MsgDate>2019-09-04 13:33:39</MsgDate><SourceSysCode>S14</SourceSysCode><TargetSysCode>S60</TargetSysCode></MessageHeader><MsgInfo><Msg><![CDATA[<msg><head><msgId>MS02014</msgId><version>2</version><msgName>HRP职工字典</msgName><sourceSysCode>S14</sourceSysCode><targetSysCode>S60</targetSysCode><createTime>20190904133339</createTime></head><body><row><action>select</action><Staff_Code>11095</Staff_Code><Staff_Name>杨峰腾</Staff_Name><Dept_id>0000001269</Dept_id><Dept_name>药学部</Dept_name><ID_Number>35062319881207101X</ID_Number><Sex_code>01</Sex_code><Sex_Name>男</Sex_Name><Date_Birth>1988-12-07 00:00:00</Date_Birth><Addr_Home></Addr_Home><Mobile_No>13290785969</Mobile_No><Major>药学（药物分析方向）</Major><Education_Name>本科</Education_Name><Degree_Name>学士</Degree_Name><Entry_Date>2012-10-01 00:00:00</Entry_Date><Arrive_Hosp_Date>2014-07-18 00:00:00</Arrive_Hosp_Date><Staff_Categ_Code>2</Staff_Categ_Code><Staff_Categ_name>医生</Staff_Categ_name><Title_Level_Code>021</Title_Level_Code><Title_Level_name>专技初级</Title_Level_name><Staff_Status_Code>0</Staff_Status_Code><Staff_Status_Name>在职</Staff_Status_Name><level_code>1303</level_code><level_name>主管药师</level_name><Degree_Code>04</Degree_Code><Ethnic_Code>01</Ethnic_Code><Ethnic_name>汉族</Ethnic_name><Political_Status>01</Political_Status><Political_Status_name>普通群众</Political_Status_name><Practice_Certificate_No></Practice_Certificate_No><Skill_Certificate_No></Skill_Certificate_No></row></body></msg>]]></Msg><MsgCount>1</MsgCount><CurrentNum>1</CurrentNum></MsgInfo><RetInfo><RetCode>1</RetCode><RetCon>查询成功</RetCon></RetInfo></ESBEntry>";
//        resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);

        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(resp);

        if (jsonObject != null) {
            String code = jsonObject.getString("code");
            logger.info("MS02014 code:" + code);
            boolean f = true;
            if ("1".equals(code)) {

                JSONArray msgs = jsonObject.getJSONArray("MsgInfo");
                if (msgs != null && msgs.size() > 0) {
                    for (int j = 0; j < msgs.size(); j++) {
                        i++;
                        net.sf.json.JSONObject msg = (net.sf.json.JSONObject) msgs.get(j);
                        if (i == 1) {
                            logger.info("msg : " + msg.toString());
                        }
                        net.sf.json.JSONObject body = msg.getJSONObject("body");
                        net.sf.json.JSONObject row = body.getJSONObject("row");
//                        String  rowstr ="{\"action\":\"select\",\"Staff_Code\":\"10893\",\"Staff_Name\":\"董若君\",\"Dept_id\":\"0000001272\",\"Dept_name\":\"急诊部\",\"ID_Number\":\"341602199111255002\",\"Sex_code\":\"02\",\"Sex_Name\":\"女\",\"Date_Birth\":\"1991-11-25 00:00:00\",\"Addr_Home\":[],\"Mobile_No\":\"18250870575\",\"Major\":\"护理\",\"Education_Name\":\"本科\",\"Degree_Name\":\"学士\",\"Entry_Date\":\"2012-07-01 00:00:00\",\"Arrive_Hosp_Date\":\"2012-07-18 00:00:00\",\"Staff_Categ_Code\":\"1\",\"Staff_Categ_name\":\"护士\",\"Title_Level_Code\":\"021\",\"Title_Level_name\":\"专技初级\",\"Staff_Status_Code\":\"1\",\"Staff_Status_Name\":\"注销\",\"level_code\":\"1402\",\"level_name\":\"护师\",\"Degree_Code\":\"04\",\"Ethnic_Code\":\"01\",\"Ethnic_name\":\"汉族\",\"Political_Status\":[],\"Political_Status_name\":[],\"Practice_Certificate_No\":\"201335000500\",\"Skill_Certificate_No\":[]}";
//                        net.sf.json.JSONObject row= net.sf.json.JSONObject.fromObject(rowstr);
                        try {
                            String idCard = row.getString("ID_Number");
                            if (StringUtils.isNotBlank(idCard)) {
                                BaseDoctorZsInfoDO info = new BaseDoctorZsInfoDO();
                                info.setStaffCode(row.getString("Staff_Code"));
                                info.setStaffName(row.getString("Staff_Name"));
                                info.setDeptId(row.getString("Dept_id"));
                                info.setDeptName(row.getString("Dept_name"));
                                info.setIdNumber(row.getString("ID_Number"));
                                info.setSexCode(row.getString("Sex_code"));
                                info.setSexName(row.getString("Sex_Name"));
//                                info.setDateBirth(row.getString("Date_Birth")!=null?DateUtil.stringToDate(row.getString("Date_Birth"),"yyyy-MM-dd HH:mm:ss"):null);
                                info.setAddrHome(row.getString("Addr_Home"));
                                info.setMobileNo(row.getString("Mobile_No"));
                                info.setMajor(row.getString("Major"));
                                info.setEducationName(row.getString("Education_Name"));
                                info.setDegreeName(row.getString("Degree_Name"));
//                                info.setEntryDate(row.getString("Entry_Date")!=null?DateUtil.stringToDate(row.getString("Date_Birth"),"yyyy-MM-dd HH:mm:ss"):null);
//                                info.setArriveHospDate(row.getString("Arrive_Hosp_Date")!=null?DateUtil.stringToDate(row.getString("Date_Birth"),"yyyy-MM-dd HH:mm:ss"):null);
                                info.setStaffCategCode(row.getString("Staff_Categ_Code"));
                                info.setStaffCategName(row.getString("Staff_Categ_name"));
                                info.setTitleLevelCode(row.getString("Title_Level_Code"));
                                info.setTitleLevelName(row.getString("Title_Level_name"));
                                info.setStaffStatusCode(row.getString("Staff_Status_Code"));
                                info.setStaffStatusName(row.getString("Staff_Status_Name"));
                                info.setLevelCode(row.getString("level_code"));
                                info.setLevelName(row.getString("level_name"));
                                info.setDegreeCode(row.getString("Degree_Code"));
                                info.setEthnicCode(row.getString("Ethnic_Code"));
                                info.setEthnicName(row.getString("Ethnic_name"));
                                info.setPoliticalStatus(row.getString("Political_Status"));
                                info.setPoliticalStatusName(row.getString("Political_Status_name"));
                                info.setPracticeCertificateNo(row.getString("Practice_Certificate_No"));
                                info.setSkillCertificateNo(row.getString("Skill_Certificate_No"));
                                doctorZsInfoDao.save(info);
                                logger.info("info cout:" + sc++);
                            }
                        } catch (Exception e) {
                            //logger.error("row "+i+" :"+ row.toString());
                            if (f) {
                                logger.error("row " + i + " :" + row.toString());
                                e.printStackTrace();
                                f = false;
                            }
                        }
                    }
                }
            }
        }
        rs.put("c", sc);
        rs.put("i", i);
        logger.info("MS02014 end:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));

        return rs;
    }
    //=============================================公众号信息======================================================================================

    /**
     * @param userName      推送人姓名
     * @param idCard        推送人身份证
     * @param phone         推送人手机号
     * @param title         推送标题
     * @param url           跳转链接
     * @param content       内容简介
     * @param contentString 内容明细串
     * @return
     */
    public String ehospitalNotice(String userName, String idCard, String phone, String title, String url, String content, String contentString) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName", userName);
        jsonObject.put("idCard", idCard);
        jsonObject.put("phone", phone);
        jsonObject.put("title", title);
        jsonObject.put("url", url);
        jsonObject.put("content", content);
        jsonObject.put("contentString", contentString);
        System.out.println(serverUrl);
        String responseMsg = httpClientUtil.sendPost(serverUrl + "/interface/ehospitalNoticePush.htm", jsonObject.toString());
        logger.info("ehospitalNoticePushResult:" + responseMsg);
        return responseMsg;
    }

    /**
     * @param openId openId
     * @return
     */
    public String getUserInfoByOpenid(String openId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("openId", openId);
        String responseMsg = httpClientUtil.sendPost(serverUrl + "/interface/getUserInfoByOpenId.htm", jsonObject.toString());
        logger.info("getUserInfoByOpenIdResult:" + responseMsg);
        return responseMsg;
    }

    /**
     * @param interfaceid 校验码,默认:100033
     * @return
     */
    public String getAccessToken(String interfaceid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("interfaceid", interfaceid);
        String responseMsg = httpClientUtil.sendPost(serverUrl + "/interface/getAccessToken.htm", jsonObject.toString());
        logger.info("getAccessTokenResult:" + responseMsg);
        return responseMsg;
    }
    //======================================中山医院公众号===end=======================================================================================

    /**
     * 获取/同步医生简介到本地库
     *
     * @param doctorCode 医生编码,当医生编码不为空则获取单个医生的简介，如果医生编码为空则获取所有医生简介
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSON BS16010(String doctorCode, boolean demoFlag) throws Exception {
        int i = 0;
        String fid = "BS16010";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            sbs.append("<MsgInfo><endNum>500</endNum><Msg></Msg>");
            if (StringUtils.isNotBlank(doctorCode)) {
                sbs.append("<query compy=\"=\" item=\"doctorNumber\" splice=\"and\" value=\"" + doctorCode + "\"/>");
            }
            //查询信息拼接
            sbs.append(" <query compy=\"=\" item=\"page\" splice=\"and\" value=\"1\"/>" +
                    "  <query compy=\"=\" item=\"initpnum\" splice=\"and\" value=\"500\"/>" +
                    "<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            logger.info("resp=" + resp);
        }
        return MqSdkUtil.xml2jsonArrayRootRowBS16011(resp);
    }

    /**
     * 获取单个/同步科室简介到本地库
     *
     * @param depNumber 科室编码：,当科室编码不为空则获取单个科室的简介，如果科室编码为空则获取所有科室简介
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSON BS16011(String depNumber, boolean demoFlag) throws Exception {
        int i = 0;
        String fid = "BS16011";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg></Msg>");
            if (StringUtils.isNotBlank(depNumber)) {
                sbs.append("<query compy=\"=\" item=\"depNumber\" splice=\"and\" value=\"" + depNumber + "\"/>");
            }
            //查询信息拼接
            sbs.append("<query compy=\"=\" item=\"page\" splice=\"and\" value=\"1\"/>" +
                    "<query compy=\"=\" item=\"initpnum\" splice=\"and\" value=\"1000\"/>" +
                    "<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            logger.info("resp=" + resp);
        }
        return MqSdkUtil.xml2jsonArrayRootRowBS16011(resp);
    }

    public void getJson(String name, String resp) throws Exception {
        logger.info("/usr/local/ehr/" + name + ".txt");
        File file = new File("/usr/local/ehr/" + name + ".txt");
        //如果文件目录不存在需要先创建文件目录
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        OutputStream output = new FileOutputStream(file);
        //字节输出流需要使用byte类型，需要将String类对象转换为字节数组
        byte data[] = resp.getBytes();

        int a = data.length;
        output.write(data, 0, a);
        //System.out.println(a);
        output.close();
    }


    /**
     * 检验模板
     *
     * @param bz_code
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS20030(String bz_code, String tc_no, String flag, boolean demoFlag) throws Exception {
        String fid = "BS20030";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum>");
            if (StringUtils.isNotBlank(bz_code) || StringUtils.isNotBlank(tc_no)) {
                sbs.append("<Msg>");
                if (StringUtils.isNotBlank(bz_code)) {
                    sbs.append(" and bz_code = '" + bz_code + "' ");
                }
                if (StringUtils.isNotBlank(tc_no)) {
                    sbs.append(" and tc_no = '" + tc_no + "' ");
                }
                sbs.append("</Msg>");
            } else {
                sbs.append("<Msg/>");
            }
            sbs.append("<FLAG>" + flag + "</FLAG>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * S60线上复诊 BS25033检查模板接口
     *
     * @param bz_code
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS25033(String bz_code, String tc_no, String flag, boolean demoFlag) throws Exception {
        String fid = "BS25033";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum>");
            if (StringUtils.isNotBlank(bz_code) || StringUtils.isNotBlank(tc_no)) {
                sbs.append("<Msg>");
                if (StringUtils.isNotBlank(bz_code)) {
                    sbs.append(" and bz_code = '" + bz_code + "' ");
                }
                if (StringUtils.isNotBlank(tc_no)) {
                    sbs.append(" and tc_no = '" + tc_no + "' ");
                }
                sbs.append("</Msg>");
            } else {
                sbs.append("<Msg/>");
            }
            sbs.append("<FLAG>" + flag + "</FLAG>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * S60线上复诊 MS02015套餐子项目字典接口
     *
     * @param parent_code
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray MS02015(String parent_code, boolean demoFlag) throws Exception {
        String fid = "MS02015";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum>");
            if (StringUtils.isNotBlank(parent_code)) {
                sbs.append("<Msg>and parent_code = '" + parent_code + "'</Msg>");
            } else {
                sbs.append("<Msg/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * S60线上复诊 MS02017套餐选择接口
     *
     * @param bz_code
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray MS02017(String bz_code, String tc_no, String flag, boolean demoFlag) throws Exception {
        String fid = "MS02017";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum>");
            if (StringUtils.isNotBlank(bz_code) || StringUtils.isNotBlank(tc_no)) {
                sbs.append("<Msg>");
                if (StringUtils.isNotBlank(bz_code)) {
                    sbs.append(" and bz_code = '" + bz_code + "' ");
                }
                if (StringUtils.isNotBlank(tc_no)) {
                    sbs.append(" and tc_no = '" + tc_no + "' ");
                }
                sbs.append("</Msg>");
            } else {
                sbs.append("<Msg/>");
            }
            sbs.append("<FLAG>" + flag + "</FLAG>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * S60线上复诊 MS02016主项目绑定子项目字典接口
     *
     * @param zd_charge_code
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray MS02016(String zd_charge_code, boolean demoFlag) throws Exception {
        String fid = "MS02016";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum>");
            if (StringUtils.isNotBlank(zd_charge_code)) {
                sbs.append("<Msg>and zd_charge_code = '" + zd_charge_code + "'</Msg>");
            } else {
                sbs.append("<Msg/>");
            }
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 同步医生信息
     *
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public int sysDoctorInfo(String docIdCard, boolean demoFlag) throws Exception {
        int i = 0;
        String fid = "MS02003";
        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");

            StringBuffer condition = new StringBuffer();
            if (StringUtils.isNoneBlank(docIdCard)){
                condition.append("<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><root><resquest Card_Id=\""+docIdCard+"\" ></resquest></root>]]>");
            }
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>10000</endNum><Msg>"+condition+"</Msg><startNum>1</startNum></MsgInfo></ESBEntry>");

            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRowMS02003(resp);
        }
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(resp);
        if (null != jsonObject && "1".equals(jsonObject.get("code").toString())) {
            JSONArray jsonObjectMgsInfo = (JSONArray) jsonObject.get("MsgInfo");
            if (null != jsonObjectMgsInfo) {
                for (Object object : jsonObjectMgsInfo) {
                    JSONArray jsonArray = JSONArray.fromObject(object);
                    net.sf.json.JSONObject jsonArraySub = jsonArray.getJSONObject(0);
//                    net.sf.json.JSONObject jsonArraySub = (net.sf.json.JSONObject) object;
                    jsonObjectMgsInfo = (JSONArray) jsonArraySub.get("body");
                    if (jsonObjectMgsInfo instanceof JSONArray) {
                        for (Object objectSub : jsonObjectMgsInfo) {
                            net.sf.json.JSONObject jsonObjectBody = (net.sf.json.JSONObject) objectSub;
                            String doctorCode = "";
                            String doctorName = "";
                            if (null != jsonObjectBody) {
                                //获取中山医院的医生
                                String winNo = "6";
                                doctorCode = null == jsonObjectBody.get("Emp_Code") ? "" : jsonObjectBody.get("Emp_Code").toString();
                                //根据医生及分部，获取医生号别
                                /*net.sf.json.JSONArray jsonArrayCharge = BS55010(winNo, doctorCode, null, false);
                                String chareType = null;
                                if (null != jsonArrayCharge) {
                                    for (Object objectCharge : jsonArrayCharge) {
                                        net.sf.json.JSONObject jsonObjectBodyCharge = (net.sf.json.JSONObject) objectCharge;
                                        if (null != jsonObjectBodyCharge) {
                                            chareType = null == jsonObjectBodyCharge.get("charge_type") ? null : jsonObjectBodyCharge.get("charge_type").toString();
                                        }
                                    }
                                }*/
                                //保存医生信息
                                BaseDoctorDO baseDoctorDO = new BaseDoctorDO();
                                String idCard = null == jsonObjectBody.get("Card_Id") ? "" : jsonObjectBody.get("Card_Id").toString();
                                String[] doctorIdcards = docIdCard.split(",");
                                String docIdCardOne ="";
                                for (int j =0 ;j<doctorIdcards.length;j++){
                                    docIdCardOne = doctorIdcards[j];
                                //同步单条信息
                                if (docIdCardOne.equalsIgnoreCase(idCard)) {

                                    baseDoctorDO.setIdcard(idCard);
                                    baseDoctorDO.setBirthday(IdCardUtil.getBirthdayForIdcard(idCard));
                                    baseDoctorDO.setSex(Integer.valueOf(IdCardUtil.getSexForIdcard(idCard)));
                                    baseDoctorDO.setLocked(0);
                                    baseDoctorDO.setEnabled(1);
                                    //拼音码
                                    baseDoctorDO.setSpell(null == jsonObjectBody.get("PinYin_Code") ? "" : jsonObjectBody.get("PinYin_Code").toString());
                                    String disableFlag = null == jsonObjectBody.get("Disable_Flag") ? "" : jsonObjectBody.get("Disable_Flag").toString();
                                    //互联网医院：1停用，0使用  转 i健康：1正常，0作废
                                    baseDoctorDO.setDel("1".equals(disableFlag) ? "0" : "1");
                                    //姓名
                                    doctorName = null == jsonObjectBody.get("Emp_Name") ? "" : jsonObjectBody.get("Emp_Name").toString();
                                    //号别
                                    baseDoctorDO.setChargeType("32");
                                    if (StringUtils.isNotBlank(idCard)) {
                                        baseDoctorDO.setSalt(PwdUtil.randomString(5));
                                        try {
                                            baseDoctorDO.setPassword(com.yihu.utils.security.MD5.md5Hex(baseDoctorDO.getIdcard().substring(baseDoctorDO.getIdcard().length() - 6) + "{" + baseDoctorDO.getSalt() + "}"));
                                        } catch (Exception e) {
                                            logger.error(e.getMessage() + "docotr=" + doctorCode + ";idcard=" + baseDoctorDO.getIdcard());
                                        }
                                    } else {
                                        baseDoctorDO.setPassword(com.yihu.utils.security.MD5.md5Hex("123456" + "{" + baseDoctorDO.getSalt() + "}"));
                                    }
                                    baseDoctorDO.setName(doctorName);
                                    baseDoctorDO.setIsFamous(0);
                                    baseDoctorDO.setCreateTime(new Date());
                                    baseDoctorDO.setUpdateTime(new Date());
                                    baseDoctorDO.setMobile("0");
                                    baseDoctorDO = baseDoctorDao.save(baseDoctorDO);
                                    //根据医生和机构判断数据是否存在，若不存在则在mapping中追加记录
                                    List<DoctorMappingDO> doctorMappingDOS = doctorMappingDao.findByDoctorAndOrgCode(baseDoctorDO.getId(), "350211A1002");
                                    if (!(null != doctorMappingDOS && doctorMappingDOS.size() > 0)) {
                                        DoctorMappingDO doctorMappingDO = new DoctorMappingDO();
                                        doctorMappingDO.setDoctor(baseDoctorDO.getId());
                                        doctorMappingDO.setDoctorName(doctorName);
                                        doctorMappingDO.setMappingCode(doctorCode);
                                        doctorMappingDO.setMappingName(doctorName);
                                        doctorMappingDO.setOrgCode("350211A1002");
                                        doctorMappingDO.setOrgName("厦门大学附属中山医院");
                                        doctorMappingDao.save(doctorMappingDO);
                                    }
                                    // 用医生和机构id、部门判断数据是否存在，若不存在则保存医生机构关联关系
                                    String deptCode = null == jsonObjectBody.get("Dept_Code") ? "" : jsonObjectBody.get("Dept_Code").toString();
                                    List<BaseDoctorHospitalDO> baseDoctorHospitalDOS = baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode("350211A1002", deptCode, baseDoctorDO.getId());
                                    if (!(null != baseDoctorHospitalDOS && baseDoctorHospitalDOS.size() > 0)) {
                                        BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                                        baseDoctorHospitalDO.setOrgCode("350211A1002");
                                        baseDoctorHospitalDO.setOrgName("厦门大学附属中山医院");
                                        baseDoctorHospitalDO.setDoctorCode(baseDoctorDO.getId());
                                        baseDoctorHospitalDO.setDeptCode(deptCode);
                                        //根据机构编码获取机构名称
                                        List<DictHospitalDeptDO> dictHospitalDeptDOS = dictHospitalDeptDao.findByOrgCodeAndCode("350211A1002", deptCode);
                                        if (null != dictHospitalDeptDOS && dictHospitalDeptDOS.size() > 0) {
                                            DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDOS.get(0);
                                            baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                                        }
                                        baseDoctorHospitalDO.setDel("1");
                                        baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                                    }
                                    BaseDoctorRoleDO roleList = baseDoctorRoleDao.findByDoctorCodeAndroleCode(baseDoctorDO.getId(), "specialist");
                                    if (roleList == null) {
                                        roleList = new BaseDoctorRoleDO();
                                        roleList.setDoctorCode(baseDoctorDO.getId());
                                        roleList.setRoleCode("specialist");
                                        baseDoctorRoleDao.save(roleList);
                                    }
                                    i++;
                                }
                                }
                            }
                        }
                    }
                }
            }
        }


        return i;
    }

    /**
     * 建立档案
     *
     * @param archiveVO
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject BS16018(ArchiveVO archiveVO, boolean demoFlag) throws Exception {
        String fid = "BS16018";
        logger.info(" BS16018 begin");

        String resp = "";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            sbs.append("<MsgInfo>");
            sbs.append("<endNum>20000</endNum>");
            sbs.append("<Msg>");
            sbs.append("<root>");
            sbs.append("<request ");
            if (StringUtils.isNotBlank(archiveVO.getId0000())) {
                sbs.append(" id0000=\"" + archiveVO.getId0000() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getCardno())) {
                sbs.append(" cardno=\"" + archiveVO.getCardno() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getXming0())) {
                sbs.append(" xming0=\"" + archiveVO.getXming0() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getSfzhao())) {
                sbs.append(" sfzhao=\"" + archiveVO.getSfzhao() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getXbie00())) {
                sbs.append(" xbie00=\"" + archiveVO.getXbie00() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getBrnl00())) {
                sbs.append(" brnl00=\"" + archiveVO.getBrnl00() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getYytel0())) {
                sbs.append(" yytel0=\"" + archiveVO.getYytel0() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getCsrq00())) {
                sbs.append(" csrq00=\"" + archiveVO.getCsrq00() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getBjjbie())) {
                sbs.append(" bjjbie=\"" + archiveVO.getBjjbie() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getCardtype())) {
                sbs.append(" cardtype=\"" + archiveVO.getCardtype() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getGuid00())) {
                sbs.append(" guid00=\"" + archiveVO.getGuid00() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getGrsfen())) {
                sbs.append(" grsfen=\"" + archiveVO.getGrsfen() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getAddres())) {
                sbs.append(" addres=\"" + archiveVO.getAddres() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getSmdj00())) {
                sbs.append(" smdj00=\"" + archiveVO.getSmdj00() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getEhealthCardId())) {
                sbs.append(" ehealth_card_id=\"" + archiveVO.getEhealthCardId() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getMindexId())) {
                sbs.append(" mindex_id=\"" + archiveVO.getMindexId() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getSmkId())) {
                sbs.append(" smk_id=\"" + archiveVO.getSmkId() + "\" ");
            }
            if (StringUtils.isNotBlank(archiveVO.getFwqd00())) {
                sbs.append(" fwqd00=\"" + archiveVO.getFwqd00() + "\" ");
            }
            sbs.append(" />");
            sbs.append("</root>");
            sbs.append("</Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");

            //查询信息拼接{"cardno":"DA9549295","xming0":"侯颖龙","sfzhao":"350583199510282220","xbie00":"2","yytel0":"18859250126","grsfen":"2","addres":"","brnl00":"25","csrq00":"19951028"}
            // {"code":"1","MsgInfo":[{"resquest":{"@ans_code":"00","@msg":"该卡已注册"}}]}
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid + " resp:" + resp);
        }
        return ConvertUtil.convertListEnvelopInRequest(resp);
    }


    /**
     * 获取居民基本信息
     *
     * @param idcard    身份证
     * @param patientId his 居民ID
     * @param admitNum  就诊次数
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS10008(String idcard,String patientName,String phoneNum, String patientId, String admitNum, String ybcard, boolean demoFlag) throws Exception {
        String fid = "BS10008";
        String resp = "";
        if (demoFlag) {
            //resp="{\"code\":\"1\",\"MsgInfo\":{\"body\":{\"row\":{\"action\":\"select\",\"Patient_Id\":\"P11887289-0\",\"Pat_Admit_ID\":[],\"Admit_Num\":\"6\",\"Mailing_Address\":[],\"Zip_Code\":[],\"Phone_Number_Home\":\"18841409773\",\"Id_Card\":\"350104198911274422\",\"Pat_Name\":\"林莹\",\"Sex_Code\":[],\"Sex\":\"2\",\"Birth_Date\":\"1989-11-27\",\"Nation_Code\":[],\"Nation\":[],\"Birth_Place\":[],\"Citizenship_Code\":[],\"Citizenship\":[],\"age\":[],\"Occupation_Code\":[],\"Occupation\":[],\"Attend_Dr_Code\":[],\"Attend_Dr_Name\":[],\"Current_Bed_No\":[],\"Current_Bed_Name\":[],\"Current_Ward_Code\":[],\"Current_Ward_Name\":[],\"Current_Dept_Code\":[],\"Current_Dept_Name\":[],\"Relationship\":[],\"Next_Of_Kin_Zip_Code\":[],\"Next_Of_Kin_Phone\":[],\"Next_Of_Kin\":[],\"Next_Of_Kin_Addr\":[],\"Name_Phinetic\":\"00\",\"Identity\":[],\"Charge_Type\":\"00\",\"Charge_Type_Name\":\"自费\",\"Phone_Number_Business\":\"18301430062\",\"Last_Visit_Date\":\"2020-07-14\",\"VIP_Indicator\":\"0\",\"Create_Date\":[],\"In_Hospital_Indicator\":[],\"Exchange_Indicator\":[],\"Create_System\":[],\"Operator\":\"8644\",\"ybcard\":\"1D51992174\",\"card_status\":\"1\",\"remain_money\":\"0.00\",\"index_no\":\"1056122677166878720\"}}}}";
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>" + mqUser + "</UserName><Password>" + mqPwd + "</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>" + sourceSysCode + "</SourceSysCode><TargetSysCode>" + targetSysCode + "</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum>");
            sbs.append("<Msg>");
            if (StringUtils.isNotBlank(idcard)) {
                sbs.append(" and Id_Card = '" + idcard + "' ");
            }
            if (StringUtils.isNotBlank(patientId)) {
                sbs.append(" and Patient_Id = '" + patientId + "' ");
            }
            if (StringUtils.isNotBlank(phoneNum)) {
                sbs.append(" and Phone_Number_Business = '" + phoneNum + "' ");
            }
            if (StringUtils.isNotBlank(patientName)) {
                sbs.append(" and Pat_Name = '" + patientName + "' ");
            }
            if (StringUtils.isNotBlank(ybcard)) {
                sbs.append(" and ybcard = '" + ybcard + "' ");
            }
            sbs.append("</Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    public JSONArray getMS02001(boolean demoFlag) throws Exception {
        String fid=MS02001;
        String resp="";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>"+mqUser+"</UserName><Password>"+mqPwd+"</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>"+sourceSysCode+"</SourceSysCode><TargetSysCode>"+targetSysCode+"</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>1000</endNum><Msg></Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBody(resp);
    }

//=====================hospital应用调用entrance应用============start=================

    /**
     * 医生信息同步
     * @return
     * @throws Exception
     */
    public Integer syncMS02003() throws Exception {
        String response="";
        String url = entranceUrl+"MS02003";
        response = httpClientUtil.get(url,"GBK");
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(response);
        if(object.getInteger("status")==200){
            String obj = object.getString("obj");
        }
        return object.getInteger("status");
    }

    /**
     * 医生简介同步
     * @return
     * @throws Exception
     */
    public Integer syncBS16010() throws Exception {
        String response="";
        String doctorCode="";
        String url = entranceUrl+"BS16010?doctorCode="+doctorCode;
        response = httpClientUtil.get(url,"GBK");
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(response);
        if(object.getInteger("status")==200){
            String obj = object.getString("obj");
        }
        return object.getInteger("status");
    }

    /**
     * 科室简介同步
     * @return
     * @throws Exception
     */
    public Integer syncBS16011() throws Exception {
        String response="";
        String depNumber="";
        String url = entranceUrl+"BS16011?depNumber="+depNumber;
        response = httpClientUtil.get(url,"GBK");
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(response);
        if(object.getInteger("status")==200){
            String obj = object.getString("obj");
        }
        return object.getInteger("status");
    }

    /**
     * 同步医生信息
     * @return
     * @throws Exception
     */
    public Integer syncDoctorInfo() throws Exception {
        String response="";
        String idcard="";
        String url = entranceUrl+"sysDoctorInfo?idcard="+idcard;
        response = httpClientUtil.get(url,"GBK");
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(response);
        if(object.getInteger("status")==200){
            String obj = object.getString("obj");
        }
        return object.getInteger("status");
    }

//=====================hospital应用调用entrance应用============end=================


/*
    *
     * 请求海康接口方法
     * @param method
     * @param type
     * @param xmlStr
     * @return
     * @throws Exception
    public String sendHaiTaiMethod(String method,String type,String xmlStr) throws Exception {
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO!=null){
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        if (!StringUtils.isNoneBlank(url)){
            throw new Exception("url 不存在！");
        }
        logger.info("请求参数：method"+method+"==type"+type+"==="+xmlStr);
        String result = null;
        try {
            org.apache.axis.client.Service service = new org.apache.axis.client.Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new URL(url));
            call.setOperationName(new QName(url, method)); // 设置要调用哪个方法
            call.addParameter("type", XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter("xmlStr",XMLType.XSD_STRING, ParameterMode.IN);
            call.setReturnType(XMLType.XSD_STRING);
            String xml = (String)call.invoke(new Object[]{type,xmlStr});
            logger.info("返回值："+xml);
            XMLSerializer xmlSerializer = new XMLSerializer();
            result = xmlSerializer.read(xml).toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
*/
    //中山消息中心通用接口
    public String zsMsgFlow(String visitId,String msgId,String idType,String idNo,String patientName,
                            String msgTime,String msgType,String msgContent,String jumpType
                                ,String jumpUrl,String miniAppId,String miniAppUrl,String remark,String sender) throws Exception{
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("zsMsgFlowUrl");
        String url = "";
        String pyCode=null;
        if (wlyyHospitalSysDictDO!=null){
            url = wlyyHospitalSysDictDO.getDictValue();
            pyCode=wlyyHospitalSysDictDO.getPyCode();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("visitId",visitId);
        jsonObject.put("msgId",msgId);
        jsonObject.put("idType",idType);
        jsonObject.put("idNo",idNo);
        jsonObject.put("patientName",patientName);
        jsonObject.put("msgTime",msgTime);
        jsonObject.put("msgType",msgType);
        jsonObject.put("msgContent",msgContent);
        jsonObject.put("jumpType",jumpType);
        jsonObject.put("jumpUrl",jumpUrl);
        jsonObject.put("miniAppId",miniAppId);
        jsonObject.put("miniAppUrl",miniAppUrl);
        jsonObject.put("remark",remark);
        jsonObject.put("sender",sender);
        String response="";
        logger.info("消息中心入参=="+jsonObject.toString());
        logger.info("url"+url);
        try {
            if (StringUtils.isNoneBlank(pyCode)&&pyCode.equalsIgnoreCase("1")){
                response =  httpClientUtil.postBody(url,jsonObject);
                logger.info("response"+response);
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(response);
                //{"code":200,"message":"SUCCESS","data":null}
                WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
                wlyyHttpLogDO.setRequest(jsonObject.toString());
                wlyyHttpLogDO.setResponse(response);
                wlyyHttpLogDO.setName(remark+"url=="+url);
                wlyyHttpLogDO.setCreateTime(new Date());
                wlyyHttpLogDao.save(wlyyHttpLogDO);
                if(object.getInteger("code")==200){
                    String message = object.getString("message");
                    return message;
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public String zsMsgFlowEntrance(String jsonData,String url){
        logger.info("消息中心入参==="+jsonData+"=====url"+url);
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        logger.info("jsonObject==="+jsonObject.toString());
        try {
            String res =  httpClientUtil.postBody(url,jsonObject);
            logger.info("res=="+res);
            return res;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }


}
