import CryptoJS from 'crypto-js'
// 随机生成 UUID 的辅助函数
export function randomUUID() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  const uuid = new Array(36);
  let rnd = 0;
  let r;
  for (let i = 0; i < 36; i++) {
      if (i === 8 || i === 13 || i === 18 || i === 23) {
          uuid[i] = '-';
      } else if (i === 14) {
          uuid[i] = '4';
      } else {
          if (rnd <= 0x02) rnd = (0x2000000 + Math.random() * 0x1000000) | 0;
          r = rnd & 0xf;
          rnd = rnd >> 4;
          uuid[i] = chars[i === 19? (r & 0x3) | 0x8 : r];
      }
  }
  return uuid.join('').replace(/-/g, '').toLowerCase();
}

/**
* 随机生成 AES 密钥
* @returns {CryptoJS.lib.WordArray}
*/
export function generateAesKey() {
  return CryptoJS.enc.Utf8.parse(randomUUID());
}

/**
* Base64 编码
* @param str {CryptoJS.lib.WordArray}
* @returns {string}
*/
export function encryptBase64(str) {
  return CryptoJS.enc.Base64.stringify(str);
}

/**
* 使用公钥加密
* @param message {string} 加密内容
* @param aesKey {CryptoJS.lib.WordArray} aesKey
* @returns {string}
*/
export function encryptWithAes(message, aesKey) {
  const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
}

/**
* 解密 Base64
* @param str {string}
* @returns {CryptoJS.lib.WordArray}
*/
export function decryptBase64(str) {
  return CryptoJS.enc.Base64.parse(str);
}

/**
* 使用密钥对数据进行解密
* @param message {string}
* @param aesKey {CryptoJS.lib.WordArray}
* @returns {string}
*/
export function decryptWithAes(message, aesKey) {
  const decrypted = CryptoJS.AES.decrypt(message, aesKey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}