package com.yifu.cloud.plus.v1.yifu.social.config;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Base64;
import java.util.Map;

/**
 * @author hgw2
 * @description 税友签名接口
 * @date 2024/12/9
 */
public class SocialFriendSign {

	public static String qianMing(Map<String, String> treeMap) throws SignatureException {
		// 1. 将以上 key=value 对的 value 进行合并,生成一下字符串 mergeStr

		//System.out.println("header内的信息："+treeMap.toString())
		StringBuilder mergeStr = new StringBuilder();
		for (Map.Entry<String, String> stringStringEntry : treeMap.entrySet()) {
			mergeStr.append(stringStringEntry.getValue());
		}
		//System.out.println("Key-Value 合并： " + mergeStr)
		// 2. 将生成的 mergeStr 进行 Url 编码
		String encodedStr = null;
		try {
			encodedStr = URLEncoder.encode(mergeStr.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// URL 编码失败
			throw new SignatureException("【税友】URL 编码失败");
		}
		//System.out.println("encodeURL 编码：" + encodedStr)
		// 3.利用 HmacSHA256 算法对 signStr 进行哈希运算生成消息摘要,摘要结果以 Base64 结果形式返回，signStr 即为请求参数中的 signature 字段
		String signatureResult = "";
		try {
			Mac mac = Mac.getInstance("HmacSHA256");
			SecretKeySpec signingKey = new SecretKeySpec(treeMap.get("appSecret").getBytes(), "HmacSHA256");
			mac.init(signingKey);
			byte[] signData = mac.doFinal(encodedStr.getBytes());
			byte[] resultBytes = Base64.getEncoder().encode(signData);
			signatureResult = new String(resultBytes, StandardCharsets.UTF_8);
		} catch (NoSuchAlgorithmException e) {
			throw new SignatureException("【税友】平台不支持 HmacSHA 摘要方式");
		} catch (InvalidKeyException e) {
			throw new SignatureException("【税友】指定的访问密钥无效");
		}
		//ystem.out.println("加密结果： " + signatureResult)
		return signatureResult;
	}

	private SocialFriendSign() {
		throw new IllegalStateException("SocialFriendSign class");
	}

}
