import md5 from 'js-md5';
// aes-decrypt.js
const authCode = localStorage.getItem('authCode');
const sysCode = localStorage.getItem('sysCode');
const secretKey = sysCode+authCode

// Base64 转 Uint8Array（保持与后端一致）
function base64ToArrayBuffer(base64) {
    const binaryString = atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes;
}

// Uint8Array 转 Base64（使用标准编码，与后端兼容）
function arrayBufferToBase64(buffer) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    for (let i = 0; i < bytes.byteLength; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary); // 标准 Base64 编码
}

// 密钥派生函数（与后端逻辑完全一致）
function deriveKey(secretKey) {
    if (!secretKey || typeof secretKey !== 'string') {
        throw new Error('密钥不能为空');
    }
    const hexHash = md5(secretKey);
    const bytes = [];
    for (let i = 0; i < hexHash.length; i += 2) {
        bytes.push(parseInt(hexHash.substr(i, 2), 16));
    }
    return new Uint8Array(bytes.slice(0, 16)); // 截断为16字节，与后端一致
}

// 生成随机 IV
function generateIV() {
    return window.crypto.getRandomValues(new Uint8Array(16));
}

// AES 加密函数
export async function encryptAES(plaintext) {
    try {
        // 生成密钥
        const key = deriveKey(secretKey);

        // 生成随机 IV
        const iv = generateIV();

        // 将明文转换为 UTF-8 ArrayBuffer
        const plaintextArrayBuffer = new TextEncoder().encode(plaintext);

        // 导入密钥
        const cryptoKey = await window.crypto.subtle.importKey(
            'raw', key, { name: 'AES-CBC', iv }, false, ['encrypt']
        );

        // 执行加密（默认使用 PKCS#7 填充，与后端 PKCS#5 兼容）
        const encryptedArrayBuffer = await window.crypto.subtle.encrypt(
            { name: 'AES-CBC', iv }, cryptoKey, plaintextArrayBuffer
        );

        // 合并 IV 和密文
        const encryptedBytesWithIV = new Uint8Array(iv.length + encryptedArrayBuffer.byteLength);
        encryptedBytesWithIV.set(iv, 0);
        encryptedBytesWithIV.set(new Uint8Array(encryptedArrayBuffer), iv.length);

        // 转换为标准 Base64
        const encryptedBase64 = arrayBufferToBase64(encryptedBytesWithIV);
        console.log('加密成功:', encryptedBase64)
        return encryptedBase64;
    } catch (error) {
        console.error('加密失败:', error);
        throw error;
    }
}
// AES 解密函数
export async function decryptAES(encryptedData) {
    try {
        console.log('开始解密...');

        // 验证输入
        if (!encryptedData || !secretKey) {
            throw new Error('加密数据或密钥为空');
        }

        // 生成密钥
        const key = deriveKey(secretKey);

        // 转换数据
        const encryptedBytes = base64ToArrayBuffer(encryptedData);
        console.log('加密数据总长度:', encryptedBytes.length);

        // 提取 IV 和密文
        const iv = encryptedBytes.slice(0, 16);
        const ciphertext = encryptedBytes.slice(16);
        console.log('IV 长度:', iv.length);
        console.log('密文长度:', ciphertext.length);

        // 导入密钥
        const cryptoKey = await window.crypto.subtle.importKey(
            'raw', key, {name: 'AES-CBC', iv}, false, ['decrypt']
        );

        // 执行解密
        const decryptedArrayBuffer = await window.crypto.subtle.decrypt(
            {name: 'AES-CBC', iv}, cryptoKey, ciphertext
        );

        // 转换为字符串
        const decryptedText = new TextDecoder('utf-8').decode(decryptedArrayBuffer);
        console.log('解密成功:', decryptedText);

        return decryptedText;
    } catch (error) {
        console.error('解密失败:', error);
        throw error;
    }
}