import { Toast } from 'vant';
// import { CryptoJS } from './aes';
// import { JSEncrypt } from 'jsencrypt';
// if (process.client) {
//   require('jsencrypt');
// }

import { getPubKey } from '@/api/login';

let pubKey = '';

// generate key
function getAesKey(len) {
  len = len || 16;
  var aesKey = '';
  var strList =
    '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var strLen = strList.length;
  for (var i = 0; i < len; i++) {
    aesKey += strList.charAt(Math.floor(Math.random() * strLen));
  }
  return aesKey;
}

// 加密传参,发送请求
async function sendEncryptRequest(content, cb) {
  console.log('content', content);
  content = JSON.stringify(content); // 后端要求转 string
  const params = null;
  if (pubKey) {
    // pubKey获取过就不用再获取了
    const params = formatContent(content, pubKey);
    cb && cb(params);
  } else {
    handleGetPubKey(content, cb);
  }
  return params;
}

// get public key
function handleGetPubKey(content, cb) {
  // debugger;
  getPubKey().then((res) => {
    // console.log('>>>>>>>>>>>>>>>>>>>> publicKey: ', res);
    /* if(res.status && res.status === 200) {
        res = res.data;
      }*/
    console.log('res------', res);
    // debugger;
    if (res.code == '000000') {
      pubKey = res.data;
      if (cb) {
        const params = formatContent(content, pubKey);
        cb && cb(params);
      }
    } else {
      Toast({
        message: (res && res.message) || '接口出错',
        duration: 1500,
      });
    }
  });
}

// format account params
function formatContent(content, pubKey) {
  // obj为具体的json传参
  const aesKey = getAesKey(16);
  const params = {
    key: '',
    content: '',
  };

  params.content = AesEncrypt(content, aesKey);
  params.key = RsaEncrypt(aesKey, pubKey);
  return params;
}

// AES encrypt
function AesEncrypt(content, aesKey) {
  const sKey = CryptoJS.enc.Utf8.parse(aesKey);
  const sContent = CryptoJS.enc.Utf8.parse(content);
  const encrypted = CryptoJS.AES.encrypt(sContent, sKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
}

// RSA encrypt
function RsaEncrypt(aesKey, pubKey) {
  const _encrypt = new JSEncrypt();
  const boss_public_key = pubKey;
  _encrypt.setPublicKey(boss_public_key);
  const encrypted = _encrypt.encrypt(aesKey);
  return encrypted;
}

export {
  getAesKey,
  sendEncryptRequest,
  handleGetPubKey,
  formatContent,
  AesEncrypt,
  RsaEncrypt,
};
