package com.friday.custody.api.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class HTSCSignGenerator {

    /**
     *
     * @param appSecret
     * @param dataMap key:appId,requestParams,timestamp,url
     * @return
     */
    public static  String genSign(String appSecret, Map<String,String> dataMap){
        log.info("【签名计算开始】appSecret={},dataMap={}",appSecret,dataMap);
        try{
            //1.对appSecret进行解码
            byte[] key1= Base64.getDecoder().decode(appSecret.getBytes(StandardCharsets.UTF_8));
            //2.对参数key小写化排序并组装key1:value1,key2:value
            List<String> dataStrList = new ArrayList<>();
            for (String key:dataMap.keySet()){
                String value = dataMap.get(key);
                dataStrList.add(key.toLowerCase()+":"+value);
            }
            Collections.sort(dataStrList);
            String dataStr = join(dataStrList, ",");
            log.info("【签名计算参数拼接】dataStr={}",dataStr);
            //3. 进行计算签名
            String sign = encryptHmac(key1,dataStr.getBytes("UTF-8"));
            log.info("【签名计算结束】sign={}",sign);
            return  sign;
        }catch (Exception e){
            log.error("签名计算异常: ",e);
        }
        return  null;
    }
    
    /**
     * HmacSHA256签名
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptHmac(byte[] key, byte[] data) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);

        byte[] resultBytes = mac.doFinal(data);
        String resultString = new String(Hex.encodeHex(resultBytes,false));

        return resultString;
    }
    
    private static String join(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        for(String ele : list) {
            if(sb.length() > 0) {
                sb.append(separator);
            }
            sb.append(ele);
        }
        return sb.toString();
    }

}
