package com.yuchen.saas.park.api.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.UUID;

/**
 * @Author: baichaojie
 * @CreateTime: 2024/10/30 15:01
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
public class ThirdSignatureUtil {

    private static final String REQ_PARAM_FORMAT = "version=%s&clientId=%s&timestamp=%s&nonce=%s&signatureVersion=%s";

    /**
     * 根据参数生成签名
     *
     * @param clientId
     * @param clientSecret
     * @param version
     * @param timestamp
     * @param nonce
     * @param signatureVersion
     * @return
     */
    public static String genSignature(String clientId, String clientSecret, String version, String timestamp, String nonce, String signatureVersion) {
        // 拼接参与签名字符串
        String paramsEncode = String.format(REQ_PARAM_FORMAT, version, clientId, timestamp, nonce, signatureVersion);
        String signature = "";
        try {
            //signature = HmacSha1Util.genHmac(paramsEncode, clientSecret).replaceAll("[\\s*\t\n\r]", "");
            signature = HmacSha1Util.getSHA256(paramsEncode);

        } catch (Exception e) {
            log.error("genSignature exception", e);
            throw new RuntimeException(e);
        }
        return signature;
    }

    /**
     * 判断签名是否合法
     *
     * @param currentSignature
     * @param clientId
     * @param clientSecret
     * @param version
     * @param timestamp
     * @param nonce
     * @param signatureVersion
     * @return
     */
    public static boolean isValidSignature(String currentSignature, String clientId, String clientSecret, String version, String timestamp, String nonce, String signatureVersion) {
        String signature = genSignature(clientId, clientSecret, version, timestamp, nonce, signatureVersion);
        return StringUtils.equals(currentSignature, signature);
    }

    public static void main(String[] args) {
        String clientId = "1024";
        String clientSecret = "abc";
        String version = "1.0";
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = UUID.randomUUID().toString();
        String signatureVersion = "1.1";
        String signature = genSignature(clientId, clientSecret, version, timestamp, nonce, signatureVersion);
        System.out.println(signature);
    }
}
