import cryptoJs from 'crypto-js';
import { Base64 } from 'js-base64';
import { isObject } from '@utils/validate';

const encryptKey = '1q2w3e4r5t6y7u8i';
const encryptIv = '1234567812345678';

export const encryptByAES = (value) => {
  if (value === '') {
    return '';
  }
  let encryptValue = cryptoJs.enc.Utf8.parse(value);
  let keyHex = cryptoJs.enc.Utf8.parse(encryptKey);
  let ivHex = cryptoJs.enc.Utf8.parse(encryptIv);
  let encrypted = cryptoJs.AES.encrypt(encryptValue, keyHex, {
    iv: ivHex,
    mode: cryptoJs.mode.CBC,
    padding: cryptoJs.pad.Pkcs7
  });
  return encrypted.toString();
};

export const decryptByAES = (value) => {
  if (value === '') {
    return '';
  }
  let keyHex = cryptoJs.enc.Utf8.parse(encryptKey);
  let ivHex = cryptoJs.enc.Utf8.parse(encryptIv);
  let decrypted = cryptoJs.AES.decrypt(value, keyHex, {
    iv: ivHex,
    mode: cryptoJs.mode.CBC,
    padding: cryptoJs.pad.Pkcs7
  });
  return decrypted.toString(cryptoJs.enc.Utf8);
};

export const encryptByBase64 = (value) => {
  if (value === '') {
    return '';
  }
  // 如果是对象/数组的话，需要先JSON.stringify转换成字符串
  return Base64.encode(value);
};

export const encryptByMd5 = (value) => {
  if (value === '') {
    return '';
  }
  return cryptoJs.MD5(value);
};

export const uuid = () => {
  let s = [];
  let hexDigits = '0123456789abcdef';
  for (let i = 0; i < 36; i++) {
    let startPos = Math.floor(Math.random() * 0x10);
    s[i] = hexDigits.substring(startPos, startPos + 1);
  }
  s[14] = '4';
  let startPos = (s[19] & 0x3) | 0x8;
  s[19] = hexDigits.substring(startPos, startPos + 1);
  s[8] = s[13] = s[18] = s[23] = '-';
  return s.join('');
};

export const sortByKey = (obj) => {
  if (isObject(obj)) {
    let keySortArr = Object.keys(obj).sort();
    let sortObj = {};
    for (let i in keySortArr) {
      sortObj[keySortArr[i]] = obj[keySortArr[i]];
    }
    return sortObj;
  }
  return obj;
};

export const randomLenNum = (len, date) => {
  if (len <= 0) {
    len = 4;
  }
  if (len > 16) {
    len = 16;
  }
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substring(0, len || 4);
  if (date) {
    random = random + Date.now();
  }
  return random;
};

export const getRouter = (routers, path) => {
  let router;
  routers.forEach((item) => {
    if (path === item.path) {
      router = item;
    }
    if (item.children) {
      const data = getRouter(item.children, path);
      if (data !== undefined) {
        router = data;
      }
    }
  });
  return router;
};

export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.\d{3}/gm), '');
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
}
