import CryptoJS from "crypto-js";

// 递归获取底层子数组
export function findBottomSubarrays(arr) {
  let bottomSubarrays = [];
  function recursiveSearch(subArr) {
    for (let item of subArr) {
      if (item.children && item.children.length) {
        recursiveSearch(item.children);
      } else {
        bottomSubarrays.push(...subArr);
        break;
      }
    }
  }
  recursiveSearch(arr);
  return bottomSubarrays;
}

// 加密数据
export let encrypt = (str, keyStr, ivStr) => {
  keyStr = keyStr ? keyStr : "0000000671595991";
  ivStr = ivStr ? ivStr : "tdrdadq59tbss5n7";
  //密钥16位
  let key = CryptoJS.enc.Utf8.parse(keyStr);
  //加密向量16位
  let iv = CryptoJS.enc.Utf8.parse(ivStr);
  let encrypted = CryptoJS.AES.encrypt(str, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });

  return encrypted.toString();
};
// 解密
export const decrypt = (word, keyStr, ivStr) => {
  keyStr = keyStr ? keyStr : "0000000671595991";
  ivStr = ivStr ? ivStr : "tdrdadq59tbss5n7";
  let key = CryptoJS.enc.Utf8.parse(keyStr);
  let iv = CryptoJS.enc.Utf8.parse(ivStr);

  let decrypt = CryptoJS.AES.decrypt(word, key, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return decrypt.toString(CryptoJS.enc.Utf8);
};

/**
 * 加密存储临时数据并解析对象
 */
const aseKey = "**_FXxx_1234_KEY";
const KEY = "KEY_EXTRA";
export class SessionCrypto {
  // 加密
  static setItem(key = KEY, value = "") {
    if (typeof key === "string") {
      const stringify = JSON.stringify(value);
      const encrypt = CryptoJS.AES.encrypt(
        stringify,
        CryptoJS.enc.Utf8.parse(aseKey),
        {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7,
        }
      ).toString();
      window.sessionStorage.setItem(key, encrypt);
      return encrypt;
    }
  }
  // 解密
  static getItem(key = KEY) {
    const ssStr = window.sessionStorage.getItem(key) || "";
    try {
      if (ssStr) {
        const decrypt = CryptoJS.AES.decrypt(
          ssStr,
          CryptoJS.enc.Utf8.parse(aseKey),
          {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
          }
        ).toString(CryptoJS.enc.Utf8);
        const parseStr = JSON.parse(decrypt);
        return parseStr;
      }
      return "";
    } catch (e) {
      return "";
    }
  }
  // 删除
  static remove(key) {
    window.sessionStorage.removeItem(key);
  }
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}
