// const CryptoJS = require('crypto-js');
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
import AES from 'crypto-js/aes';
import SHA1 from 'crypto-js/sha1';
import MD5 from 'crypto-js/md5';
import SparkMD5 from 'spark-md5';

export const getBase64 = (content) => {
  const words = Utf8.parse(content);
  const base64Str = Base64.stringify(words);

  return base64Str;
};

export const getAES = (content) => {
  const KEY = '1234567890123456';
  const IV = '1234567890123456';

  var key = Utf8.parse(KEY);
  var iv = Utf8.parse(IV);
  var encrypted = AES.encrypt(content, key, { iv: iv });
  return encrypted.toString();
};

/**
 * 获取authorisation
 * @param {Object} infos 相关信息
 * @param {String} type 类别：secret、token两种
 */
export const getAuthorization = (infos, type) => {
  // {type} {invoker}:base64(sha1(method&uri&timestamp&{secret}))
  if (type === 'secret') {
    // accessKey | method&uri&timestamp&accessSecret
    const str = `${infos.method.toLowerCase()}&${infos.uri}&${
      infos.timestamp
    }&${infos.accessSecret}`;
    const sign = Base64.stringify(SHA1(str));
    return `Secret ${infos.accessKey}:${sign}`;
  } else if (type === 'token') {
    // userId | method&uri&timestamp&token
    const str = `${infos.method.toLowerCase()}&${infos.uri}&${
      infos.timestamp
    }&${infos.token}`;
    const sign = Base64.stringify(SHA1(str));
    return `Token ${infos.sessionId}:${sign}`;
  }
};

/**
 *
 * @param {any} str 字符串
 */
export const getMD5 = (content) => {
  return MD5(content);
};

// export const getFileMD5 = (file) => {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.onloadend = function () {
//       const arrayBuffer = reader.result;
//       resolve(MD5(arrayBuffer).toString());
//     };
//     reader.onerror = function (err) {
//       reject(err);
//     };
//     reader.readAsArrayBuffer(file);
//   });
// };

export const getFileMD5 = (dataFile) => {
  return new Promise((rs, rj) => {
    var fileReader = new FileReader();
    var spark = new SparkMD5(); //创建md5对象（基于SparkMD5）
    if (dataFile.size > 1024 * 1024 * 10) {
      var data1 = dataFile.slice(0, 1024 * 1024 * 10); //将文件进行分块 file.slice(start,length)
      fileReader.readAsBinaryString(data1); //将文件读取为二进制码
    } else {
      fileReader.readAsBinaryString(dataFile);
    }
    fileReader.onload = function (e) {
      spark.appendBinary(e.target.result);
      var md5 = spark.end();
      rs(md5);
    };
    fileReader.onerror = function (err) {
      rj(err);
    };
  });
};
