package com.yeejoin.amos.boot.module.common.api.crypto;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import java.nio.charset.StandardCharsets;

public class AESUtil {

    private static final String key = "amos-tzs-app-991";
    private static final String iv = "amos-tzs-app-9iv";

    private final AES aes;

    private AESUtil(Mode mode, Padding padding, byte[] key, byte[] iv) {
        aes = new AES(mode, padding, key, iv);
    }

    private static volatile AESUtil instance = null;

    private static AESUtil getInstance() {
        if (instance == null) {
            synchronized (AESUtil.class) {
                if (instance == null) {
                    try {
                        instance = new AESUtil(Mode.CBC, Padding.PKCS5Padding, key.getBytes(StandardCharsets.UTF_8), iv.getBytes(StandardCharsets.UTF_8));
                    } catch (Exception e) {
                        // 加密初始化失败，使用空实现
                        instance = new AESUtil() {
                            protected String doEncrypt(String data) {
                                return data;
                            }
                            protected String doDecrypt(String data) {
                                return data;
                            }
                        };
                    }
                }
            }
        }
        return instance;
    }

    // 空构造函数，用于创建失败时的备用实例
    private AESUtil() {
        this.aes = null;
    }

    public static String encrypt(String data) {
        return getInstance().doEncrypt(data);
    }

    public static String decrypt(String data) {
        return getInstance().doDecrypt(data);
    }

    // 子类覆盖的方法
    protected String doEncrypt(String data) {
        assert aes != null;
        return aes.encryptBase64(data);
    }

    protected String doDecrypt(String data) {
        assert aes != null;
        return aes.decryptStr(data, StandardCharsets.UTF_8);
    }

}
