package org.dromara.zhishu.util;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Log4j2
@RequiredArgsConstructor
public class KongfzApiUtils {
    private static final String API_URL = "https://api.kongfz.com/router/rest";
    @Value("${kongfz.appId}")
    private String appId;
    @Value("${kongfz.appSecret}")
    private String appSecret;
    @Value("${kongfz.accessToken}")
    private String accessToken;


    /**
     * 生成当前时间字符串
     */
    public static String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return sdf.format(new Date());
    }

    /**
     * 生成签名
     */

    public static String generateSign(Map<String, String> params, String secretKey)  {
        StringBuilder paramStr = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        paramStr.append("secret=").append(secretKey);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] digest = md.digest(paramStr.toString().getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    public static Map<String, String> buildKongfzParams(String appId, String secretKey) throws NoSuchAlgorithmException {
        Map<String, String> params = new HashMap<>();
        params.put("method", "kongfz.shop.simple.get");
        params.put("appId", appId);
        // 若需要授权，设置 accessToken
        // params.put("accessToken", "YOUR_ACCESS_TOKEN");
        params.put("datetime", getCurrentDateTime());
        params.put("format", "json");
        params.put("v", "1.0");
        params.put("signMethod", "md5");
        String sign = generateSign(params, secretKey);
        params.put("sign", sign);
        params.put("simplify", "0");
        return params;
}


}
