import CryptoJS from "crypto-js";

const key = CryptoJS.enc.Utf8.parse("daac3ae52eff4cec"); // 16位

const encrypt = (word) => {
  let encrypted = "";
  if (typeof word === "string") {
    const src = CryptoJS.enc.Utf8.parse(word);
    encrypted = CryptoJS.AES.encrypt(src, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
  } else if (typeof word === "object") {
    // 对象格式的转成json字符串
    const data = JSON.stringify(word);
    const src = CryptoJS.enc.Utf8.parse(data);
    encrypted = CryptoJS.AES.encrypt(src, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
  }
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
};
function decryptAes(params) {
  try {
    // 如果params不是对象或为空，直接返回
    if (!params || typeof params !== "object") {
      return params;
    }

    // 如果没有encryptData字段，直接返回原参数
    if (!params.encryptData) {
      return params;
    }

    const key = CryptoJS.enc.Utf8.parse("fa4e0fae59534676"); // 16 bytes key for AES

    const bytes = CryptoJS.AES.decrypt(params.encryptData, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    const decryptedText = bytes.toString(CryptoJS.enc.Utf8);
    const decryptedData = JSON.parse(decryptedText);

    // 递归调用解密
    return decryptAes(decryptedData);
  } catch (e) {
    console.info(e);
  }
}

export { encrypt, decryptAes };
