import CryptoJS from 'crypto-js'


const KEY = 'wkwwkwwkwwkwwkwA'

/**
 * * 加密
 * @param data { string }
 * @returns { string } 加密后的数据
 */
export const cryptoEncode = (data) => {
  const key = CryptoJS.enc.Utf8.parse(KEY);
  const iv = CryptoJS.lib.WordArray.random(16); // 随机生成16字节的IV
  const encrypted = CryptoJS.AES.encrypt(data, key, {
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
    iv: iv,
  });
  // 将IV与加密后的数据拼接并以特定格式返回，以便在Java中分离IV和加密后的数据
  return iv.toString(CryptoJS.enc.Base64) + encrypted.toString();
};

export const cryptoDecode = (data) => {
  const key = CryptoJS.enc.Utf8.parse(KEY);
  const ivBase64 = data.substring(0, 24); // 16字节的Base64编码是24字符
  const encryptedBase64 = data.substring(24);
  const iv = CryptoJS.enc.Base64.parse(ivBase64);
  const decrypted = CryptoJS.AES.decrypt(encryptedBase64, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
};


function getRandomString16() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < 16; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}
export function AES_CBC_ENCRYPT(val) {
  const IV = getRandomString16();
  const KEY = '05f8f563b95103e1';
  const secretKey = CryptoJS.enc.Utf8.parse(KEY);
  const ivk = CryptoJS.enc.Utf8.parse(IV);
  let ivHex = CryptoJS.enc.Base64.stringify(ivk);
  let messageHex = CryptoJS.enc.Utf8.parse(val);
  let encrypted = CryptoJS.AES.encrypt(messageHex, secretKey, {
    iv: ivk,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let result = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  return {
    ciphertext: result,
    iv: ivHex,
  };
}
export function generateSign(data) {
  const KEY = '05f8f563b95103e1';
  delete data.sign;
  const keys = Object.keys(data).sort();
  let str = keys.map(key => {
    return `${key}=${encodeURIComponent(data[key])}`
  }).join('&');
  data.sign = CryptoJS.MD5(`${str}${KEY}`).toString();
  return data;
}
