package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.project.system.domain.vo.ResultVo;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


public class ZhiHuiTokenUtils {
    private static final String TOKEN_URL = "https://zhihui.qq.com/account/api/auth/token";
    private static final String PROFILE_URL = "https://zhihui.qq.com/account/api/auth/profile";
    private static final String secretKey = "72b08c9192094759ba18aacb0394c589";

    public static String getToken(String appid, String channel, String stamp, String timestamp) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", appid);
        params.put("channel", channel);
        params.put("stamp", stamp);
        params.put("timestamp", timestamp);

        String sign = getSign(params);
        params.put("sig", sign);
        String result = HttpUtils.sendPost(TOKEN_URL, getParams(params));
        ResultVo resultVo = JSON.parseObject(result, ResultVo.class);
        //请求成功
        if (!"200".equals(resultVo.getStatusCode())) {
            throw new BaseException(resultVo.getMessage());
        }
        return resultVo.getData();
    }

    public static String getSign(Map<String, String> params) {
        String stringBuilder = null;

        String paramstr = getParams(params);
        try {

            paramstr = URLEncoder.encode(paramstr);
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256Hmac.init(secretKeySpec);
            byte[] encryptedBytes = sha256Hmac.doFinal(paramstr.getBytes(StandardCharsets.UTF_8));
            stringBuilder = bytesToHex(encryptedBytes);
        } catch (Exception e) {

        }
        return stringBuilder;
    }


    private static String getParams(Map<String, String> params) {
        StringBuilder paramStringB = new StringBuilder();
        TreeMap<String, String> sortMap = new TreeMap<>(params);
        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            paramStringB.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (paramStringB.length() > 0) {
            paramStringB.setLength(paramStringB.length() - 1);
        }
        return paramStringB.toString();
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

}
