package com.pj.api.wx;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import com.pj.current.config.WxConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
@Slf4j
public class WxUtils {

    public  String sign(final Map<String, String> data,String key) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (StrUtil.isNotEmpty(data.get(k))){
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        log.info("wx pay sign str:{}",sb.toString());
        return SecureUtil.md5(sb.toString()).toUpperCase();
    }

    public Map<String, Object> msgToMap(HttpServletRequest request) throws Exception {
        // 处理接收消息
        InputStream inputStream = request.getInputStream();
        // 将流转换为字符串
        StringBuilder xmlMsg = new StringBuilder();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        while ((s = in.readLine()) != null) {
            xmlMsg.append(s);
        }
        in.close();
        inputStream.close();
        return XmlUtil.xmlToMap(xmlMsg.toString());
    }
}
