package com.backendsys.service.SDKService.SDKTencent;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;


@Service
public class SDKTencentServiceImpl implements SDKTencentService {

    /**
     * 获得 Signature 签名 (仅用于内部接口换签，不公开使用)
     * - 通过 { appKey } 和 { accessToken } 获得：
     {
         "appkey": "9d66c73a8a694333b5244447edd62576",
         "signature": "hkOgBdqx52Cm/gHc1KGZTAnw7fVM1q+bcx1aY1dB9NU=",
         "signatureEncode": "hkOgBdqx52Cm%2FgHc1KGZTAnw7fVM1q%2Bbcx1aY1dB9NU%3D",
         "timestamp": 1712252559
     }
     */
    public Map<String, Object> getSignature(String appKey, String accessToken) {

        try {
            // 获得时间戳
            long timestamp = DateUtil.currentSeconds();
            String signatureString = "appkey=" + appKey + "&timestamp=" + timestamp;

            // 使用HMAC-SHA256算法进行加密
            HMac hMac = new HMac(HmacAlgorithm.HmacSHA256, accessToken.getBytes());
            byte[] hashBytes = hMac.digest(signatureString.getBytes());

            // 对加密后的结果进行Base64编码
            String signature = Base64.encode(hashBytes);
            // 对签名进行URL编码
            String signature_encode = URLEncoder.encode(signature, "UTF-8");

            Map<String, Object> result = new LinkedHashMap<>();
            result.put("appkey", appKey);
            result.put("signature", signature);
            result.put("signatureEncode", signature_encode);
            result.put("timestamp", timestamp);

            return result;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

}
