package com.yida.data.device.studentCard.utils;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.webservice.SoapClient;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map.Entry;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


@Slf4j
public class _810AUtil {

    private final static String KEY = "CDZBZ";
    private final static String SECRET = "EDC9411E58C1D7B011A6DCE6985F0ACE";

    public static void send(String method, String params) {
        SoapClient client = SoapClient.create("http://39.106.116.138:7899/?wsdl")
            .setMethod("ns:" + method, "http://tempuri.org/ns.xsd")
            .setParam("InInfo", params, false);
        String res = client.send();
        log.info("810A响应:[{}],发送参数:[{}],发送方法:[{}]", res, params, method);
        // 解析响应消息
        try {
            Document resXml = XmlUtil.parseXml(res);
            Element root = resXml.getDocumentElement();
            NodeList outStr = root.getElementsByTagName("outStr");
            JSONObject resJson = JSONUtil.parseObj(outStr.item(0).getTextContent());
            if (!resJson.getInt("ERRORCODE").equals(0)) {
                log.error("请求810A失败,res:[{}]", resJson);
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * 转换参数并发送请求
     *
     * @param method 请求方法
     * @param params 请求参数 有序(具体顺序与字段见810A文档)
     * @return
     */
    public static void convertAndSend(String method, LinkedHashMap<String, String> params) {
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        StringBuilder sb = new StringBuilder().append(SECRET).append(timestamp);
        for (Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        params.put("SIGN", MD5.create().digestHex(sb.toString()).toUpperCase(Locale.ROOT));
        params.put("TIMESTAMP", timestamp);
        params.put("KEY", KEY);
        send(method, JSONUtil.toJsonStr(params));
    }

    public static void main(String[] args) {
        LinkedHashMap<String, String> msg = new LinkedHashMap<>();
        msg.put("DEVICENUM", "866104040235601");
        msg.put("WHINFO", EscapeUtil.escape("我是一条小青龙，小青龙"));
        msg.put("COURSEID", "1");
        msg.put("WHID", "123123qwe");
        convertAndSend("PushDeviceHomework", msg);
    }
}
