import CryptoJS from "crypto-js";
const utils = {
  aesEncrypt: function(text) {
    /* aes加密 */
    let key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF"); /* 密钥 */
    let iv = CryptoJS.enc.Utf8.parse("ABCDEF1234123412"); /* 密钥偏移量 */
    let srcs = CryptoJS.enc.Utf8.parse(text);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString().toLowerCase();
  },
  aesDecrypt: function(text) {
    /* aes解密 */
    let key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF"); /* 密钥 */
    let iv = CryptoJS.enc.Utf8.parse("ABCDEF1234123412"); /* 密钥偏移量 */
    let encryptedHexStr = CryptoJS.enc.Hex.parse(text);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  },
  checkIsLogin: () => {
    let loginUserInfo = utils.getLoginUserInfo();
    if (loginUserInfo && JSON.parse(decodeURIComponent(loginUserInfo)).token) {
      return true;
    } else {
      return false;
    }
  },
  getLoginUserInfo: () => {
    // let loginUserInfo = utils.storage.fetch("loginUserInfo");
    let loginUserInfo = utils.getCookie("loginUserInfo");
    return loginUserInfo;
  },
  setCookie: (key, value = "", exdays = 1) => {
    if (typeof window === "undefined") {
      // console.log('此方法只支持在浏览器中执行')
      return false;
    }
    if (!key) {
      // console.log('请传入cookie name')
      return false;
    }
    const d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    document.cookie = `${key}=${value}; path=/; expires=${d.toGMTString()}`;
  },
  getCookie: key => {
    if (typeof window === "undefined") {
      // console.log('此方法只支持在浏览器中执行')
      return false;
    }
    if (!key) {
      // console.log('请传入cookie name')
      return false;
    }
    const cookieStr = document.cookie;
    if (cookieStr.length > 0) {
      let cStart = cookieStr.indexOf(key + "=");
      if (cStart !== -1) {
        cStart = cStart + key.length + 1;
        let cEnd = cookieStr.indexOf(";", cStart);
        if (cEnd === -1) cEnd = cookieStr.length;
        return unescape(cookieStr.substring(cStart, cEnd));
      }
    }
    return "";
  },
  /* 判断是否QQ */
  checkIsQQ: () => {
    let ua = window.navigator.userAgent;
    if (ua.match(/QQ\/[0-9]/i)) {
      return true;
    } else {
      return false;
    }
  },
  /* 判断是否微信 */
  checkIsWeixin: () => {
    let ua = window.navigator.userAgent;
    if (ua.match(/MicroMessenger\/[0-9]/i)) {
      return true;
    } else {
      return false;
    }
  },
  /* 判断是否是Hooli Android App */
  checkIsHooliAndroid: () => {
    let flag = false;
    if (window.Android && window.Android.javaScriptToNative) {
      flag = true;
    }
    return flag;
  },
  /* 判断是否是Hooli Ios App */
  checkIsHooliIos: () => {
    let flag = false;
    if (
      window.webkit &&
      window.webkit.messageHandlers &&
      window.webkit.messageHandlers.javaScriptToNative &&
      window.webkit.messageHandlers.javaScriptToNative.postMessage
    ) {
      flag = true;
    }
    return flag;
  },
  storage: {
    save: (key, value) => {
      let result = null;
      if (window) {
        result = window.localStorage.setItem(key, JSON.stringify(value));
      }
      return result;
    },
    fetch: key => {
      let result = null;
      if (window && key) {
        result = JSON.parse(window.localStorage.getItem(key));
      }
      return result;
    },
    remove: key => {
      if (window) {
        window.localStorage.removeItem(key);
      }
    },
    clear: () => {
      if (window) {
        window.localStorage.clear();
      }
    }
  },
  sessionStorage: {
    save: (key, value) => {
      let result = null;
      if (window) {
        result = window.sessionStorage.setItem(key, JSON.stringify(value));
      }
      return result;
    },
    fetch: key => {
      let result = null;
      if (window && key) {
        result = JSON.parse(window.sessionStorage.getItem(key));
      }
      return result;
    },
    remove: key => {
      if (window) {
        window.sessionStorage.removeItem(key);
      }
    },
    clear: () => {
      if (window) {
        window.sessionStorage.clear();
      }
    }
  },
  queryString: name => {
    let result = location.search.match(
      new RegExp("[?&]" + name + "=([^&]+)", "i")
    );
    if (result == null || result.length < 1) {
      return "";
    }
    return decodeURIComponent(result[1]);
  },
  deepClone: obj => {
    /* 深度克隆对象 */
    if (obj === null || typeof obj !== "object") {
      return obj;
    }
    let clone;
    if (obj instanceof Date) {
      clone = new Date();
      clone.setTime(obj.getTime());
      return clone;
    }
    if (obj instanceof Array) {
      clone = [];
      let i;
      let n = obj.length;
      for (i = 0; i < n; i++) {
        clone[i] = utils.deepClone(obj[i]);
      }
      return clone;
    }
    if (obj instanceof Object) {
      clone = {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          clone[key] = utils.deepClone(obj[key]);
        }
      }
      return clone;
    }
    throw new Error(`Unable to clone obj! Its type isn't supported.`);
  },
  // dates为数字类型，0代表今日,-1代表昨日，1代表明日，返回yyyy-mm-dd格式字符串，dates不传默认代表今日。
  getDate: dates => {
    let dd = new Date();
    let n = dates || 0;
    dd.setDate(dd.getDate() + n);
    let y = dd.getFullYear();
    let m = dd.getMonth() + 1;
    let d = dd.getDate();
    m = m < 10 ? "0" + m : m;
    d = d < 10 ? "0" + d : d;
    let day = y + "-" + m + "-" + d;
    let dayStart =
      new Date(Date.parse(day.replace(/-/g, "/"))).getTime() / 1000;
    let dayEnd = new Date().setTime(
      Date.parse(day.replace(/-/g, "/")) / 1000 + 24 * 60 * 60 - 1
    );
    let arr = [dayStart, dayEnd];
    return arr;
  },
  // type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
  getMonday: (type, dates) => {
    let now = new Date();
    let nowTime = now.getTime();
    let day = now.getDay();
    let longTime = 24 * 60 * 60 * 1000;
    let n = longTime * 7 * (dates || 0);
    let ddd = "";
    if (type === "s") {
      ddd = nowTime - (day - 1) * longTime + n;
    }
    if (type === "e") {
      ddd = nowTime + (7 - day) * longTime + n;
    }
    let dd = new Date(ddd);
    let y = dd.getFullYear();
    let m = dd.getMonth() + 1;
    let d = dd.getDate();
    m = m < 10 ? "0" + m : m;
    d = d < 10 ? "0" + d : d;
    let monday = y + "-" + m + "-" + d;
    let arr = [];
    if (type === "s") {
      let dayStart =
        new Date(Date.parse(monday.replace(/-/g, "/"))).getTime() / 1000;
      arr = [dayStart];
    } else if (type === "e") {
      let dayEnd = new Date().setTime(
        Date.parse(monday.replace(/-/g, "/")) / 1000 + 24 * 60 * 60 - 1
      );
      arr = [dayEnd];
    }
    return arr;
  },
  // type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，months为数字类型，不传或0代表本月，-1代表上月，1代表下月
  getMonth: (type, months) => {
    let d = new Date();
    let year = d.getFullYear();
    let month = d.getMonth() + 1;
    if (Math.abs(months) > 12) {
      months = months % 12;
    }
    if (months !== 0) {
      if (month + months > 12) {
        year++;
        month = (month + months) % 12;
      } else if (month + months < 1) {
        year--;
        month = 12 + month + months;
      } else {
        month = month + months;
      }
    }
    month = month < 10 ? "0" + month : month;
    //  let date = d.getDate()
    let firstday = year + "-" + month + "-" + "01";
    let lastday = "";
    if (
      month === "01" ||
      month === "03" ||
      month === "05" ||
      month === "07" ||
      month === "08" ||
      month === "10" ||
      month === "12"
    ) {
      lastday = year + "-" + month + "-" + 31;
    } else if (month === "02") {
      if (
        (year % 4 === 0 && year % 100 !== 0) ||
        (year % 100 === 0 && year % 400 === 0)
      ) {
        lastday = year + "-" + month + "-" + 29;
      } else {
        lastday = year + "-" + month + "-" + 28;
      }
    } else {
      lastday = year + "-" + month + "-" + 30;
    }
    let day = "";
    let arr = [];
    if (type === "s") {
      day = firstday;
      let dayStart =
        new Date(Date.parse(day.replace(/-/g, "/"))).getTime() / 1000;
      arr = [dayStart];
    } else {
      day = lastday;
      let dayEnd = new Date().setTime(
        Date.parse(day.replace(/-/g, "/")) / 1000 + 24 * 60 * 60 - 1
      );
      arr = [dayEnd];
    }

    return arr;
  },
  // 格式化时间戳
  timestampToTime(timestamp) {
    let date = null;
    if (timestamp.toString().length == 13) {
      date = new Date(timestamp);
    } else {
      date = new Date(timestamp * 1000);
    }
    let Y = date.getFullYear() + "-";
    let M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
    let h =
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
    let m =
      (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
      ":";
    let s =
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
  },
  // 格式化日期
  timestampToDate(timestamp) {
    // 格式化时间戳，输出2018-2-2
    let date = new Date(timestamp);
    let Y = date.getFullYear() + "-";
    let M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate() + " ";
    return Y + M + D;
  },
  dealPermission(vm, tag) {
    let permissionArr = vm.$store.state.activeBtnArr;
    let onoff = false;
    permissionArr.map(val => {
      let { operate } = val;
      if (tag === operate) {
        onoff = true;
      }
    });
    return onoff;
  },
  formatMoney(value) {
    if (!value) return "0.00";
    let intPart = Number(value).toFixed(0); // 获取整数部分
    let intPartFormat = intPart
      .toString()
      .replace(/(\d)(?=(?:\d{3})+$)/g, "$1,"); // 将整数部分逢三一断
    let floatPart = ".00"; // 预定义小数部分
    let value2Array = value.split(".");
    //= 2表示数据有小数位
    if (value2Array.length === 2) {
      floatPart = value2Array[1].toString(); // 拿到小数部分
      if (floatPart.length === 1) {
        // 补0,实际上用不着
        return intPartFormat + "." + floatPart + "0";
      } else {
        return intPartFormat + "." + floatPart;
      }
    } else {
      return intPartFormat + floatPart;
    }
  },
  // 删除对象空属性
  removeProperty(object) {
    for (let prop in object) {
      if (object.hasOwnProperty(prop)) {
        if (object[prop] === "" || object[prop] == "[]") {
          delete object[prop];
        }
      }
    }
    return object;
  },
  // ahex 转 rgba
  colorToRgba(color) {
    let rgba = "";
    color = color.substr(1);
    let colorLen = color.length;
    let aValue, rValue, gValue, bValue;
    aValue = "0xFF";
    if (colorLen === 6 || colorLen === 8) {
      if (colorLen === 8) {
        aValue = "0x" + color.substr(0, 2);
        color = color.substr(2);
      }
      rValue = "0x" + color.substr(0, 2);
      gValue = "0x" + color.substr(2, 2);
      bValue = "0x" + color.substr(4, 2);
      rgba =
        "rgba(" +
        parseInt(rValue) +
        "," +
        parseInt(gValue) +
        "," +
        parseInt(bValue) +
        "," +
        parseInt(aValue) / 100 +
        ")";
    }
    return rgba;
  },
  /* 校验字段合法性rule */
  checkMobile: s => {
    /* 校验手机号格式是否正确 */
    if (s) {
      s = s.toString().trim();
      var rule = /^\d{3,20}$/;
      return rule.test(s);
    }
    return false;
  },
  checkEmail: s => {
    /* 校验邮箱格式是否正确 */
    if (s) {
      s = s.toString().trim();
      var rule = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;
      return rule.test(s);
    }
    return false;
  },
  checkPwd: s => {
    /* 校验登录密码格式是否正确 */
    if (s) {
      s = s.toString().trim();
      var rule = /^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[a-zA-Z0-9]{8,16}$/;
      return rule.test(s);
    }
    return false;
  },
  checkCode: s => {
    /* 校验短信或邮箱验证码格式是否正确 */
    if (s) {
      s = s.toString().trim();
      var rule = /^\d{6}$/;
      return rule.test(s);
    }
    return false;
  },
  checkImgCode: s => {
    /* 校验图片验证码格式是否正确 */
    if (s) {
      s = s.toString().trim();
      var rule = /^[a-zA-Z]{4}$/;
      return rule.test(s);
    }
    return false;
  },
  checkNickname: s => {
    /* 校验昵称格式是否正确 */
    if (s) {
      s = s.toString().trim();
      var rule = /^[A-Za-z0-9\u4e00-\u9fa5]{2,20}$/;
      return rule.test(s);
    }
    return false;
  }
};
export default utils;
