/*
 * @Description: token aes加密
 * @Autor: tanglitong
 * @Date: 2020-08-12 11:00:01
 * @LastEditors: tanglitong
 * @LastEditTime: 2020-08-12 15:24:12
 */

// dev: VUE_APP_KEY_WORD = RT4yFCoxKAYIIPRw
// pro: VUE_APP_KEY_WORD = XGyhhVkqacubqo83

import CryptoJS from 'crypto-js'

/**
 * @description: 自定义token加密
 */
export const aesEncryptToken = (word, keyWord = process.env.VUE_APP_KEY_WORD) => {
  const random = randomn(6)
  const time = new Date().getTime()
  let wordJson = JSON.stringify({
    random: random,
    tokenStr: word,
    timestamp: time,
    sign: aesEncrypt(`${random}&${word}&${time}`, keyWord)
  })
  return aesEncrypt(wordJson, keyWord)
}

/**
 * @description: ase加密
 * @param {word} 要加密的内容
 * @param {keyWord} 密钥
 * @return {ase}
 */
function aesEncrypt(word, keyWord) {
  let key = CryptoJS.enc.Utf8.parse(keyWordDecrypt(keyWord))
  let srcs = CryptoJS.enc.Utf8.parse(word)
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString()
}

/**
 * @description: 解密aes密钥
 * @param {keyWord} 密钥
 * @return {keyWord} 
 */
function keyWordDecrypt(keyWord, chunk = 4, order = [0.5, 0.375, 0.125, 0.25]) {
  const keyWordArr = keyWord.split('')
  let mergeArr = []
  let mergeStr = ''
  for (let i = 0, j = keyWordArr.length; i < j; i += chunk) {
    mergeArr.push(keyWordArr.slice(i, i + chunk).join(''))
  }
  order.forEach(element => {
    mergeStr += (mergeArr[element * 8 - 1])
  });
  return mergeStr
}

/**
 * @description: 生成n位字母数字随机数
 * @param {n} 生成长度
 * @return {random} 
 */
function randomn(n) {
  let res = ''
  for (; res.length < n; res += Math.random().toString(36).substr(2).toUpperCase()) {}
  return res.substr(0, n)
}