// const CryptoJS = require('crypto-js') //引用AES源码js
import CryptoJS from 'crypto-js'

const key = CryptoJS.enc.Utf8.parse('4-[nyNW8rO0zT#Wx') //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('U8noy&QjEQ[ffjWm') //十六位十六进制数作为密钥偏移量

//解密方法
const Decrypt = function (word) {
  let encryptedHexStr = CryptoJS.enc.Hex.parse(word)
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  let decrypt = CryptoJS.AES.decrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

//加密方法
const Encrypt = function (word) {
  let srcs = CryptoJS.enc.Utf8.parse(word)
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.ciphertext.toString().toUpperCase()
}

const splitCheckItems = function (str) {
  return str.split('；')
}

const dateFormat = function (fmt, date) {
  let ret
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  }
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
    }
  }
  return fmt
}

// 图片预加载
const preloader = function (imgList, next) {
  let count = 0
  // let loadingInstance1 = Toast({
  //     type: 'loading',
  //     message: '加载中...',
  //     forbidClick: true,
  // });
  for (let img of imgList) {
    let image = new Image()
    image.src = img.imgUrl
    image.onload = () => {
      count++
      if (count == imgList.length) {
        // loadingInstance1.close();
        // Toast.clear();
        next()
      }
    }
  }
}

// 认知任务匹配
const taskMatch = function (id, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].id == id) {
      return arr[i]
    }
  }
}

// sessionStorage 加解密处理
let oSessionStorage = {
  setItem(key, value) {
    sessionStorage.setItem(Encrypt(key), Encrypt(value))
  },
  getItem(key) {
    if (sessionStorage.getItem(Encrypt(key))) {
      return Decrypt(sessionStorage.getItem(Encrypt(key)))
    } else {
      return null
    }
  },
  removeItem(key) {
    sessionStorage.removeItem(Encrypt(key))
  },
}

export { splitCheckItems, dateFormat, Decrypt, Encrypt, preloader, taskMatch, oSessionStorage }
