import { getEnvConfig } from './env'

const envConfig = getEnvConfig()
const AES_KEY = envConfig.aesKey || '12345678901234567890123456789012'
const AES_IV = envConfig.aesIv || '1234567890123456'

const CryptoJS = require('../static/utils/crypto-js.min.js')

function encrypt(data) {
  return new Promise((resolve, reject) => {
    try {
      let str = typeof data === 'string' ? data : JSON.stringify(data)
      let encrypted = CryptoJS.AES.encrypt(
        CryptoJS.enc.Utf8.parse(str),
        CryptoJS.enc.Utf8.parse(AES_KEY),
        {
          iv: CryptoJS.enc.Utf8.parse(AES_IV),
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        }
      )
      resolve(encrypted.toString())
    } catch (e) {
      console.error('加密失败', e)
      reject(e)
    }
  })
}

function decrypt(data) {
  return new Promise((resolve, reject) => {
    try {
      let decrypted = CryptoJS.AES.decrypt(
        data,
        CryptoJS.enc.Utf8.parse(AES_KEY),
        {
          iv: CryptoJS.enc.Utf8.parse(AES_IV),
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        }
      )
      let str = decrypted.toString(CryptoJS.enc.Utf8)
      try {
        resolve(JSON.parse(str))
      } catch {
        resolve(str)
      }
    } catch (e) {
      console.error('解密失败', e)
      reject(e)
    }
  })
}

export default {
  encrypt,
  decrypt
}