package com.docus.server.rpc.impl;

import com.alibaba.fastjson.JSONObject;
import com.docus.core.util.Func;
import com.docus.server.rpc.GdSzyZhReportService;
import com.docus.server.rpc.dto.GdSzyZhReportDetailDto;
import com.docus.server.rpc.dto.GdSzyZhReportListDto;
import com.docus.server.util.JaxWsDynamicClientUtil;
import com.docus.server.util.TableJsonRead;
import com.docus.server.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author YongBin Wen
 * @date 2026/4/7 15:18
 */
@Slf4j
@Service
public class GdSzyZhReportServiceImpl implements GdSzyZhReportService {
    final String configPath = "data-config";
    final String configName = "gdszyzh-collect-config";

    @Override
    public GdSzyZhReportListDto pacsList(String empId, String jzh, String beginDate, String endDate) {
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);

        JSONObject pacsWsConfig = configOjb.getJSONObject("PACS");
        String wsUrl = pacsWsConfig.getString("listUrl");
        String namespaceUri = pacsWsConfig.getString("listNamespaceUri");
        String method = pacsWsConfig.getString("listOperationName");
        String param = pacsListParam(empId, jzh, beginDate, endDate);
        String[] params = {param};
        Object resultObj = JaxWsDynamicClientUtil.send(wsUrl, namespaceUri, method, params);
        String result = String.valueOf(resultObj);
        log.info("PACS查询报告列表，地址：{},方法：{},参数：{} 调用成功，得到结果为：{}", wsUrl, method, param, result);
        return parsePacsListResult(result);
    }


    @Override
    public GdSzyZhReportDetailDto pacsDetail(String examNo) {
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);

        JSONObject pacsWsConfig = configOjb.getJSONObject("PACS");
        String wsUrl = pacsWsConfig.getString("detailUrl");
        String namespaceUri = pacsWsConfig.getString("detailNamespaceUri");
        String method = pacsWsConfig.getString("detailOperationName");
        String param = pacsDetailParam(examNo);
        String[] params = {param};
        Object resultObj = JaxWsDynamicClientUtil.send(wsUrl, namespaceUri, method, params);
        String result = String.valueOf(resultObj);
        log.info("PACS查询报告详情，地址：{},方法：{},参数：{} 调用成功，得到结果为：{}", wsUrl, method, param, result);
        return parsePacsDetailResult(result);
    }


    private static String pacsListParam(String empId, String jzh, String beginDate, String endDate) {
        return "<ESBEntry>" +
                "<AccessControl>" +
                "<SysFlag>1</SysFlag>" +
                "<UserName>HIS_ZY</UserName>" +
                "<Password>HIS_ZY_0330</Password>" +
                "<Fid>BS04002</Fid>" +
                "<OrderNo>BS04002S02001</OrderNo>" +
                "<SUBOR_HOSPITAL_DISTRICT>ZH</SUBOR_HOSPITAL_DISTRICT>" +
                "</AccessControl>" +
                "<MessageHeader>" +
                "<Fid>BS04002</Fid>" +
                "<OrderNo>BS04002S02001</OrderNo>" +
                "<SourceSysCode>S02</SourceSysCode>" +
                "<TargetSysCode>S00</TargetSysCode>" +
                "<MsgDate>2020-04-27 23:41:09</MsgDate>" +
                "</MessageHeader>" +
                "<RequestOption>" +
                "<triggerData>0</triggerData>" +
                "<dataAmount>500</dataAmount>" +
                "</RequestOption>" +
                "<MsgInfo flag=\"1\">" +
                "<Msg/>" +
                "<distinct value=\"0\"/>" +
                "<query item=\"WS_INPUT\" compy=\"=\" value=\"WS\" splice=\"AND\"/>" +
                "<query_ws action=\"queueReportList\">" +
                "<content>" +
                "<Request>" +
                "<Msg>" +
                "<VUID>001</VUID>" +
                "<OUTHOSP_INDEX_NO/>" +
                "<OUTHOSP_NO>" + jzh + "</OUTHOSP_NO>" +
                "<INHOSP_INDEX_NO/>" +
                "<INHOSP_NO/>" +
                "<EMPI_ID>" + empId + "</EMPI_ID>" +
                "<BEGIN_DATE>" + beginDate + "</BEGIN_DATE>" +
                "<END_DATE>" + endDate + "</END_DATE>" +
                "<EXAM_CATEG_CODE>PACS.CS,PACS.CT,PACS.FS</EXAM_CATEG_CODE>" +
                "</Msg>" +
                "</Request>" +
                "</content>" +
                "</query_ws>" +
                "</MsgInfo>" +
                "<GroupInfo flag=\"0\">" +
                "<AS ID=\"\" linkField=\"\"/>" +
                "</GroupInfo>" +
                "</ESBEntry>";
    }

    private static GdSzyZhReportListDto parsePacsListResult(String result) {
        XmlUtil xmlUtil = XmlUtil.of(result);
        NodeList examInfoList = xmlUtil.getNodeList("/Response/MsgInfo/Msg/ExamInfo");
        int length = examInfoList.getLength();
        List<GdSzyZhReportListDto.Report> reportList = new ArrayList<>();
        for (int i = 1; i <= length; i++) {
            Node examNoNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ExamInfo[" + i + "]/EXAM_NO");
            Node examClassNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ExamInfo[" + i + "]/EXAM_CATEG_CODE");
            Node examDateNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ExamInfo[" + i + "]/EXAM_DATE");
            Node examTimeNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ExamInfo[" + i + "]/EXAM_TIME");
            Node examItemNameNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ExamInfo[" + i + "]/ExamItemInfo/EXAM_ITEM_NAME");
            String examDateTime = examDateNode.getTextContent() + " " + examTimeNode.getTextContent();
            GdSzyZhReportListDto.Report report = new GdSzyZhReportListDto.Report();
            report.setReportNo(examNoNode.getTextContent());
            report.setReportTitle(examItemNameNode.getTextContent());
            report.setReportClass(examClassNode.getTextContent());
            report.setReportTime(Func.parseDate(examDateTime, "yyyy-MM-dd HH:mm:ss"));
            reportList.add(report);
        }
        GdSzyZhReportListDto dto = new GdSzyZhReportListDto();
        dto.setReportList(reportList);
        return dto;
    }

    private static String pacsDetailParam(String examNo) {
        return "<ESBEntry>" +
                "<AccessControl>" +
                "<SysFlag>1</SysFlag>" +
                "<UserName>HIS_ZY</UserName>" +
                "<Password>HIS_ZY_0330</Password>" +
                "<Fid>BS04002</Fid>" +
                "<OrderNo>BS04002S02001</OrderNo>" +
                "<SUBOR_HOSPITAL_DISTRICT>ZH</SUBOR_HOSPITAL_DISTRICT>" +
                "</AccessControl>" +
                "<MessageHeader>" +
                "<Fid>BS04002</Fid>" +
                "<OrderNo>BS04002S02001</OrderNo>" +
                "<SourceSysCode>S02</SourceSysCode>" +
                "<TargetSysCode>S00</TargetSysCode>" +
                "<MsgDate>2020-04-27 23:41:09</MsgDate>" +
                "</MessageHeader>" +
                "<RequestOption>" +
                "<triggerData>0</triggerData>" +
                "<dataAmount>500</dataAmount>" +
                "</RequestOption>" +
                "<MsgInfo flag=\"1\">" +
                "<Msg/>" +
                "<distinct value=\"0\"/>" +
                "<query item=\"WS_INPUT\" compy=\"=\" value=\"WS\" splice=\"AND\"/>" +
                "<query_ws action=\"queueReportInfo\">" +
                "<content>" +
                "<Request>" +
                "<Msg>" +
                "<EXAM_NO>" + examNo + "</EXAM_NO>" +
                "</Msg>" +
                "</Request>" +
                "</content>" +
                "</query_ws>" +
                "</MsgInfo>" +
                "<GroupInfo flag=\"0\">" +
                "<AS ID=\"\" linkField=\"\"/>" +
                "</GroupInfo>" +
                "</ESBEntry>";
    }

    private static GdSzyZhReportDetailDto parsePacsDetailResult(String result) {
        XmlUtil xmlUtil = XmlUtil.of(result);
        Node reportUrlNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ReportInfo/REPORT_URL2");
        String reportUrl = reportUrlNode.getTextContent();
        GdSzyZhReportDetailDto dto = new GdSzyZhReportDetailDto();
        dto.setReportUrl(reportUrl);
        return dto;
    }

    @Override
    public GdSzyZhReportListDto lisList(String empId, String jzh, String beginDate, String endDate) {
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);

        JSONObject pacsWsConfig = configOjb.getJSONObject("LIS");
        String wsUrl = pacsWsConfig.getString("listUrl");
        String namespaceUri = pacsWsConfig.getString("listNamespaceUri");
        String method = pacsWsConfig.getString("listOperationName");

        String headParam = "<Root>" +
                "<MethodCode>201_Q_WS_JYBGLBCX</MethodCode>" +
                "<ProductCode>HIS</ProductCode>" +
                "<HospitalCode>4</HospitalCode>" +
                "<Ticket>dd1f95caf9b367af90fb2849e791dfd3</Ticket>" +
                "<DataFormat>XML</DataFormat>" +
                "</Root>";
        String bodyParam = lisListParam(empId, jzh, beginDate, endDate);
        String[] params = {headParam, bodyParam};
        Object resultObj = JaxWsDynamicClientUtil.send(wsUrl, namespaceUri, method, params);
        String result = String.valueOf(resultObj);
        log.info("LIS查询报告列表，地址：{},方法：{},头参数：{},主体参数：{} 调用成功，得到结果为：{}", wsUrl, method, headParam, bodyParam, result);
        return parseLisListResult(result);
    }

    @Override
    public Object lisDetail(String sampleNo) {

        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);

        JSONObject pacsWsConfig = configOjb.getJSONObject("LIS");
        String wsUrl = pacsWsConfig.getString("detailUrl");
        String namespaceUri = pacsWsConfig.getString("detailNamespaceUri");
        String method = pacsWsConfig.getString("detailOperationName");

        String headParam = "<Root>" +
                "<MethodCode>201_Q_WS_JYBGJGMXCX</MethodCode>" +
                "<ProductCode>HIS</ProductCode>" +
                "<HospitalCode>4</HospitalCode>" +
                "<Ticket>dd1f95caf9b367af90fb2849e791dfd3</Ticket>" +
                "<DataFormat>XML</DataFormat>" +
                "</Root>";
        String bodyParam = lisDetailParam(sampleNo);
        String[] params = {headParam, bodyParam};
        Object resultObj = JaxWsDynamicClientUtil.send(wsUrl, namespaceUri, method, params);
        String result = String.valueOf(resultObj);

        log.info("LIS查询报告详情，地址：{},方法：{},头参数：{},主体参数：{} 调用成功，得到结果为：{}", wsUrl, method, headParam, bodyParam, result);
        return parsePacsDetailResult(result);
    }

    private static String lisListParam(String empId, String jzh, String beginDate, String endDate) {
        return "<Request>" +
                "<Msg>" +
                "<OUTHOSP_INDEX_NO />" +
                "<OUTHOSP_NO />" +
                "<INHOSP_INDEX_NO />" +
                "<INHOSP_NO />" +
                "<EMPI_ID>" + empId + "</EMPI_ID>" +
                "<TEST_PAT_SOURCE_CODE />" +
                "<BEGIN_DATE>" + beginDate + "</BEGIN_DATE>" +
                "<END_DATE>" + endDate + "</END_DATE>" +
                "</Msg>" +
                "</Request>";
    }

    private static GdSzyZhReportListDto parseLisListResult(String result) {
        XmlUtil xmlUtil = XmlUtil.of(result);
        NodeList nodeList = xmlUtil.getNodeList("/Response/MsgInfo/Msg/ReportInfo");
        int length = nodeList.getLength();
        List<GdSzyZhReportListDto.Report> reportList = new ArrayList<>();
        for (int i = 1; i <= length; i++) {
            Node sampleNoNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ReportInfo[" + i + "]/SAMPLE_NO");
            Node reportPdfUrlNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ReportInfo[" + i + "]/REPORT_PDF_URL");
            Node testCategNameNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ReportInfo[" + i + "]/TEST_CATEG_NAME");
            Node sampleTypeCodeNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ReportInfo[" + i + "]/SAMPLE_TYPE_CODE");
            Node reportApprovalDatetimeNode = xmlUtil.getNode("/Response/MsgInfo/Msg/ReportInfo[" + i + "]/REPORT_APPROVAL_DATETIME");

            GdSzyZhReportListDto.Report report = new GdSzyZhReportListDto.Report();
            report.setReportNo(sampleNoNode.getTextContent());
            report.setReporPath(reportPdfUrlNode.getTextContent());
            report.setReportClass(sampleTypeCodeNode.getTextContent());
            report.setReportTitle(testCategNameNode.getTextContent());
            report.setReportTime(Func.parseDate(reportApprovalDatetimeNode.getTextContent(), "yyyy-MM-dd HH:mm:ss"));
            reportList.add(report);
        }
        GdSzyZhReportListDto dto = new GdSzyZhReportListDto();
        dto.setReportList(reportList);
        return dto;
    }

    private static String lisDetailParam(String sampleNo) {
        return "<Request>" +
                "<Msg>" +
                "<SAMPLE_NO>" + sampleNo + "</SAMPLE_NO>" +
                "</Msg>" +
                "</Request>";
    }

    private static Object parseLisDetailResult(String result) {
        // 暂未实现
        return null;
    }


}
