package cd.casic.plugin.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class SM4EncryptUtil {
    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//    @Value("${encryption-key}")
    private static String key = "abcdabcdabcdabcd";

    public static String encrypt(String str) {
        SM4 sm4 = SmUtil.sm4(key.getBytes());
        String s = sm4.encryptHex(str.getBytes());
        return s;
    }
    public static String decrypt(String str) {
        SM4 sm4 = SmUtil.sm4(key.getBytes());
        String s = sm4.decryptStr(str);
        return s;
    }

    public static void main(String[] args) {

        String encrypt = encrypt(LocalDateTime.now().plusMonths(1).format(dateTimeFormatter));
        System.out.println(encrypt);
        System.out.println(decrypt(encrypt));
    }
    public static boolean checkLicense(String license, String pluginId) {
        // 逻辑是 不存在证书直接放行 存在证书需要判断证书是否过期
        if (ObjectUtil.isNotEmpty(license)) {
            String decrypt = SM4EncryptUtil.decrypt(license);
            LocalDateTime overDueTime = LocalDateTime.parse(decrypt, dateTimeFormatter);
            LocalDateTime now = LocalDateTime.now();
            if (now.isAfter(overDueTime)) {
                log.warn("plugin:[{}] license expired!", pluginId);
                return false;
            }
        }
        return true;
    }
}
