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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.entity.hospital.prescription.BaseNatAppointmentDO;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.hospital.prescription.dao.BaseNatAppointmentDao;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.WebserviceUtil;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
import com.yihu.utils.date.DateUtil;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class TasyNatService {
    private static Logger logger = LoggerFactory.getLogger(TasyNatService.class);
    private static String operator="健康之路";
    private static String key="1";
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private WlyyHttpLogDao wlyyHttpLogDao;
    @Autowired
    private BasePatientWechatDao basePatientWechatDao;
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private BaseNatAppointmentDao baseNatAppointmentDao;
    @Autowired
    private BusinessOrderDao businessOrderDao;

    public String getOperateUrl(){

        List<WlyyHospitalSysDictDO> list =  wlyyHospitalSysDictDao.findByDictName("TasyWebOperateService");

        String url = list.get(0).getDictCode();
        return url;
    }
    public String gethsQueryDataWS(){

        List<WlyyHospitalSysDictDO> list =  wlyyHospitalSysDictDao.findByDictName("hdrQueryDataWSUrl");

        String url = list.get(0).getDictCode();
        return url;
    }
    public String getTaszWebServiceInfo(String api, Map<String,String> params, String url)throws Exception{

        logger.info("url"+url);

        List<WlyyHospitalSysDictDO> xzzxNamespaces =  wlyyHospitalSysDictDao.findByDictName("TasyNamespace");

        String xzzxNamespace = xzzxNamespaces.get(0).getDictCode();

        logger.info("TasyNamespace",xzzxNamespace);

        return WebserviceUtil.post(url,xzzxNamespace,api,params);
    }


    /**
     * 线上注册
     * @return
     */
    public String registerPatient(JSONObject jsonObject)throws Exception{
        String api = "SickNocardRegister";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        if (StringUtils.isNoneBlank(jsonObject.getString("IdType"))){
            condition += "<IdType>"+jsonObject.getString("IdType")+"</IdType>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("IdNo"))){
            condition += "<IdNo>"+jsonObject.getString("IdNo")+"</IdNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("UserName"))){
            condition += "<UserName>"+jsonObject.getString("UserName")+"</UserName>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("UserSex"))){
            condition += "<UserSex>"+jsonObject.getString("UserSex")+"</UserSex>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("MobilePhone"))){
            condition += "<MobilePhone>"+jsonObject.getString("MobilePhone")+"</MobilePhone>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("Birthday"))){
            condition += "<Birthday>"+jsonObject.getString("Birthday")+"</Birthday>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("Address "))){
            condition += "<Address >"+jsonObject.getString("Address ")+"</Address >";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("WorkUnit"))){
            condition += "<WorkUnit>"+jsonObject.getString("WorkUnit")+"</WorkUnit>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("CardType"))){
            condition += "<CardType>"+jsonObject.getString("CardType")+"</CardType>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("CardNo"))){
            condition += "<CardNo>"+jsonObject.getString("CardNo")+"</CardNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("Citizen"))){
            condition += "<Citizen>"+jsonObject.getString("Citizen")+"</Citizen>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("BirthPlace"))){
            condition += "<BirthPlace>"+jsonObject.getString("BirthPlace")+"</BirthPlace>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("MaritalStatus"))){
            condition += "<MaritalStatus>"+jsonObject.getString("MaritalStatus")+"</MaritalStatus>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("UnitPhone"))){
            condition += "<UnitPhone>"+jsonObject.getString("UnitPhone")+"</UnitPhone>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("Email"))){
            condition += "<Email>"+jsonObject.getString("Email")+"</Email>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("Community"))){
            condition += "<Community>"+jsonObject.getString("Community")+"</Community>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ContactName"))){
            condition += "<ContactName>"+jsonObject.getString("ContactName")+"</ContactName>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ContactRelation"))){
            condition += "<ContactRelation>"+jsonObject.getString("ContactRelation")+"</ContactRelation>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ContactPhone"))){
            condition += "<ContactPhone>"+jsonObject.getString("ContactPhone")+"</ContactPhone>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ContactAddress"))){
            condition += "<ContactAddress>"+jsonObject.getString("ContactAddress")+"</ContactAddress>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("Id000"))){
            condition += "<Id000>"+jsonObject.getString("Id000")+"</Id000>";
        }

        String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<root>"+condition+"</root>";

        Map<String,String> params = new HashedMap();
        params.put("msgHeader",msgHeader);
        params.put("msgBody",msgBody);
        logger.info("registerPatient params:"+params.toString());
        String xml = getTaszWebServiceInfo("CallInterface",params,getOperateUrl());
        /*xml= xml.replace("<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
        xml= xml.replace("]]>","");*/
        xml=xml.substring(xml.indexOf("<root>"),xml.lastIndexOf("]]"));
        System.out.println(xml);
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        logger.info("registerPatient json:"+json);
        return json;
    }
    /**
     * 挂号+项目开单
     * @return
     */
    public String insertNucleicBill(JSONObject jsonObject)throws Exception{
        String api = "insertNucleicBill";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        if (StringUtils.isNoneBlank(jsonObject.getString("deptCode"))){
            condition += "<deptCode>"+jsonObject.getString("deptCode")+"</deptCode>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("staffNo"))){
            condition += "<staffNo>"+jsonObject.getString("staffNo")+"</staffNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("preNo"))){
            condition += "<preNo>"+jsonObject.getString("preNo")+"</preNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("icCardNo"))){
            condition += "<icCardNo>"+jsonObject.getString("icCardNo")+"</icCardNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("patientName"))){
            condition += "<patientName>"+jsonObject.getString("patientName")+"</patientName>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("registerFee"))){
            condition += "<registerFee>"+jsonObject.getString("registerFee")+"</registerFee>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("clinicFee"))){
            condition += "<clinicFee>"+jsonObject.getString("clinicFee")+"</clinicFee>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("address_now"))){
            condition += "<address_now>"+jsonObject.getString("address_now")+"</address_now>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ncp_standing_type"))){
            condition += "<ncp_standing_type>"+jsonObject.getString("ncp_standing_type")+"</ncp_standing_type>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ncp_profession"))){
            condition += "<ncp_profession>"+jsonObject.getString("ncp_profession")+"</ncp_profession>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("ncp_profession_sub"))){
            condition += "<ncp_profession_sub>"+jsonObject.getString("ncp_profession_sub")+"</ncp_profession_sub>";
        }
        String itemCoditon="";
        if (StringUtils.isNoneBlank(jsonObject.getString("item"))){
            JSONObject itemObject=jsonObject.getJSONObject("item");
            if (StringUtils.isNoneBlank(itemObject.getString("itemCode"))){
                itemCoditon += "<itemCode>"+itemObject.getString("itemCode")+"</itemCode>";
            }
            if (StringUtils.isNoneBlank(itemObject.getString("itemName"))){
                itemCoditon += "<itemName>"+itemObject.getString("itemName")+"</itemName>";
            }
            if (StringUtils.isNoneBlank(itemObject.getString("itemPrice"))){
                itemCoditon += "<itemPrice>"+itemCoditon+"</itemPrice>";
            }
            condition += "<itemList><item>"+itemCoditon+"</item></itemList>";
        }
        String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<root>"+condition+"</root>";

        Map<String,String> params = new HashedMap();
        params.put("msgHeader",msgHeader);
        params.put("msgBody",msgBody);
        logger.info("insertNucleicBill params:"+params.toString());
        String xml = getTaszWebServiceInfo("CallInterface",params,getOperateUrl());
        /*xml= xml.replace("<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
        xml= xml.replace("]]>","");*/
        xml=xml.substring(xml.indexOf("<root>"),xml.lastIndexOf("]]"));
        System.out.println(xml);
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        logger.info("insertNucleicBill json:"+json);
        return json;
    }
    /**
     * 取消核酸预约
     * @return
     */
    public String cancelNucleicBill(JSONObject jsonObject)throws Exception{
        String api = "cancelNucleicBill";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        if (StringUtils.isNoneBlank(jsonObject.getString("hisTradeNo"))){
            condition += "<hisTradeNo>"+jsonObject.getString("hisTradeNo")+"</hisTradeNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("icCardNo"))){
            condition += "<icCardNo>"+jsonObject.getString("icCardNo")+"</icCardNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("patientName"))){
            condition += "<patientName>"+jsonObject.getString("patientName")+"</patientName>";
        }

        String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<root>"+condition+"</root>";

        Map<String,String> params = new HashedMap();
        params.put("msgHeader",msgHeader);
        params.put("msgBody",msgBody);
        logger.info("cancelNucleicBill params:"+params.toString());
        String xml = getTaszWebServiceInfo("CallInterface",params,getOperateUrl());
        /*xml= xml.replace("<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
        xml= xml.replace("]]>","");*/
        xml=xml.substring(xml.indexOf("<root>"),xml.lastIndexOf("]]"));
        System.out.println(xml);
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        logger.info("cancelNucleicBill json:"+json);
        return json;
    }

    /**
     * 核酸检测项目扣费
     * @return
     */
    public String ChargenucleicBill(JSONObject jsonObject)throws Exception{
        String api = "ChargenucleicBill";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        if (StringUtils.isNoneBlank(jsonObject.getString("hisTradeNo"))){
            condition += "<hisTradeNo>"+jsonObject.getString("hisTradeNo")+"</hisTradeNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("icCardNo"))){
            condition += "<icCardNo>"+jsonObject.getString("icCardNo")+"</icCardNo>";
        }
        if (StringUtils.isNoneBlank(jsonObject.getString("patientName"))){
            condition += "<patientName>"+jsonObject.getString("patientName")+"</patientName>";
        }

        String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<root>"+condition+"</root>";

        Map<String,String> params = new HashedMap();
        params.put("msgHeader",msgHeader);
        params.put("msgBody",msgBody);
        logger.info("ChargenucleicBill params:"+params.toString());
        String xml = getTaszWebServiceInfo("CallInterface",params,getOperateUrl());
        xml=xml.substring(xml.indexOf("<root>"),xml.lastIndexOf("]]"));
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        saveHttpLog("ChargenucleicBill",jsonObject.toString(),json,"ChargenucleicBill");
        logger.info("ChargenucleicBill json:"+json);
        return json;
    }

    //组装核算下单参数
    public String initNatParams(String preNo,String patientName,String icCardNo,String address,String job,String jobChild){
        List<WlyyHospitalSysDictDO> natConfigList = wlyyHospitalSysDictDao.findByDictName("natConfigList");
        String deptCode = "0001";
        String staffNo = "0001";
        String registerFee = "0.01";
        String clinicFee = "0.01";
        String itemCode = "xmCode";
        String itemName = "核酸检测";
        String itemPrice = "0.01";
        String ncpStandingType="";
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:natConfigList){
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"deptCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                deptCode = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"staffNo".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                staffNo = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"registerFee".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                registerFee = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"clinicFee".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                clinicFee = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"itemCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                itemCode = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"itemName".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                itemName = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"itemPrice".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                itemPrice = wlyyHospitalSysDictDO.getDictValue();
            }
            if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"ncp_standing_type".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                ncpStandingType = wlyyHospitalSysDictDO.getDictValue();
            }
        }
        JSONObject jsonObject = new JSONObject();
        //jsonObject.put("preNo",preNo);
        jsonObject.put("icCardNo",icCardNo);
        jsonObject.put("patientName",patientName);
        jsonObject.put("deptCode",deptCode);
        jsonObject.put("staffNo",staffNo);
        jsonObject.put("registerFee",registerFee);
        jsonObject.put("clinicFee",clinicFee);
        jsonObject.put("ncp_profession_sub",jobChild);
        jsonObject.put("address_now",address);
        jsonObject.put("ncp_profession",job);
        jsonObject.put("ncp_standing_type",ncpStandingType);
        JSONObject item = new JSONObject();
        item.put("itemCode",itemCode);
        item.put("itemName",itemName);
        item.put("itemPrice",itemPrice);
        jsonObject.put("item",item);
        String res="";
        try {
            res = insertNucleicBill(jsonObject);
            saveHttpLog("insertNucleicBill",jsonObject.toString(),res,"insertNucleicBill");
            if (StringUtils.isNoneBlank(res)){
                return res;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return "";
    }
    //调用取消核酸接口
    public String cancelNat(String hisTraceNo,String idCardNo,String patientName){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hisTradeNo",hisTraceNo);
        jsonObject.put("icCardNo",idCardNo);
        jsonObject.put("patientName",patientName);
        String res="";
        try {
            res = cancelNucleicBill(jsonObject);
            saveHttpLog("cancelNat",jsonObject.toString(),res,"cancelNat");
            if (StringUtils.isNoneBlank(res)){
                return res;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    //调用扣费接口
    public String chargeBill(String hisTraceNo,String idCardNo,String patientName){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hisTraceNo",hisTraceNo);
        jsonObject.put("idCardNo",idCardNo);
        jsonObject.put("patientName",patientName);
        String res="";
        try {
            res = ChargenucleicBill(jsonObject);
            saveHttpLog("chargeBill",jsonObject.toString(),res,"chargeBill");
            if (StringUtils.isNoneBlank(res)){
                return res;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
//Integer payType,String tradeNo,String openId,String idNo,String name ,String amountJSONObject jsonObject = new JSONObject();
//        jsonObject.put("payType",payType);
//        jsonObject.put("tradeNo",tradeNo);
//        jsonObject.put("openId",openId);
//        jsonObject.put("idNo",idNo);
//        jsonObject.put("name",name);
//        jsonObject.put("amount",amount);
    public String placeOrder(JSONObject jsonObject){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("placeOrderUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        System.out.println(url);
        /*List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("payType", jsonObject.getString("payType")));
        params.add(new BasicNameValuePair("tradeNo", jsonObject.getString("tradeNo")));
        params.add(new BasicNameValuePair("openId", jsonObject.getString("openId")));
        params.add(new BasicNameValuePair("name", jsonObject.getString("name")));
        params.add(new BasicNameValuePair("idNo", jsonObject.getString("idNo")));
        params.add(new BasicNameValuePair("amount", jsonObject.getString("amount")));*/
        System.out.println(jsonObject.toString());
        String response = httpClientUtil.postBody(url,jsonObject);
        System.out.println("res"+response);
        saveHttpLog("placeOrder",jsonObject.toString(),response,url);
        return response;
    }

    public String orderStatus(JSONObject jsonObject){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("orderStatusUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        System.out.println(url);
        String response = httpClientUtil.postBody(url,jsonObject);
        System.out.println("res"+response);
        saveHttpLog("orderStatus",jsonObject.toString(),response,url);
        return response;
    }

    public String tmpPush(JSONObject jsonObject){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("tmpPushUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        System.out.println(url);
        String response = httpClientUtil.postBody(url,jsonObject);
        System.out.println("res"+response);
        saveHttpLog("tmpPush",jsonObject.toString(),response,url);
        return response;
    }
    public void  saveHttpLog(String name,String req,String res,String code){
        WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
        wlyyHttpLogDO.setRequest(req);
        wlyyHttpLogDO.setName(name);
        //wlyyHttpLogDO.setCode(code);
        wlyyHttpLogDO.setCreateTime(new Date());
        wlyyHttpLogDO.setResponse(res);
        wlyyHttpLogDao.save(wlyyHttpLogDO);

    }
    public String sendWxtemplateMessaeg(String patient,String name,String scene,String relationCode){
        String url="";
        String openId="";
        JSONObject key=new JSONObject();
        JSONObject first=new JSONObject();
        JSONObject key1=new JSONObject();
        JSONObject key2=new JSONObject();
        JSONObject key3=new JSONObject();
        JSONObject key4=new JSONObject();
        JSONObject key5=new JSONObject();
        JSONObject remark=new JSONObject();
        BaseNatAppointmentDO baseNatAppointmentD0 = baseNatAppointmentDao.findOne(Integer.valueOf(relationCode));
        List<BasePatientWechatDo> basePatientWechatDo = basePatientWechatDao.findByWechatIdAndPatientId("xm_tasy_wx",patient);
        if (basePatientWechatDo!=null&&basePatientWechatDo.size()>0){
            openId=basePatientWechatDo.get(0).getOpenid();
        }
        if ("hszfcgtx".equalsIgnoreCase(scene)){
            //开始发送模板消息
            logger.info("开始发送模板消息");
            List<WxTemplateConfigDO> wxTemplateConfigDO = wxTemplateConfigDao.findByWechatIdAndScene("xm_tasy_wx",scene);
            WxTemplateConfigDO wxTemplateConfigDO1 = new WxTemplateConfigDO();
            if (wxTemplateConfigDO!=null&&wxTemplateConfigDO.size()>0){
                wxTemplateConfigDO1 = wxTemplateConfigDO.get(0);
            }
            url=wxTemplateConfigDO1.getUrl()+relationCode;
            first.put("value",wxTemplateConfigDO1.getFirst());
            first.put("color",wxTemplateConfigDO1.getKeyword6());
            key1.put("value",baseNatAppointmentD0.getDoctorName());
            key1.put("color",wxTemplateConfigDO1.getKeyword6());
            key2.put("value",baseNatAppointmentD0.getChargeAmount()+".00元");
            key2.put("color",wxTemplateConfigDO1.getKeyword6());
            key3.put("value",wxTemplateConfigDO1.getKeyword3());
            key3.put("color",wxTemplateConfigDO1.getKeyword6());
            key4.put("value",baseNatAppointmentD0.getChargeAmount()+".00元");
            key4.put("color",wxTemplateConfigDO1.getKeyword6());
            key5.put("value",baseNatAppointmentD0.getVoucherNo());
            key5.put("color",wxTemplateConfigDO1.getKeyword6());
            remark.put("value",wxTemplateConfigDO1.getRemark());
            remark.put("color",wxTemplateConfigDO1.getKeyword6());
            key.put("first",first);
            key.put("keyword1",key1);
            key.put("keyword2",key2);
            key.put("keyword3",key3);
            key.put("keyword4",key4);
            key.put("keyword5",key5);
            key.put("remark",remark);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("template_id",wxTemplateConfigDO1.getTemplateId());//
            jsonObject.put("data",key);
            jsonObject.put("touser",openId);
            jsonObject.put("url",url);
            logger.info("核酸检测支付成功模板消息推送param"+jsonObject.toString());
            String tmResilt= tmpPush(jsonObject);
            return tmResilt;
        } else if ("hszftx".equalsIgnoreCase(scene)) {
            //开始发送模板消息
            logger.info("开始发送模板消息");
            List<WxTemplateConfigDO> wxTemplateConfigDO = wxTemplateConfigDao.findByWechatIdAndScene("xm_tasy_wx",scene);
            WxTemplateConfigDO wxTemplateConfigDO1 = new WxTemplateConfigDO();
            if (wxTemplateConfigDO!=null&&wxTemplateConfigDO.size()>0){
                wxTemplateConfigDO1 = wxTemplateConfigDO.get(0);
            }
            url=wxTemplateConfigDO1.getUrl()+relationCode;
            first.put("value",wxTemplateConfigDO1.getFirst());
            first.put("color",wxTemplateConfigDO1.getKeyword6());
            key1.put("value",name);
            key1.put("color",wxTemplateConfigDO1.getKeyword6());
            key2.put("value",baseNatAppointmentD0.getDeptName());
            key2.put("color",wxTemplateConfigDO1.getKeyword6());
            key3.put("value",wxTemplateConfigDO1.getKeyword3());
            key3.put("color",wxTemplateConfigDO1.getKeyword6());
            key4.put("value",baseNatAppointmentD0.getDoctorName());
            key4.put("color",wxTemplateConfigDO1.getKeyword6());
            key5.put("value", DateUtil.formatDate(baseNatAppointmentD0.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            key5.put("color",wxTemplateConfigDO1.getKeyword6());
            remark.put("value",wxTemplateConfigDO1.getRemark());
            remark.put("color",wxTemplateConfigDO1.getKeyword6());
            key.put("first",first);
            key.put("keyword1",key1);
            key.put("keyword2",key2);
            key.put("keyword3",key3);
            key.put("keyword4",key4);
            key.put("keyword5",key5);
            key.put("remark",remark);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("template_id",wxTemplateConfigDO1.getTemplateId());//
            jsonObject.put("data",key);
            jsonObject.put("touser",openId);
            jsonObject.put("url",url);
            logger.info("核酸检测支付提醒模板消息推送param"+jsonObject.toString());
            String tmResilt= tmpPush(jsonObject);
            return tmResilt;
        } else if ("hsyycg".equalsIgnoreCase(scene)) {
            //开始发送模板消息
            logger.info("开始发送模板消息");
            List<WxTemplateConfigDO> wxTemplateConfigDO = wxTemplateConfigDao.findByWechatIdAndScene("xm_tasy_wx",scene);
            WxTemplateConfigDO wxTemplateConfigDO1 = new WxTemplateConfigDO();
            if (wxTemplateConfigDO!=null&&wxTemplateConfigDO.size()>0){
                wxTemplateConfigDO1 = wxTemplateConfigDO.get(0);
            }
            url=wxTemplateConfigDO1.getUrl()+relationCode;
            first.put("value",wxTemplateConfigDO1.getFirst().replace("key1",name));
            first.put("color",wxTemplateConfigDO1.getKeyword6());
            key1.put("value",name);
            key1.put("color",wxTemplateConfigDO1.getKeyword6());
            key2.put("value",baseNatAppointmentD0.getInspectionName());
            key2.put("color",wxTemplateConfigDO1.getKeyword6());
            key3.put("value",wxTemplateConfigDO1.getKeyword3());//DateUtil.formatDate(baseNatAppointmentD0.getAppointmentTime(),"yyyy-MM-dd")
            key3.put("color",wxTemplateConfigDO1.getKeyword6());
            key4.put("value",wxTemplateConfigDO1.getKeyword4());
            key4.put("color",wxTemplateConfigDO1.getKeyword6());
            remark.put("value",wxTemplateConfigDO1.getRemark());
            remark.put("color",wxTemplateConfigDO1.getKeyword6());
            key.put("first",first);
            key.put("keyword1",key1);
            key.put("keyword2",key2);
            key.put("keyword3",key3);
            key.put("keyword4",key4);
            key.put("remark",remark);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("template_id",wxTemplateConfigDO1.getTemplateId());//
            jsonObject.put("data",key);
            jsonObject.put("touser",openId);
            jsonObject.put("url",url);
            logger.info("核酸检测预约成功模板消息推送param"+jsonObject.toString());
            String tmResilt= tmpPush(jsonObject);
            return tmResilt;
        }
        return "";
    }
    //查询排班部门
    public String departMent(String ApplyType){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("DepartMentUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        url+="?ApplyType="+ApplyType;
        System.out.println(url);
        String response = httpClientUtil.get(url,"UTF-8");
        System.out.println("res"+response);
        saveHttpLog("departMent",ApplyType,response,url);
        return response;
    }
    //保存预约
    public String saveRegOrder(String DepartId,String OrderDate,String OrderTime,String OrderID,String HisID,String Tel,
                               String HisName,String ApplyType){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("saveNatOrderUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        url+="?DepartId="+DepartId+"&OrderDate="+OrderDate+"&OrderTime="+OrderTime+"&OrderID="+OrderID
                +"&HisID="+HisID+"&Tel="+Tel+"&HisName="+HisName+"&ApplyType="+ApplyType;
        System.out.println(url);
        String response = httpClientUtil.get(url,"UTF-8");
        System.out.println("res"+response);
        saveHttpLog("saveRegOrder",url,response,url);
        return response;
    }
    //取消预约
    public String cancleOrder(String HisID,String HisSeqNo,String OrderNumber) throws Exception{
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("CancleOrderUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        url+="?HisID="+HisID+"&HisSeqNo="+HisSeqNo+"&OrderNumber="+OrderNumber;
        System.out.println(url);

        String response = httpClientUtil.get(url,"UTF-8");
        System.out.println("res"+response);
        saveHttpLog("cancleOrder",url,response,url);
        return response;
    }
    //查询排班医生
    public String GetDoctorWorkDate(String ApplyType,String DepartId){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("GetDoctorWorkDateUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        url+="?ApplyType="+ApplyType+"&DepartId="+DepartId;
        System.out.println(url);
        String response = httpClientUtil.get(url,"UTF-8");
        System.out.println("res"+response);
        saveHttpLog("departMent",url,response,url);
        return response;
    }
    //预约查询
    public String GetOrderInfo(String HisID,String ApplyType){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("GetOrderInfoUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        url+="?ApplyType="+ApplyType+"&HisID="+HisID;
        System.out.println(url);
        String response = httpClientUtil.get(url,"UTF-8");
        System.out.println("res"+response);
        saveHttpLog("departMent",url,response,url);
        return response;
    }
    //获取号源
    public String GetOrderSource(String DepartId,String DoctorId,String QueryDate,String ApplyType,String IsAll,String QueryTime){
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("GetOrderSourceUrl");
        if (wlyyHospitalSysDictDO!=null){
            url=wlyyHospitalSysDictDO.getDictValue();
        }
        url+="?DepartId="+DepartId+"&DoctorId="+DoctorId+"&QueryDate="+QueryDate+"&ApplyType="+ApplyType+"&IsAll="+IsAll+"&QueryTime="+QueryTime;
        System.out.println(url);
        String response = httpClientUtil.get(url,"UTF-8");
        System.out.println("res"+response);
        saveHttpLog("GetOrderInfo",url,response,url);
        return response;
    }
    //查询患者就诊卡
    public String findHisPatientCard(String idcard) throws Exception{
        String api = "QuerySickInfo";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        if (StringUtils.isNoneBlank(idcard)){
            condition += "<IdNo>"+idcard+"</IdNo>";
            condition += "<IdType>100</IdType>";
        }

        String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<root>"+condition+"</root>";

        Map<String,String> params = new HashedMap();
        params.put("msgHeader",msgHeader);
        params.put("msgBody",msgBody);
        logger.info("QuerySickInfo params:"+params.toString());
        String xml = getTaszWebServiceInfo("CallInterface",params,getOperateUrl());
        xml=xml.substring(xml.indexOf("<root>"),xml.lastIndexOf("]]"));
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        logger.info("QuerySickInfo json:"+json);
        return json;
    }
    public JSONArray findPatientCard(String patient) throws Exception{
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        String idcard="";
        if (basePatientDO!=null){
            idcard=basePatientDO.getIdcard();
        }
        String res = findHisPatientCard(idcard);
        JSONArray jsonArray = new JSONArray();
        if (StringUtils.isNoneBlank(res)){
            JSONObject jsonObject = JSON.parseObject(res);
            jsonArray.add(jsonObject);
            return jsonArray;
        }
        return null;
    }
    //病人单据状态查询
    public String QueryApplyInfo(String nullahNumber) throws Exception{
        String api = "QueryApplyInfo";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        if (StringUtils.isNoneBlank(nullahNumber)){
            condition += "<NullahNumber>"+nullahNumber+"</NullahNumber>";
        }

        String msgBody ="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<root>"+condition+"</root>";

        Map<String,String> params = new HashedMap();
        params.put("msgHeader",msgHeader);
        params.put("msgBody",msgBody);
        logger.info("QueryApplyInfo params:"+params.toString());
        String xml = getTaszWebServiceInfo("CallInterface",params,getOperateUrl());
        xml=xml.substring(xml.indexOf("<root>"),xml.lastIndexOf("]]"));
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        logger.info("QueryApplyInfo json:"+json);
        return json;
    }

    public void savePayStatusByHis(String patientId) throws Exception {
        List<BaseNatAppointmentDO> baseNatAppointmentDOList = baseNatAppointmentDao.findByTasy(patientId);
        for (BaseNatAppointmentDO baseNatAppointmentDO:baseNatAppointmentDOList){
            System.out.println("baseNatAppointmentDO==="+baseNatAppointmentDO.getName());
                String res = QueryApplyInfo(baseNatAppointmentDO.getRealOrder());
                JSONObject jsonObject = JSON.parseObject(res);
                if (jsonObject!=null){
                    if (jsonObject.getString("ReturnCode").equalsIgnoreCase("1")){
                        String applyinfo = jsonObject.getString("applyinfo");
                        if (StringUtils.isNoneBlank(applyinfo)){
                            if (applyinfo.contains("[")){
                                JSONArray jsonArray = JSON.parseArray(applyinfo);
                                if (jsonArray!=null&&jsonArray.size()>0) {
                                    if (StringUtils.isNoneBlank(baseNatAppointmentDO.getVoucherNo())) {
                                        for (int i = 0; i < jsonArray.size(); i++) {
                                            JSONObject child = jsonArray.getJSONObject(i);
                                            System.out.println("数组" + child.getString("ApplyNo"));
                                            if (child.getString("ApplyNo").equalsIgnoreCase(baseNatAppointmentDO.getVoucherNo())) {
                                                if ("已扣费".equalsIgnoreCase(child.getString("Status"))) {
                                                    baseNatAppointmentDO.setPayStatus("1");
                                                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(baseNatAppointmentDO.getId().toString());
                                                    if (businessOrderDO != null) {
                                                        businessOrderDO.setStatus(1);
                                                        businessOrderDao.save(businessOrderDO);
                                                    }
                                                } else if ("已退费".equalsIgnoreCase(child.getString("Status"))) {
                                                    logger.info("进入退费订单同步");
                                                    baseNatAppointmentDO.setPayStatus("-1");
                                                    baseNatAppointmentDO.setIsSuccess("-1");
                                                    baseNatAppointmentDO.setCancelReson("患者本人线下取消");
                                                    baseNatAppointmentDO.setCancelTime(new Date());
                                                    baseNatAppointmentDO.setCancelBy(patientId);
                                                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(baseNatAppointmentDO.getId().toString());
                                                    if (businessOrderDO != null) {
                                                        businessOrderDO.setStatus(-1);
                                                        businessOrderDao.save(businessOrderDO);
                                                    }
                                                    //取消号源
                                                    //cancleOrder(baseNatAppointmentDO.getCardNo(),baseNatAppointmentDO.getRegisterNo(),baseNatAppointmentDO.getOderNum());
                                                }
                                                baseNatAppointmentDao.save(baseNatAppointmentDO);
                                            }
                                        }
                                    }else {
                                        JSONObject child = jsonArray.getJSONObject(jsonArray.size()-1);
                                        System.out.println("数组" + child.getString("ApplyNo"));
                                        if (child.getString("ApplyNo").equalsIgnoreCase(baseNatAppointmentDO.getVoucherNo())) {
                                            if ("已扣费".equalsIgnoreCase(child.getString("Status"))) {
                                                baseNatAppointmentDO.setPayStatus("1");
                                                BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(baseNatAppointmentDO.getId().toString());
                                                if (businessOrderDO != null) {
                                                    businessOrderDO.setStatus(1);
                                                    businessOrderDao.save(businessOrderDO);
                                                }
                                            } else if ("已退费".equalsIgnoreCase(child.getString("Status"))) {
                                                logger.info("进入退费订单同步");
                                                baseNatAppointmentDO.setPayStatus("-1");
                                                baseNatAppointmentDO.setIsSuccess("-1");
                                                baseNatAppointmentDO.setCancelReson("患者本人线下取消");
                                                baseNatAppointmentDO.setCancelTime(new Date());
                                                baseNatAppointmentDO.setCancelBy(patientId);
                                                BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(baseNatAppointmentDO.getId().toString());
                                                if (businessOrderDO != null) {
                                                    businessOrderDO.setStatus(-1);
                                                    businessOrderDao.save(businessOrderDO);
                                                }
                                                //取消号源
                                                //cancleOrder(baseNatAppointmentDO.getCardNo(),baseNatAppointmentDO.getRegisterNo(),baseNatAppointmentDO.getOderNum());
                                            }
                                            baseNatAppointmentDO.setVoucherNo(child.getString("ApplyNo"));
                                            baseNatAppointmentDao.save(baseNatAppointmentDO);
                                        }
                                    }
                                }
                            }else {
                                JSONObject jsonObject1 = JSONObject.parseObject(applyinfo);
                                System.out.println("单条"+jsonObject1.getString("ApplyNo"));
                                if ("已扣费".equalsIgnoreCase(jsonObject1.getString("Status"))){
                                    baseNatAppointmentDO.setPayStatus("1");
                                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(baseNatAppointmentDO.getId().toString());
                                    if (businessOrderDO!=null){
                                        businessOrderDO.setStatus(1);
                                        businessOrderDao.save(businessOrderDO);
                                    }
                                }else if ("已退费".equalsIgnoreCase(jsonObject1.getString("Status"))){
                                    logger.info("进入退费订单同步");
                                    baseNatAppointmentDO.setPayStatus("-1");
                                    baseNatAppointmentDO.setIsSuccess("-1");
                                    baseNatAppointmentDO.setCancelReson("患者本人线下取消");
                                    baseNatAppointmentDO.setCancelTime(new Date());
                                    baseNatAppointmentDO.setCancelBy(patientId);
                                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(baseNatAppointmentDO.getId().toString());
                                    if (businessOrderDO!=null){
                                        businessOrderDO.setStatus(-1);
                                        businessOrderDao.save(businessOrderDO);
                                    }
                                    //取消号源
                                    //cancleOrder(baseNatAppointmentDO.getCardNo(),baseNatAppointmentDO.getRegisterNo(),baseNatAppointmentDO.getOderNum());
                                }
                                baseNatAppointmentDO.setVoucherNo(jsonObject1.getString("ApplyNo"));
                                baseNatAppointmentDao.save(baseNatAppointmentDO);
                            }
                        }
                    }
                }
            }
    }
    public String selectByRelationCode(String relationCode) throws  Exception{
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
        if (NumberUtils.isDigits(relationCode) ){
            BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(Integer.valueOf(relationCode));
            if (baseNatAppointmentDO!=null&&"-1".equalsIgnoreCase(baseNatAppointmentDO.getIsSuccess())){
                throw new Exception("订单已取消");
            }
            if (businessOrderDO!=null&&businessOrderDO.getStatus()==1){
                throw new Exception("订单已支付");
            }
            String openId="";
            List<BasePatientWechatDo> wechatList=basePatientWechatDao.findByWechatIdAndPatientId("xm_tasy_wx",baseNatAppointmentDO.getConsumer());
            if (wechatList!=null&&wechatList.size()>0){
                openId=wechatList.get(0).getOpenid();
            }
            if (StringUtils.isNoneBlank(businessOrderDO.getOrderNo())){
                String orderNo= businessOrderDO.getOrderNo();
                String newOrder="HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100;
                businessOrderDO.setOrderNo(newOrder);
                businessOrderDO.setHistoryOrder(orderNo+","+newOrder);
            }
            com.alibaba.fastjson.JSONObject orderObj= new com.alibaba.fastjson.JSONObject();
            orderObj.put("payType",1);
            orderObj.put("tradeNo",businessOrderDO.getOrderNo());
            orderObj.put("openId",openId);
            orderObj.put("name",baseNatAppointmentDO.getName());
            orderObj.put("idNo",baseNatAppointmentDO.getCardNo());
            Map mapHis=getPatientHisId(baseNatAppointmentDO.getCardNo(),baseNatAppointmentDO.getMedicare());
            orderObj.put("patientId",mapHis.get("Patientid").toString());
            orderObj.put("mobile",mapHis.get("MobilePhone").toString());
            //orderObj.put("socialCard","");
            orderObj.put("icCard",baseNatAppointmentDO.getMedicare());
            BigDecimal b = new BigDecimal(baseNatAppointmentDO.getChargeAmount());
            b=b.setScale(2, BigDecimal.ROUND_DOWN);
            System.out.println("amount"+b);
            orderObj.put("amount",b);
            //重新下单
            String orderRes=placeOrder(orderObj);
            if (StringUtils.isNoneBlank(orderRes)){
                com.alibaba.fastjson.JSONObject jsonObject= JSON.parseObject(orderRes);
                if (jsonObject!=null){
                    if("0".equalsIgnoreCase(jsonObject.getString("code"))){
                        com.alibaba.fastjson.JSONObject dataObj= com.alibaba.fastjson.JSONObject.parseObject(jsonObject.getString("data"));
                        businessOrderDO.setTraceNo(dataObj.getString("orderNo"));
                        businessOrderDO.setRematk(dataObj.toJSONString());
                        businessOrderDO=businessOrderDao.save(businessOrderDO);
                    }
                }
            }
        }
        return businessOrderDO.getRematk();
    }
    public String getNatResult(String patientId) throws Exception{
        BasePatientDO basePatientDO = basePatientDao.findById(patientId);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -6);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(c.getTime());
        String idcard="";
        String hospitalOid="";
        String wsCode="";
        if (basePatientDO!=null){
            idcard=basePatientDO.getIdcard();
        }
        List<WlyyHospitalSysDictDO> list = wlyyHospitalSysDictDao.findByDictName("hdrQueryDataParam");
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
            if ("hospitalOid".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                hospitalOid=wlyyHospitalSysDictDO.getDictValue();
            }
            if ("wsCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                wsCode=wlyyHospitalSysDictDO.getDictValue();
            }
        }
        String res=hdrQueryDataWS(idcard,wsCode,hospitalOid,dateStr);
        return res;
    }


    //病人单据状态查询
    public String hdrQueryDataWS(String idcard,String wsCode,String oid,String time) throws Exception{
        /*String api = "hdrQueryDataWS";*/
        /*String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
                "   <serverName>"+api+"</serverName>  " +
                "   <format>xml</format>" +
                "   <callOperator>"+operator+"</callOperator> " +
                "   <certificate>"+key+"</certificate> " +
                "</root>";*/
        String msg="<HOSPITAL_OID>"+oid+"</HOSPITAL_OID>";
        if (StringUtils.isNoneBlank()){
            msg+="<ID_CARD>"+idcard+"</ID_CARD>";
        }
        if (StringUtils.isNoneBlank(wsCode)){
            msg+="<WS_CODE>"+wsCode+"</WS_CODE>";
        }
        String condition ="";
        if (StringUtils.isNoneBlank(time)){
            condition+="<CONDITION><ELEM NAME=\"LAB_ITEM_NAME\" VALUE=\"核酸\" OPERATOR=\"like\"></ELEM>" +
                    "<ELEM NAME=\"REPORT_TIME\" VALUE=\""+time+"\" OPERATOR=\"&gt;=\"></ELEM></CONDITION>";
        }

        String msgBody ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<MSG>"+msg+condition+"</MSG>";

        Map<String,String> params = new HashedMap();
        params.put("msg",msgBody);
        logger.info("hdrQueryDataWS params:"+params.toString());
        String xml = getTaszWebServiceInfo("hdrQueryDataWS",params,gethsQueryDataWS());
        if (xml.contains("<ArrayList>")){
            xml=xml.substring(xml.indexOf("<ArrayList>"),xml.lastIndexOf("]]"));
        }else {
            xml=xml.substring(xml.indexOf("<?xml"),xml.lastIndexOf("]]"));
        }
        XMLSerializer xmlSerializer = new XMLSerializer();
        String json = xmlSerializer.read(xml).toString();
        logger.info("hdrQueryDataWS json:"+json);
        return json;
    }
    public  Map checkBalance(String relationCode) throws  Exception{
        BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(Integer.parseInt(relationCode));
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("MzBalance");
        String tmpBalance="";
        if (wlyyHospitalSysDictDO!=null){
            tmpBalance=wlyyHospitalSysDictDO.getDictValue();
        }
        String res = findHisPatientCard(baseNatAppointmentDO.getCardNo());
        String mediacard=baseNatAppointmentDO.getMedicare();
        Map result=new HashMap();
        if (StringUtils.isNoneBlank(res)){
            JSONObject jsonObject = JSON.parseObject(res);
            if ("1".equalsIgnoreCase(jsonObject.getString("ReturnCode"))) {
                String patients=jsonObject.getString("patients");
                if (patients.contains("[")){
                    JSONArray jsonArray = JSON.parseArray(patients);
                    if (jsonArray != null && jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject child = jsonArray.getJSONObject(i);
                            if (mediacard.equalsIgnoreCase(child.getString("CardNo"))) {
                                String MzBalance = child.getString("MzBalance");
                                if (StringUtils.isNoneBlank(tmpBalance)){
                                    MzBalance=tmpBalance;
                                }
                                BigDecimal b = new BigDecimal(MzBalance);
                                b=b.setScale(2, BigDecimal.ROUND_DOWN);
                                System.out.println("MzBalance====="+MzBalance);
                                if (StringUtils.isNoneBlank(MzBalance) && b.compareTo(new BigDecimal("0")) < 0) {
                                    result.put("msgCode", "-1");
                                    result.put("msg", "余额不足");
                                    return result;
                                }
                            }
                        }

                    }
                }else {
                    try {
                        JSONObject jsonObject1= JSONObject.parseObject(patients);
                        if (mediacard.equalsIgnoreCase(jsonObject1.getString("CardNo"))) {
                            String MzBalance = jsonObject1.getString("MzBalance");
                            if (StringUtils.isNoneBlank(tmpBalance)){
                                MzBalance=tmpBalance;
                            }
                            System.out.println("MzBalance====="+MzBalance);
                            BigDecimal b = new BigDecimal(MzBalance);
                            b=b.setScale(2, BigDecimal.ROUND_DOWN);
                            System.out.println("MzBalance====="+b);
                            if (StringUtils.isNoneBlank(MzBalance) && b.compareTo(new BigDecimal("0")) < 0) {
                                result.put("msgCode", "-1");
                                result.put("msg", "余额不足");
                                return result;
                            }
                            return result;
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        result.put("msgCode","-1000");
                        result.put("msg","json格式验证失败");
                    }

                }

            }
        }
        result.put("msgCode","200");
        result.put("msg","验证通过");
        return  result;
    }
    public Map getPatientHisId(String idcard,String mediacard) throws Exception{
        Map map = new HashMap();
        String res = findHisPatientCard(idcard);
        JSONObject jsonObject = JSON.parseObject(res);
        if ("1".equalsIgnoreCase(jsonObject.getString("ReturnCode"))) {
            String patients=jsonObject.getString("patients");
            if (patients.contains("[")) {
                JSONArray jsonArray = JSON.parseArray(patients);
                if (jsonArray != null && jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject child = jsonArray.getJSONObject(i);
                        if (mediacard.equalsIgnoreCase(child.getString("CardNo"))) {
                            String Patientid = child.getString("Patientid");
                            String MobilePhone = child.getString("MobilePhone");
                            map.put("Patientid",Patientid);
                            map.put("MobilePhone",MobilePhone);
                            return map;
                        }
                    }

                }
            } else {
                try {
                    JSONObject jsonObject1 = JSONObject.parseObject(patients);
                    if (mediacard.equalsIgnoreCase(jsonObject1.getString("CardNo"))) {
                        String Patientid = jsonObject1.getString("Patientid");
                        String MobilePhone = jsonObject1.getString("MobilePhone");
                        map.put("Patientid",Patientid);
                        map.put("MobilePhone",MobilePhone);
                        return map;
                    }
                } catch (Exception e) {
                   e.printStackTrace();
                }

            }
        }
        return map;
    }
}
