package cn.com.poc.common.utils;

import cn.com.yict.framemax.core.i18n.I18nMessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author alex.yao
 * @date 2023/11/22 23:35
 */
public class SignUtil {

    private static MessageDigest md;

    private static Logger logger = LoggerFactory.getLogger(SignUtil.class);

    /**
     * 鉴权签名
     *
     * @param appSecret secret
     * @param timeStamp 时间戳
     * @param api       调用API
     */
    public static String sign(String appSecret, String timeStamp, String api) {
        Assert.notBlank(appSecret);
        Assert.notBlank(timeStamp);
        Assert.notBlank(api);
        String str = appSecret + timeStamp + api;
        str = str.toLowerCase();
        try {
            if (md == null) {
                md = MessageDigest.getInstance("SHA-1");
            }
            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            logger.info("to sign:{}", sb.toString());
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 签名校验
     *
     * @param sign
     * @param appSecret
     * @param timestamp
     * @param api
     * @return
     */
    public static boolean signVerification(String sign, String appSecret, String timestamp, String api) {
        //计算签名
        logger.info("sign:{},appSecret:{},timestamp:{},api:{}", sign, appSecret, timestamp, api);
        if (!sign(appSecret, timestamp, api).equals(sign)) {
            throw new I18nMessageException("exception/error.signature");
        }
        //匹对时间戳是否超过签名有效时间
        long s = (System.currentTimeMillis() - Long.parseLong(timestamp)) / (1000 * 60);
        if (s < -1L) {
            throw new I18nMessageException("exception/signature.validity.time.exception");
        }
        if (s > 5L) {
            throw new I18nMessageException("exception/signature.has.expired");
        }
        return true;
    }

}
