package com.kym.common.utils;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.alibaba.fastjson2.JSONObject;
import com.kym.common.cache.PlatformCache;
import com.kym.common.constant.ResponseEnum;
import com.kym.common.exception.PlatformPushException;
import com.kym.entity.platform.response.PlatformResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 各互联互通平台AES加解密工具
 *
 * @author skyline
 */
@Slf4j
public class PlatformAesUtil {

    /**
     * AES：加密方式   CBC：工作模式   PKCS5Padding：填充模式
     */
    private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";


    /**
     * AES 加密操作
     *
     * @param dataSecret
     * @param dataSecretIv
     * @param content      待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String dataSecret, String dataSecretIv, String content) {

        if (content == null || content.isEmpty()) {
            return content;
        }

        try {
            /*
             * 新建一个密码编译器的实例，由三部分构成，用"/"分隔，分别代表如下
             * 1. 加密的类型(如AES，DES，RC2等)
             * 2. 模式(AES中包含ECB，CBC，CFB，CTR，CTS等)
             * 3. 补码方式(包含nopadding/PKCS5Padding等等)
             * 依据这三个参数可以创建很多种加密方式
             */
            Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);

            //偏移量
            IvParameterSpec zeroIv = new IvParameterSpec(dataSecretIv.getBytes(StandardCharsets.UTF_8));

            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);

            //使用加密秘钥
            SecretKeySpec skeySpec = new SecretKeySpec(dataSecret.getBytes(StandardCharsets.UTF_8), AES);
            //初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, zeroIv);
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            // 通过Base64转码返回
            return Base64.encodeBase64String(result);
        } catch (Exception ex) {
            Logger.getLogger(PlatformAesUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;

    }

    /**
     * AES 解密操作
     *
     * @param dataSecret
     * @param dataSecretIv
     * @param content
     * @return
     */
    public static String decrypt(String dataSecret, String dataSecretIv, String content) {
        if (content == null || content.isEmpty()) {
            return content;
        }

        try {
            //实例化
            Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
            IvParameterSpec zeroIv = new IvParameterSpec(dataSecretIv.getBytes(StandardCharsets.UTF_8));

            SecretKeySpec skeySpec = new SecretKeySpec(dataSecret.getBytes(StandardCharsets.UTF_8), AES);
            //SecretKeySpec skeySpec = getSecretKey(key);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, zeroIv);

            byte[] result = cipher.doFinal(Base64.decodeBase64(content));

            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            Logger.getLogger(PlatformAesUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
//    private static SecretKeySpec getSecretKey(final String key) {
//        //返回生成指定算法密钥生成器的 KeyGenerator 对象
//        KeyGenerator kg;
//        try {
//            kg = KeyGenerator.getInstance(AES);
//            //AES 要求密钥长度为 128
//            kg.init(128, new SecureRandom(key.getBytes()));
//            //生成一个密钥
//            SecretKey secretKey = kg.generateKey();
//            // 转换为AES专用密钥
//            return new SecretKeySpec(secretKey.getEncoded(), AES);
//        } catch (Exception ex) {
//            Logger.getLogger(PlatformAesUtil.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        return null;
//    }

    /**
     * 验签、解密推送消息
     *
     * @param platformName
     * @param json
     * @return
     */
    public static String signValidation(String platformName, JSONObject json) {
        var platform = PlatformCache.INSTANCE.getPlatformByName(platformName);
        // 验签 解密数据
        var OperatorID = json.getString("OperatorID");
        var Data = json.getString("Data");
        var TimeStamp = json.getString("TimeStamp");
        var Seq = json.getString("Seq");
        var Sig = json.getString("Sig");
        var signString = OperatorID + Data + TimeStamp + Seq;
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, platform.getUserSigSecret().getBytes());
        // 签名（转为大写）
        var sign = mac.digestHex(signString).toUpperCase();
        if (sign.equals(Sig)) {
            // 解密数据
            return PlatformAesUtil.decrypt(platform.getUserDataSecret(), platform.getUserDataSecretIv(), Data);
        } else {
            // 验签失败
            PlatformResponse platformResponse = new PlatformResponse();
            platformResponse.setRet(4001);
            platformResponse.setMsg(ResponseEnum.PLATFORM_PUSH_SIGN_FAIL.getMessage());
            log.error("{}推送数据验签失败，数据：{}", platformName, json);
            throw new PlatformPushException(ResponseEnum.PLATFORM_PUSH_SIGN_FAIL, platformResponse);
        }

    }

    /**
     * 构建平台参数（向谁请求数据则用谁的秘钥。OperatorID请求者的）
     *
     * @param platformName
     * @param params
     * @return
     */
    public static String buildPlatformParams(String platformName, String params) {
        var platform = PlatformCache.INSTANCE.getPlatformByName(platformName);
        // 使用DataSecret对data加密
        var dataStr = PlatformAesUtil.encrypt(platform.getDataSecret(), platform.getDataSecretIv(), params);
        // 时间戳
        var timeStamp = LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN);
        // 自增序列
        var seq = timeStamp.substring(timeStamp.length() - 4);
        // 使用SigSecret以HMAC-MD5算法对消息体签名（签名顺序：OperatorId、Data、TimeStamp、Seq）
        var signString = platform.getUserOperatorId() + dataStr + timeStamp + seq;
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, platform.getSigSecret().getBytes());
        // 签名（转为大写）
        var sign = mac.digestHex(signString).toUpperCase();
        return """
                {
                    "OperatorID":"%s",
                    "Data":"%s",
                    "TimeStamp":"%s",
                    "Seq":"%s",
                    "Sig":"%s"
                }
                """.formatted(platform.getOperatorId(), dataStr, timeStamp, seq, sign);
    }
}
