package thyyxxk.webserver.service.ca;

import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.Forest;
import com.dtflys.forest.utils.ForestDataType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CaWSDL {

    private final String regex = "<ns1:out>(.*?)</ns1:out>";
    // 创建 Pattern 对象
    private final Pattern pattern = Pattern.compile(regex);

    private final String url;

    public CaWSDL(String url) {
        this.url = url;
    }

    public JSONObject invoke(String method, String request) {
        String WSDL = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.security.openapi.sp.custle.com\">\n" +
                      "   <soapenv:Header/>\n" +
                      "   <soapenv:Body>\n" +
                      "      <web:${name}>\n" +
                      "         <web:in0>\n" +
                      "    <![CDATA[${data}]]>\n" +
                      "         </web:in0>\n" +
                      "      </web:${name}>\n" +
                      "   </soapenv:Body>\n" +
                      "</soapenv:Envelope>";
        String body = WSDL.replace("${name}", method).replace("${data}", request);
        String execute = Forest.post(url).addBody(body).bodyType(ForestDataType.XML).execute(String.class);
        String data = findData(execute);
        return JSONUtil.xmlToJson(data);
    }

    private String findData(String input) {
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            // 获取第一个捕获组
            return HtmlUtil.unescape(matcher.group(1));
        } else {
            return "";
        }
    }
}
