package com.docus.server.rpc.impl;

import com.docus.server.rpc.YdZyyPacsService;
import com.docus.server.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.w3c.dom.Node;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author YongBin Wen
 * @date 2024/9/14 16:53
 */
@Component
@Slf4j
public class YdZyyPacsServiceImpl implements YdZyyPacsService {


    @Override
    public String getJpgReportBase64(String remark) {
        String wsUrl = "http://10.10.100.106:8011/PACS_WS.asmx";
        String method = "GetStudyReportPreview";
        String param = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://127.0.0.1/\">\n" +
                "    <soapenv:Header/>\n" +
                "    <soapenv:Body>\n" +
                "        <ns:GetStudyReportPreview>\n" +
                "            <!--Optional:-->\n" +
                "            <ns:para>\n" +
                "                <ns:DataFormat>dfXML</ns:DataFormat>\n" +
                "                <!--Optional:-->\n" +
                "                <ns:Token></ns:Token>\n" +
                "                <!--Optional:-->\n" +
                "                <ns:Para>\n" +
                "                    <![CDATA[\n" +
                "            <CallPara><HospitalID>32</HospitalID><SerialNo>" + remark + "</SerialNo><ImageType>JPG</ImageType><ImageDPI>300</ImageDPI><OutFilePath>D:\\CTTEST</OutFilePath><ConvertBase64>TRUE</ConvertBase64></CallPara>\n" +
                "            ]]>\n" +
                "            \n" +
                "            \n" +
                "                </ns:Para>\n" +
                "            </ns:para>\n" +
                "        </ns:GetStudyReportPreview>\n" +
                "    </soapenv:Body>\n" +
                "</soapenv:Envelope>";

        try {
            // 服务器地址
            URL url = new URL(wsUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 拼接soap
            byte[] buf = param.getBytes(StandardCharsets.UTF_8);
            // 设置报头
            conn.setRequestProperty("Content-Length", String.valueOf(buf.length));
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            conn.setRequestProperty("soapActionString", method);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStream out = conn.getOutputStream();
            out.write(buf);
            out.close();
            // 获取响应状态码
            int code = conn.getResponseCode();
            StringBuilder respXml = new StringBuilder();
            if (code == HttpStatus.OK.value()) {
                InputStream is = conn.getInputStream();
                byte[] b = new byte[1024];
                int len;
                while ((len = is.read(b)) != -1) {
                    String s = new String(b, 0, len, StandardCharsets.UTF_8);
                    respXml.append(s);
                }
                is.close();
            }
            return parsePacsBase64(respXml.toString());
        } catch (Exception ex) {
            log.error("英德中医院获取pacs报告出现异常，参数：" + param + ",异常信息：" + ex.getMessage(), ex);
            return null;
        }
    }

    private static String parsePacsBase64(String soapResult) {
        String startStr = "<GetStudyReportPreviewResult>";
        String endStr = "</GetStudyReportPreviewResult>";
        int start = soapResult.indexOf(startStr);
        int end = soapResult.indexOf(endStr) + endStr.length();
        soapResult = soapResult.substring(start, end);
        soapResult = soapResult.replace("&lt;", "<");
        soapResult = soapResult.replace("&gt;", ">");
        XmlUtil xmlUtil = XmlUtil.of(soapResult);
        Node errorCodeNode = xmlUtil.getNode("/GetStudyReportPreviewResult/iErrorCode");
        if ("0".equals(errorCodeNode.getTextContent())) {
            Node fileBase64Node = xmlUtil.getNode("/GetStudyReportPreviewResult/sResultValue/string/FileBase64");
            if (fileBase64Node != null) {
                return fileBase64Node.getTextContent();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
                "\t<soap:Body>\n" +
                "\t\t<GetStudyReportPreviewResponse xmlns=\"http://127.0.0.1/\">\n" +
                "\t\t\t<GetStudyReportPreviewResult>\n" +
                "\t\t\t\t<DataFormat>dfXML</DataFormat>\n" +
                "\t\t\t\t<iErrorCode>0</iErrorCode>\n" +
                "\t\t\t\t<sErrorMessage>执行成功</sErrorMessage>\n" +
                "\t\t\t\t<iResultValue>0</iResultValue>\n" +
                "\t\t\t\t<sResultValue>\n" +
                "\t\t\t\t\t<string>&lt;ImageType&gt;JPG&lt;/ImageType&gt;\n" +
                "&lt;ImageDPI&gt;300&lt;/ImageDPI&gt;\n" +
                "&lt;FileName&gt;D:\\CTTEST\\PACS_REPORT_IMAGE_2018935_202409141634352881.JPG&lt;/FileName&gt;\n" +
                "&lt;ImageSize&gt;0&lt;/ImageSize&gt;\n" +
                "&lt;Md5Value&gt;&lt;/Md5Value&gt;\n" +
                "&lt;FileBase64&gt;/9j/4AAQSkZJRgABAQEAYABgAAtLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3oAKKKKACiiigAooooAKKKKAP/Z&lt;/FileBase64&gt;\n" +
                "</string>\n" +
                "\t\t\t\t</sResultValue>\n" +
                "\t\t\t</GetStudyReportPreviewResult>\n" +
                "\t\t</GetStudyReportPreviewResponse>\n" +
                "\t</soap:Body>\n" +
                "</soap:Envelope>";
        System.out.println(parsePacsBase64(result));
    }
}
