import CryptoJS from 'crypto-js'

/**
 * AES128ECBEncrypt 加密方法
 */
export function AES128ECBEncrypt(inputText: any, key: any) {
  const inputArr = []
  while (inputText.length < 32) {
    inputText += '0'
  }
  for (let i = 0; i < inputText.length / 2; i++) {
    inputArr.push(Number.parseInt(inputText.substring(i * 2, i * 2 + 2), 16))
  }
  const inputParse = int8arrayParse(inputArr)
  const keyParse = CryptoJS.enc.Utf8.parse(key)
  const n = CryptoJS.AES.encrypt(inputParse, keyParse, {
    iv: [],
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.NoPadding,
  })
  const w = int8arrayStringify(n.ciphertext)
  const encryptStr = bufTohex(w.buffer)
  return encryptStr
}

export function bufTohex(buffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => (`00${x.toString(16)}`).slice(-2)).join('')
}

export function int8arrayParse(e: any) {
  const r = e.length
  const i = []
  let n = 0
  for (; n < r; n++) {
    i[n >>> 2] |= (255 & e[n]) << 24 - n % 4 * 8
  }
  return CryptoJS.lib.WordArray.create(i, r)
}

export function int8arrayStringify(t: any) {
  const e = t.words
  const r = t.sigBytes
  const i = new Int8Array(r)
  let n = 0
  for (; n < r; n++) {
    i[n] = e[n >>> 2] >> 24 - n % 4 * 8 & 255
  }
  return i
}
