// utils/crypto-js-adapter.js
// 适配微信小程序的 CryptoJS 工具
import JSEncrypt from '@/components/jsencrypt/jsencrypt.min.js';
// 引入 CryptoJS 核心文件
import Core from '../crypto-js/core.js';
import AES from '../crypto-js/aes.js';
import Utf8 from '../crypto-js/enc-utf8.js';
import Base64 from '../crypto-js/enc-base64.js';
import Hex from '../crypto-js/enc-hex.js';
// import CBC from '../crypto-js/mode-cbc.js';
import CryptoJS from '../crypto-js/index.js'
import Pkcs7 from '../crypto-js/pad-pkcs7.js';

// 适配微信小程序的随机数生成器
function wxGetRandomValues(length) {
	return new Promise((resolve, reject) => {
		wx.getRandomValues({
			length: length,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}
// 将ArrayBuffer转换为CryptoJS WordArray
function arrayBufferToWordArray(arrayBuffer) {
	const uint8Array = new Uint8Array(arrayBuffer);
	console.log(uint8Array, '333')
	const words = [];

	for (let i = 0; i < uint8Array.length; i += 4) {
		let word = 0;
		for (let j = 0; j < 4; j++) {
			if (i + j < uint8Array.length) {
				word |= uint8Array[i + j] << (24 - j * 8);
			}
		}
		words.push(word);
	}

	return CryptoJS.lib.WordArray.create(words, uint8Array.length);
}
Core.lib.WordArray.random = async function(nBytes) {
	// 创建一个16字节的Uint8Array
	const res = await wxGetRandomValues(nBytes);
	console.log(res)
	const ivWordArray = arrayBufferToWordArray(res.randomValues);
	console.log(ivWordArray.words, '111')
	// 转换为十六进制字符串并截取前16字节（32个字符）
	const hexString = ivWordArray.toString();
	const ivValue = hexString.substring(0, 32);
	console.log(ivValue, hexString, '000')
	return hexString

};


/**
 * AES加密（使用CryptoJS）
 * @param {string} data 要加密的数据
 * @param {string} key 密钥
 * @param {string} iv 初始化向量（十六进制格式）
 * @returns {Promise<{encrypted: string, iv: string}>}
 */
async function encrypt(data, key, iv = null) {
	try {
		// 生成随机IV（如果未提供）
		if (!iv) {
			iv = await Core.lib.WordArray.random(16);
		}

		// 执行加密
		const encrypted = AES.encrypt(
			JSON.stringify(data),
			CryptoJS.enc.Utf8.parse(key), {
				iv: CryptoJS.enc.Utf8.parse(iv),
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.Pkcs7
			});

		return {
			encrypted: encrypted.toString(),
			iv: iv
		};
	} catch (error) {
		console.error('AES加密失败:', error);
		throw error;
	}
}

/**
 * AES解密（使用CryptoJS）
 * @param {string} encryptedData Base64格式的加密数据
 * @param {string} key 密钥
 * @param {string} iv 初始化向量（十六进制格式）
 * @returns {Promise<string>}
 */
async function decrypt(encryptedData, key, iv) {
	try {

		const decrypted = AES.decrypt(encryptedData, CryptoJS.enc.Utf8.parse(iv), {
			iv: CryptoJS.enc.Utf8.parse(iv),
			mode: CryptoJS.mode.CBC,
			padding: Pkcs7
		});

		return decrypted.toString(Utf8);
	} catch (error) {
		console.error('AES解密失败:', error);
		throw error;
	}
}

/**
 * 生成随机密钥
 * @param {number} length 密钥长度（16, 24, 32）
 * @returns {Promise<string>}
 */
async function generateKey(length = 32) {
	const randomKey = await Core.lib.WordArray.random(length);
	return Hex.stringify(randomKey);
}

/**
 * 生成随机IV
 * @returns {Promise<string>}
 */
async function generateIV() {
	const randomIv = await Core.lib.WordArray.random(16);
	return Hex.stringify(randomIv);
}


	// 生成密钥对
	function generateRSAKeyPair(){
		 const keySize = parseInt(1024);
		        const encryptor = new JSEncrypt({ default_key_size: keySize });
		        
		        encryptor.getKey();
		        
		        const publicKey = encryptor.getPublicKey();
		        const privateKey = encryptor.getPrivateKey();
				console.log(publicKey,privateKey)
	}
	// rsa加密
	function rsaEncrypt(publicKey,data) {
	  const encrypt = new JSEncrypt();
	  encrypt.setPublicKey(publicKey);
	  var time = +new Date();
	  var str2 = data;
	  return encrypt.encrypt(str2)
	}
	// ras解密
	function rsaDecrypt(PrivateKey, data) {
	  const encrypt = new JSEncrypt();
	  encrypt.setPrivateKey(PrivateKey);
	  return encrypt.decrypt(data);
	}


export default {
	encrypt,
	decrypt,
	generateKey,
	generateIV,
	generateRSAKeyPair,
	rsaEncrypt,
	rsaDecrypt
};