package com.saye.hospitalgd.util;

import com.saye.hospitalgd.commons.date.DateDUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author thuang
 * @version 1.0
 * @description: inputXml需要将尖括号替换为转义字符
 * @date 2021/9/17 15:43
 */
@Slf4j
public class HisUtil {

    /**
     * @description: 获取his数据（中联）
     * @author thuang
     * @date 2021/9/29 13:59
     * @version 1.0
     */
    public HashMap<String, String> getHisDataByZL(String url, String businessNo, String inputXml) {
        HashMap<String, String> resultMap = new HashMap<>();

        String errCode = "0";
        String errMsg = "";

        try {
            RestTemplate restTemplate = RestTemplateUtil.getInstance();

            // 创建一个请求头对象
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
            // 设置请求头对象contentTyp的为text/xml;charset=UTF-8
            headers.setContentType(type);

            // 将请求参数进行封装并进行远程接口服务调用
            // 构造webservice请求参数
            StringBuffer soapRequestData = new StringBuffer("");
            soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">");
            soapRequestData.append("<soapenv:Header/>");
            soapRequestData.append("<soapenv:Body>");
            soapRequestData.append("<tem:MOP_PatHosPayDetailQuery>");
//            soapRequestData.append("<tem:BusinessNo>");

            //传入交易编号
//            soapRequestData.append(businessNo);

//            soapRequestData.append("</tem:BusinessNo>");
            soapRequestData.append("<tem:InMsg>");

            //传入参数 < > 符号需要转义
            inputXml = inputXml.replaceAll("<", "&lt;");
            inputXml = inputXml.replaceAll(">", "&gt;");

            soapRequestData.append(inputXml);

            soapRequestData.append("</tem:InMsg>");
            soapRequestData.append("</tem:MOP_PatHosPayDetailQuery>");
            soapRequestData.append("</soapenv:Body>");
            soapRequestData.append("</soapenv:Envelope>");

            // 创建请求
            HttpEntity<String> request = new HttpEntity<String>(soapRequestData + "", headers);

            // 发送post请求并获取到响应结果
            String str = restTemplate.postForObject(url, request, String.class);
            Document document = DocumentHelper.parseText(str);

            Element rootElt = document.getRootElement();

            //直接获取body
            Iterator body = rootElt.elementIterator("Body");
            Element recordEless = (Element) body.next();

            Iterator callHisResponse = recordEless.elementIterator("MOP_PatHosPayDetailQueryResponse");
            Element hisResponse = (Element) callHisResponse.next();

            Iterator callHisResult = hisResponse.elementIterator("MOP_PatHosPayDetailQueryResult");
            Element hisResult = (Element) callHisResult.next();

            String text = hisResult.getText();

            resultMap.put("dataStr", text);
        } catch (Exception e) {
            e.printStackTrace();

            errCode = "999";
            errMsg = "调用his接口失败，原因" + e.getMessage();

        }

        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);

        return resultMap;
    }


    /**
     * @description: 解析返回的内容.获取其中的His对账数据（中联）
     * @author thuang
     * @date 2021/9/29 14:04
     * @version 1.0
     */
    public HashMap<String, Object> managerDataStrByZL(String dataStr) {
        HashMap<String, Object> resultMap = new HashMap<>();

        String errCode = "0";
        String errMsg = "";

        try {
            dataStr = dataStr.replaceAll("&lt;", "<");
            dataStr = dataStr.replaceAll("&gt;", ">");

            Document document = DocumentHelper.parseText(dataStr);

            Element rootElt = document.getRootElement();

            Iterator iterator = rootElt.elementIterator();

            Element returnResult = (Element) iterator.next();//returnResult
            Element returnCode = returnResult.element("returncode");
            Element ErrorMsg = returnResult.element("errormsg");


            if (!"1".equals(returnCode.getText())) {
                errCode = returnCode.getText();
                errMsg = ErrorMsg.getText();
            }

            //如果正确 开始解析
            if ("1".equals(returnCode.getText())) {
                List<HashMap<Object, Object>> addList = new ArrayList<>();

                Element Items = (Element) iterator.next();

                Iterator itemIterator = Items.elementIterator();

                while (itemIterator.hasNext()) {
                    HashMap<Object, Object> addMap = new HashMap<>();
                    Element item = (Element) itemIterator.next();

                    Element visitzOrg = item.element("VisitzOrg");
                    String visitzOrgText = visitzOrg.getText();

                    Element bizType = item.element("BizType");
                    String bizTypeText = bizType.getText();


                    Element payType = item.element("PayType");
                    String payTypeText = payType.getText();

                    Element amount = item.element("Amount");
                    String amountText = amount.getText();

                    Element zfAmount = item.element("ZFAmount");
                    String zfAmountText = zfAmount.getText();

                    Element ybzhAmount = item.element("YBZHAmount");
                    String ybzhAmountText = ybzhAmount.getText();

                    Element ybtcAmount = item.element("YBTCAmount");
                    String ybtcAmountText = ybtcAmount.getText();

                    Element receiptNo = item.element("ReceiptNO");
                    String receiptNoText = receiptNo.getText();

                    Element invnum = item.element("InvNum");
                    String invnumText = invnum.getText();

                    Element patientID = item.element("PatientID");
                    String patientIDText = patientID.getText();


                    Element inhosnum = item.element("InHosNum");
                    String inhosnumText = inhosnum.getText();

                    Element patientName = item.element("PatientName");
                    String patientNameText = patientName.getText();

                    Element tradeTime = item.element("TradeTime");
                    String tradeTimeText = tradeTime.getText();


                    Element hisTime = item.element("HisTime");
                    String hisTimeText = hisTime.getText();


                    Element hisOperNum = item.element("HisOperNum");
                    String hisOperNumText = hisOperNum.getText();


                    Element tranID = item.element("PowerTranID");
                    String tranIDText = tranID.getText();

                    addMap.put("visitzOrg", visitzOrgText);
                    addMap.put("bizType", bizTypeText);
                    addMap.put("payType", payTypeText);
                    addMap.put("amount", amountText);
                    addMap.put("zfAmount", zfAmountText);
                    addMap.put("ybzhAmount", ybzhAmountText);
                    addMap.put("ybtcAmount", ybtcAmountText);
                    addMap.put("receiptNo", receiptNoText);
                    addMap.put("invnum", invnumText);
                    addMap.put("patientID", patientIDText);
                    addMap.put("inhosnum", inhosnumText);
                    addMap.put("patientName", patientNameText);

                    String trade_date = "";
                    String TradeTime = "";

                    String[] s = hisTimeText.split(" ");
                    trade_date = s[0];
                    TradeTime = s[1];


                    addMap.put("trade_date", trade_date + "");

                    addMap.put("tradeTime", TradeTime);
                    addMap.put("hisTime", hisTimeText);


                    addMap.put("hisOperNum", hisOperNumText);
                    addMap.put("tranID", tranIDText);


                    addList.add(addMap);
                }
                resultMap.put("addList", addList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            errCode = "999";
            errMsg = "his数据字符串中提取数据失败，原因：" + e.getMessage();

        }
        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);

        return resultMap;
    }


    /**
     * @description: 获取his数据（卫宁）
     * @author thuang
     * @date 2021/10/13 10:17
     * @version 1.0
     */
    public HashMap<String, String> getHisDataByWN(String url, String tranCode, String inputXml) {
        HashMap<String, String> resultMap = new HashMap<>();

        String errCode = "0";
        String errMsg = "";

        try {
            RestTemplate restTemplate = RestTemplateUtil.getInstance();

            // 创建一个请求头对象
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
            // 设置请求头对象contentTyp的为text/xml;charset=UTF-8
            headers.setContentType(type);

            // 将请求参数进行封装并进行远程接口服务调用
            // 构造webservice请求参数
            StringBuffer soapRequestData = new StringBuffer("");
            soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:kws=\"http://www.winning.com.cn/KWS/\">");
            soapRequestData.append("<soapenv:Header/>");
            soapRequestData.append("<soapenv:Body>");
            soapRequestData.append("<kws:WebBusiness>");
            soapRequestData.append("<kws:TranCode>");

            //传入交易编号
            soapRequestData.append(tranCode);

            soapRequestData.append("</kws:TranCode>");
            soapRequestData.append("<kws:InXml>");

            //传入参数 < > 符号需要转义
            inputXml = inputXml.replaceAll("<", "&lt;");
            inputXml = inputXml.replaceAll(">", "&gt;");

            soapRequestData.append(inputXml);

            soapRequestData.append("</kws:InXml>");
            soapRequestData.append("</kws:WebBusiness>");
            soapRequestData.append("</soapenv:Body>");
            soapRequestData.append("</soapenv:Envelope>");


            // 创建请求
            HttpEntity<String> request = new HttpEntity<String>(soapRequestData + "", headers);

            // 发送post请求并获取到响应结果
            String str = restTemplate.postForObject(url, request, String.class);


            Document document = DocumentHelper.parseText(str);

            Element rootElt = document.getRootElement();

            //直接获取body
            Iterator body = rootElt.elementIterator("Body");
            Element recordEless = (Element) body.next();

            Iterator callHisResponse = recordEless.elementIterator("WebBusinessResponse");
            Element hisResponse = (Element) callHisResponse.next();

            Iterator callHisResult = hisResponse.elementIterator("WebBusinessResult");
            Element hisResult = (Element) callHisResult.next();

            String text = hisResult.getText();

            Iterator callOutXml = hisResponse.elementIterator("OutXml");
            Element outXml = (Element) callOutXml.next();
            String text1 = outXml.getText();

            resultMap.put("dataStr", text1);
        } catch (Exception e) {
            e.printStackTrace();

            errCode = "999";
            errMsg = "调用his接口失败，原因" + e.getMessage();

        }

        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);

        return resultMap;

    }


    /**
     * @description: 解析返回的内容.获取其中的His对账数据（卫宁）
     * @author thuang
     * @date 2021/9/29 14:04
     * @version 1.0
     */
    public HashMap<String, Object> managerDataStrByWN(String dataStr) {
        HashMap<String, Object> resultMap = new HashMap<>();

        String errCode = "0";
        String errMsg = "";

        try {
            dataStr = dataStr.replaceAll("&lt;", "<");
            dataStr = dataStr.replaceAll("&gt;", ">");

            Document document = DocumentHelper.parseText(dataStr);

            Element rootElt = document.getRootElement();

            Iterator iterator = rootElt.elementIterator();

            Element codeElm = (Element) iterator.next();
            Element msgElm = (Element) iterator.next();

            String code = codeElm.getText();
            String msg = msgElm.getText();

            if (!"0".equals(code)) {
                errCode = code;
                errMsg = msg;
            }

            //如果正确 开始解析
            if ("0".equals(code)) {
                List<HashMap<Object, Object>> addList = new ArrayList<>();

                Element result = (Element) iterator.next();

                Iterator itemIterator = result.elementIterator();

                while (itemIterator.hasNext()) {
                    HashMap<Object, Object> addMap = new HashMap<>();
                    Element item = (Element) itemIterator.next();

                    //数据类型 1-门诊 2-住院
                    Element sjlxElm = item.element("sjlx");
                    String sjlx = sjlxElm.getText();

                    //患者姓名
                    Element hzxmElm = item.element("hzxm");
                    String hzxm = hzxmElm.getText();

                    //患者标识
                    Element patidElm = item.element("patid");
                    String patid = patidElm.getText();

                    //交易金额
                    Element jyjeElm = item.element("jyje");
                    String jyje = jyjeElm.getText();
                    //格式化金额 原先小数四位 有效两位
                    jyje = new BigDecimal(jyje).setScale(2, BigDecimal.ROUND_HALF_UP).toString();

                    //退余金额
                    Element tyjeElm = item.element("tyje");
                    String tyje = tyjeElm.getText();
                    //格式化金额 原先小数四位 有效两位
                    tyje = new BigDecimal(tyje).setScale(2, BigDecimal.ROUND_HALF_UP).toString();

                    //支付流水号（平台交易号，银商订单号）
                    Element zflshElm = item.element("zflsh");
                    String zflsh = zflshElm.getText();

                    //交易时间
                    Element jyrqElm = item.element("jyrq");
                    String jyrq = jyrqElm.getText();

                    //是否退款记录
                    Element sftkjlElm = item.element("sftkjl");
                    String sftkjl = sftkjlElm.getText();

                    //支付方式
                    Element zffsElm = item.element("zffs");
                    String zffs = zffsElm.getText();

                    //交易类型
                    Element jylxElm = item.element("jylx");
                    String jylx = jylxElm.getText();

                    //操作员号
                    Element czyhElm = item.element("czyh");
                    String czyh = czyhElm.getText();

                    //交易日期
                    String trade_date = "";
                    if (jyrq.length() > 10) {
                        //卫宁的日期格式为yyyyMMddHH:mm:ss 格式化日期为 yyyy-MM-dd HH:mm:ss
                        trade_date = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, DateDUtil.strToDate(DateDUtil.yyyyMMddHH_mm_ss, jyrq));
                    }


                    addMap.put("sjlx", sjlx);
                    addMap.put("hzxm", hzxm);
                    addMap.put("patid", patid);
                    addMap.put("jyje", jyje);
                    addMap.put("tyje", tyje);
                    addMap.put("zflsh", zflsh);
                    addMap.put("jyrq", jyrq);
                    addMap.put("sftkjl", sftkjl);
                    addMap.put("zffs", zffs);
                    addMap.put("jylx", jylx);
                    addMap.put("czyh", czyh);
                    addMap.put("trade_date", trade_date);

                    addList.add(addMap);
                }
                resultMap.put("addList", addList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            errCode = "999";
            errMsg = "his数据字符串中提取数据失败，原因：" + e.getMessage();
        }
        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);

        return resultMap;
    }


    /**
     * @description: 获取his数据（弘扬）
     * @author thuang
     * @date 2022/1/24 10:13
     * @version 1.0
     */
    public HashMap<String, String> getHisDataByHY(String url, String tranCode, String inputXml) {
        HashMap<String, String> resultMap = new HashMap<>();

        String errCode = "0";
        String errMsg = "";

        try {
            RestTemplate restTemplate = RestTemplateUtil.getInstance();

            // 创建一个请求头对象
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
            // 设置请求头对象contentTyp的为text/xml;charset=UTF-8
            headers.setContentType(type);

            // 将请求参数进行封装并进行远程接口服务调用
            // 构造webservice请求参数
            StringBuffer soapRequestData = new StringBuffer("");
            soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">");
            soapRequestData.append("<soapenv:Header/>");
            soapRequestData.append("<soapenv:Body>");
            soapRequestData.append("<tem:MOP_PatHosPayDetailQuery>");
            soapRequestData.append("<tem:InMsg>");

            //传入参数 < > 符号需要转义
            inputXml = inputXml.replaceAll("<", "&lt;");
            inputXml = inputXml.replaceAll(">", "&gt;");

            soapRequestData.append(inputXml);

            soapRequestData.append("</tem:InMsg>");
            soapRequestData.append("</tem:MOP_PatHosPayDetailQuery>");
            soapRequestData.append("</soapenv:Body>");
            soapRequestData.append("</soapenv:Envelope>");

            // 创建请求
            HttpEntity<String> request = new HttpEntity<String>(soapRequestData + "", headers);

            // 发送post请求并获取到响应结果
            String str = restTemplate.postForObject(url, request, String.class);

            Document document = DocumentHelper.parseText(str);

            Element rootElt = document.getRootElement();

            //直接获取body
            Iterator body = rootElt.elementIterator("Body");
            Element recordEless = (Element) body.next();

            Iterator callHisResponse = recordEless.elementIterator("MOP_PatHosPayDetailQueryResponse");
            Element hisResponse = (Element) callHisResponse.next();

            // 根据新的XML结构，先获取第一个request元素
            Iterator callRequest = hisResponse.elementIterator("request");
            if (!callRequest.hasNext()) {
                throw new RuntimeException("未找到request元素");
            }
            Element requestElement = (Element) callRequest.next();

            // 从第一个request元素中获取第二个request元素
            Iterator callSecondRequest = requestElement.elementIterator("request");
            if (!callSecondRequest.hasNext()) {
                throw new RuntimeException("未找到第二个request元素");
            }
            Element secondRequestElement = (Element) callSecondRequest.next();

            // 第二个request元素本身就是OutPut_MOP_PatHosPayDetailQuery（通过xsi:type属性标识）
            // 所以直接使用它，不需要再查找子元素
            Element hisResult = secondRequestElement;

            // 获取完整的XML内容，而不是文本内容
            String text = hisResult.asXML();

            System.out.println("从HIS接口获取的XML数据: " + text);

            /*Iterator callOutXml = hisResponse.elementIterator("OutXml");
            Element outXml = (Element)callOutXml.next();
            String text1 = outXml.getText();
*/
            resultMap.put("dataStr", text);
        } catch (Exception e) {
            log.error("调用his接口失败，原因", e);

            errCode = "999";
            errMsg = "调用his接口失败，原因" + e.getMessage();

        }

        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);

        return resultMap;
    }

    /**
     * @description: 解析返回的内容.获取其中的His对账数据（弘扬）
     * @author thuang
     * @date 2022/1/24 10:14
     * @version 1.0
     */
    public HashMap<String, Object> managerDataStrByHY(String dataStr) {
        HashMap<String, Object> resultMap = new HashMap<>();

        String errCode = "0";
        String errMsg = "";

        try {
            // 检查dataStr是否为空或null
            if (dataStr == null || dataStr.trim().isEmpty()) {
                errCode = "999";
                errMsg = "传入的XML数据为空";
                resultMap.put("errCode", errCode);
                resultMap.put("errMsg", errMsg);
                return resultMap;
            }

            dataStr = dataStr.replaceAll("&lt;", "<");
            dataStr = dataStr.replaceAll("&gt;", ">");

            log.info("解析前的XML数据: {}", dataStr);

            // 检查XML是否完整
            if (!dataStr.trim().startsWith("<") || !dataStr.trim().endsWith(">")) {
                errCode = "999";
                errMsg = "XML数据格式不完整";
                resultMap.put("errCode", errCode);
                resultMap.put("errMsg", errMsg);
                return resultMap;
            }

            Document document2 = DocumentHelper.parseText(dataStr);

            Element rootElt2 = document2.getRootElement();

            log.info("XML根元素名称: {}", rootElt2.getName());

            // 由于getHisDataByHY已经预处理了XML，这里直接查找returnresult和data元素
            Element returnresultElm = rootElt2.element("returnresult");
            if (returnresultElm == null) {
                errCode = "999";
                errMsg = "XML结构错误：没有找到returnresult元素";
                resultMap.put("errCode", errCode);
                resultMap.put("errMsg", errMsg);
                return resultMap;
            }

            // 查找data元素（可能有多个）
            List<Element> dataElements = rootElt2.elements("data");
            if (dataElements == null || dataElements.isEmpty()) {
                errCode = "999";
                errMsg = "XML结构错误：没有找到data元素";
                resultMap.put("errCode", errCode);
                resultMap.put("errMsg", errMsg);
                return resultMap;
            }

            log.info("找到data元素数量: {}", dataElements.size());

            Iterator returncode = returnresultElm.elementIterator("returncode");
            Iterator errormsg = returnresultElm.elementIterator("errormsg");

            Element codeElm = (Element) returncode.next();
            Element msgElm = (Element) errormsg.next();

            String code = codeElm.getText();
            String msg = msgElm.getText();

            if (!"1".equals(code)) {
                errCode = code;
                errMsg = msg;
            }

            //如果正确 开始解析
            if ("1".equals(code)) {
                List<HashMap<Object, Object>> addList = new ArrayList<>();

                // 遍历所有data元素
                for (Element item : dataElements) {
                    HashMap<Object, Object> addMap = new HashMap<>();

                    //数据类型 1-门诊 2-住院
                    Element visitzOrgElm = item.element("VisitzOrg");
                    String visitzOrg = visitzOrgElm != null ? visitzOrgElm.getText() : "";

                    //业务类型
                    Element bizTypeElm = item.element("BizType");
                    String bizType = bizTypeElm != null ? bizTypeElm.getText() : "";

                    //支付方式
                    Element payTypeElm = item.element("PayType");
                    String payType = payTypeElm != null ? payTypeElm.getText() : "";

                    //总金额
                    Element amountElm = item.element("Amount");
                    String amount = amountElm != null ? amountElm.getText() : "";

                    //自费支付金额
                    Element zfAmountElm = item.element("ZFAmount");
                    String zfAmount = zfAmountElm != null ? zfAmountElm.getText() : "";

                    //医保账户金额
                    Element ybzhAmountElm = item.element("YBZHAmount");
                    String ybzhAmount = ybzhAmountElm != null ? ybzhAmountElm.getText() : "";

                    //医保统筹金额
                    Element ybtcAmountElm = item.element("YBTCAmount");
                    String ybtcAmount = ybtcAmountElm != null ? ybtcAmountElm.getText() : "";

                    //收据号
                    Element receiptNOElm = item.element("ReceiptNO");
                    String receiptNO = receiptNOElm != null ? receiptNOElm.getText() : "";

                    //发票号
                    Element invNumElm = item.element("InvNum");
                    String invNum = invNumElm != null ? invNumElm.getText() : "";

                    //患者 ID
                    Element patientIDElm = item.element("PatientID");
                    String patientID = patientIDElm != null ? patientIDElm.getText() : "";

                    //患者姓名
                    Element patientNameElm = item.element("PatientName");
                    String patientName = patientNameElm != null ? patientNameElm.getText() : "";

                    //住院号
                    Element inHosNumElm = item.element("InHosNum");
                    String inHosNum = inHosNumElm != null ? inHosNumElm.getText() : "";

                    //交易时间
                    Element tradeTimeElm = item.element("TradeTime");
                    String tradeTime = tradeTimeElm != null ? tradeTimeElm.getText() : "";

                    //交易日期
                    String trade_date = "";
                    if (tradeTime != null && tradeTime.length() > 10) {
                        try {
                            // 处理日期格式：将 yyyy/M/d H:m:s 转换为 yyyy-MM-dd HH:mm:ss
                            // 例如：2024/8/7 7:55:45 -> 2024-08-07 07:55:45
                            String[] parts = tradeTime.split(" ");
                            if (parts.length == 2) {
                                String datePart = parts[0];
                                String timePart = parts[1];
                                
                                String[] dateComponents = datePart.split("/");
                                if (dateComponents.length == 3) {
                                    String year = dateComponents[0];
                                    String month = String.format("%02d", Integer.parseInt(dateComponents[1]));
                                    String day = String.format("%02d", Integer.parseInt(dateComponents[2]));
                                    
                                    String[] timeComponents = timePart.split(":");
                                    if (timeComponents.length == 3) {
                                        String hour = String.format("%02d", Integer.parseInt(timeComponents[0]));
                                        String minute = String.format("%02d", Integer.parseInt(timeComponents[1]));
                                        String second = timeComponents[2];
                                        
                                        String formattedDateTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
                                        trade_date = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, DateDUtil.strToDate(DateDUtil.yyyy_MM_dd_HH_mm_ss, formattedDateTime));
                                    }
                                }
                            }
                        } catch (Exception e) {
                            System.out.println("日期解析失败: " + tradeTime + ", 错误: " + e.getMessage());
                            trade_date = "";
                        }
                    }

                    //HIS 业务时间
                    Element hisTimeElm = item.element("HisTime");
                    String hisTime = hisTimeElm.getText();

                    //操作员
                    Element hisOperNumElm = item.element("HisOperNum");
                    String hisOperNum = hisOperNumElm.getText();

                    //交易 ID
                    Element powerTranIDElm = item.element("PowerTranID");

                    //此处为关键id，但是由于错误数据的存在 此处还是保存下。免的说之后少获取数据
                    String powerTranID = "";
                    if (powerTranIDElm != null) {
                        powerTranID = powerTranIDElm.getText();
                    }

                    addMap.put("visitzOrg", visitzOrg);
                    addMap.put("bizType", bizType);
                    addMap.put("payType", payType);
                    addMap.put("amount", amount);
                    addMap.put("zfAmount", zfAmount);
                    addMap.put("ybzhAmount", ybzhAmount);
                    addMap.put("ybtcAmount", ybtcAmount);
                    addMap.put("receiptNO", receiptNO);
                    addMap.put("invNum", invNum);
                    addMap.put("patientID", patientID);
                    addMap.put("patientName", patientName);
                    addMap.put("inHosNum", inHosNum);
                    addMap.put("tradeTime", tradeTime);
                    addMap.put("trade_date", trade_date);
                    addMap.put("hisTime", hisTime);
                    addMap.put("hisOperCode", hisOperNum);  // 修改字段名以匹配HISGetDataMethodByJH中的使用
                    addMap.put("powerTranID", powerTranID);
                    addMap.put("hisTransId", receiptNO);  // 新增HisTransId字段，使用ReceiptNO的值

                    addList.add(addMap);
                }
                
                log.info("解析到的数据条数: {}", addList.size());
                if (addList.size() > 0) {
                    log.info("第一条数据示例: {}", addList.get(0));
                }
                resultMap.put("addList", addList);
            }
        } catch (Exception e) {
            log.error("his数据字符串中提取数据失败，原因：", e);
            errCode = "999";
            errMsg = "his数据字符串中提取数据失败，原因：" + e.getMessage();
        }
        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);

        return resultMap;
    }


}
