const CryptoJS = require('crypto-js')

const _key = CryptoJS.enc.Utf8.parse('abczyxzhaoli')
const _iv = CryptoJS.enc.Utf8.parse('jkbm')

/**
 * 对称加密，加密方法
 * @param {[string]} data 要加密的数据字符串
 * @returns - 返回加密过后的字符串
 */
const encryptData = (data) => {
  let encryptedStr = ''
  try {
    let srcs = CryptoJS.enc.Utf8.parse(data)
    let encrypted = CryptoJS.AES.encrypt(srcs, _key, { iv: _iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
    encryptedStr = encrypted.ciphertext.toString().toUpperCase()
  } catch (e) {
    encryptedStr = data
    console.error('加密错误', data)
    console.error(e)
  }
  return encryptedStr
}

/**
 * 对称解密，解密方法
 * @param {[string]} data 要解密的数据字符串
 * @returns - 返回解密过后的字符串
 */
const decryptData = (data) => {
  let decryptedStr = ''
  try {
    let srcs = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(data))
    let decrypt = CryptoJS.AES.decrypt(srcs, _key, { iv: _iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
    decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  } catch (e) {
    decryptedStr = data
    console.error('解密错误', data)
    console.error(e)
  }
  return decryptedStr.toString()
}

module.exports = {
  encryptData: encryptData,
  decryptData: decryptData
}
