import XEUtils from "xe-utils";
import Vue from "vue";

/**
 * @desc   : 千分位展示
 * @author : 周兴
 * @param  : digits 小数位数，默认为2
 * @date   : 2022/11/16 10:44
 */
Number.prototype.toThousandth = function (digits) {
  if(digits == undefined){
    digits = 0;
  }
  return XEUtils.commafy(this, {digits});
}

/**
 * @desc   : 判断实体是否为空
 * @author : 周兴
 * @date   : 2024/4/9 10:25
 */
Vue.prototype.isEmpty = function (obj){
  let flag = true;
  console.log('d',obj)
  let keys = Object.keys(obj);
  for (let key of keys){
    if(obj[key]){
      flag = false;
      break;
    }
  }
  return flag;
}

/**
 * @desc   : 给列表的行设置行错误信息
 * @author : 周兴
 * @param  : row:行 msg:错误信息
 * @date   : 2022/12/16 11:08
 */
Vue.prototype.setErrToRow = function (row, msg) {
  if (!row || !msg) return;
  this.$set(row, 'info', msg);
}

/**
 * @desc   : 清除列表的行设置行错误信息
 * @author : 周兴
 * @param  : row:行
 * @date   : 2022/12/16 11:08
 */
Vue.prototype.clearRowErr = function (row) {
  if (!row) return;
  this.$set(row, 'info', null);
}

/**
 * @desc   : 获取按钮的名字，不包括快捷键
 * @author : 周兴
 * @date   : 2022/11/18 13:13
 */
Vue.prototype.$v = function (name) {
  if (name === undefined || name === null || name === '') {
    return ''
  }
  let str = this.$t(name)
  if (str.indexOf('(') > 0) {
    str = str.substr(0, str.indexOf('('))
  }
  return str
}

/**
 * @desc   : 合并实体
 * @author : 周兴
 * @date   : 2022/11/21 14:25
 */
Vue.prototype.objectMerge = function (source, target) {
  if (typeof source !== 'object') {
    source = {};
  }
  if (Array.isArray(target)) {
    return target.slice();
  }
  Object.keys(target).forEach((property) => {
    const targetProperty = target[property];
    if(targetProperty){
      if (typeof targetProperty === 'object') {
        source[property] = this.objectMerge(source[property], targetProperty);
      } else {
        source[property] = targetProperty;
      }
    }
  });
  return source;
}

export default {
  /**
   * @desc   : 合并实体(供main.js)调用，其他地方，调用上面那个
   * @author : 周兴
   * @date   : 2022/11/21 14:25
   */
  objectMergeByMainJs(source, target) {
    if (typeof source !== 'object') {
      source = {};
    }
    if (Array.isArray(target)) {
      return source.slice();
    }
    if (!source['key']) {
      Object.keys(target).forEach((property) => {
        const targetProperty = target[property];
        if (typeof targetProperty === 'object') {
          source[property] = this.objectMergeByMainJs(source[property], targetProperty);
        } else {
          source[property] = targetProperty;
        }
      });
    }
    return source;
  }
}

/**
 * 深拷贝
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
Vue.prototype.deepClone = function (source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone');
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = this.deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @desc   : 实体是否这个key值
 * @author : 周兴
 * @date   : 2022/11/16 17:14
 */
Vue.prototype.hasKey = function (object, key) {
  if (key) {
    return key in object
  }
  return false;
}

/**
 * @desc   : 实体是否这个Value值(只支持文本和数组类型）
 * @author : 周兴
 * @date   : 2022/11/16 17:14
 */
Vue.prototype.hasValue = function (object, value, keys, isEqual = true) {
  if (!object || !value) {
    return false;
  }
  let valuesList = []
  let keysArr = Object.keys(object);
  keysArr.forEach(it => {
    if (keys && keys.length > 0) {
      if (keys.indexOf(it) >= 0) {
        valuesList.pushNoRepeat(object[it])
      }
    } else {
      valuesList.pushNoRepeat(object[it])
    }
  })
  let filterRows = []
  // 值等
  if (isEqual) {
    filterRows = valuesList.filter(it => it.toString() === value)
  } else { // 模糊
    filterRows = valuesList.filter(it => it.toString().indexOf(value) >= 0)
  }
  if (filterRows && filterRows.length > 0) {
    return true;
  }
  return false;
}


/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
  const keysArr1 = Object.keys(obj1)
  const keysArr2 = Object.keys(obj2)
  if (keysArr1.length !== keysArr2.length) return false
  else if (keysArr1.length === 0 && keysArr2.length === 0) return true
  /* eslint-disable-next-line */
  else return !keysArr1.some(key => obj1[key] != obj2[key])
}



/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (targetarr, arr) => {
  return targetarr.some(_ => arr.indexOf(_) > -1)
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @H_x_d 判断所有元素都要包含,如果arr(包含权限的数组）为空则返回false
 * @description 控制左侧菜单的显示
 */
export const hasAllOf = (targetarr, arr) => {
  if (!arr) return false
  for (let it of targetarr) {
    if (![it].some(_ => arr.indexOf(_) > -1)) return false
  }
  return true
}

/**
 * @param {String|Number} value 要验证的字符串或数值
 * @param {*} validList 用来验证的列表
 */
export function oneOf(value, validList) {
  for (let i = 0; i < validList.length; i++) {
    if (value === validList[i]) {
      return true
    }
  }
  return false
}


/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
  const ua = window.navigator.userAgent
  const isExplorer = (exp) => {
    return ua.indexOf(exp) > -1
  }
  if (isExplorer('MSIE')) return 'IE'
  else if (isExplorer('Firefox')) return 'Firefox'
  else if (isExplorer('Chrome')) return 'Chrome'
  else if (isExplorer('Opera')) return 'Opera'
  else if (isExplorer('Safari')) return 'Safari'
}

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler)
      }
    }
  }
})()

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function () {
  if (document.removeEventListener) {
    return function (element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler)
      }
    }
  }
})()


/**
 * @Date 2019-10-11 11:44
 * @Author H_x_d
 * @Description 系统，浏览器
 */
export const getOsAndWebVersion = () => {
  var BrowserMatch = {
    init: function () {
      this.browser = this.getBrowser().browser || "未知浏览器";  //获取浏览器名
      this.version = this.getBrowser().version || "未知浏览器版本号";  //获取浏览器版本
      this.OS = this.getOS() || "未知操作系统"; //系统版本号
      this.digits = this.getDigits()
    },
    getOS: function () {  //判断所处操作系统
      var sUserAgent = navigator.userAgent.toLowerCase();

      var isWin = (navigator.platform == "Win32") || (navigator.platform == "Win64") || (navigator.platform == "wow64");

      var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
      if (isMac) return "Mac";
      var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
      if (isUnix) return "Unix";
      var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
      var bIsAndroid = sUserAgent.toLowerCase().match(/android/i) == "android";
      if (isLinux) {
        if (bIsAndroid) return "Android";
        else return "Linux";
      }
      if (isWin) {
        var isWin2K = sUserAgent.indexOf("Windows nt 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
        if (isWin2K) return "Win2000";
        var isWinXP = sUserAgent.indexOf("Windows nt 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1
        sUserAgent.indexOf("Windows XP") > -1;
        if (isWinXP) return "WinXP";
        var isWin2003 = sUserAgent.indexOf("Windows nt 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
        if (isWin2003) return "Win2003";
        var isWinVista = sUserAgent.indexOf("Windows nt 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
        if (isWinVista) return "WinVista";
        var isWin7 = sUserAgent.indexOf("Windows nt 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
        if (isWin7) return "Win7";
        var isWin8 = sUserAgent.indexOf("windows nt 6.2") > -1 || sUserAgent.indexOf("Windows 8") > -1;
        if (isWin8) return "Win8";
        var isWin10 = sUserAgent.indexOf("windows nt 10.0") > -1 || sUserAgent.indexOf("Windows 10") > -1;
        if (isWin10) return "Win10";
      }
      if (navigator.platform === "iPad") return 'IOS'
      return "其他";
    },
    getDigits: function () { //判断当前操作系统的版本号
      var sUserAgent = navigator.userAgent.toLowerCase();
      var is64 = sUserAgent.indexOf("win64") > -1 || sUserAgent.indexOf("wow64") > -1;
      if (is64) {
        return "64位";
      } else {
        return "32位";
      }
    },
    getBrowser: function () {  // 获取浏览器名
      var rMsie = /(msie\s|trident\/7)([\w\.]+)/;
      var rTrident = /(trident)\/([\w.]+)/;
      var rEdge = /(chrome)\/([\w.]+)/;//IE

      var rFirefox = /(firefox)\/([\w.]+)/;  //火狐
      var rOpera = /(opera).+version\/([\w.]+)/;  //旧Opera
      var rNewOpera = /(opr)\/(.+)/;  //新Opera 基于谷歌
      var rChrome = /(chrome)\/([\w.]+)/; //谷歌
      var rUC = /(chrome)\/([\w.]+)/;//UC
      var rMaxthon = /(chrome)\/([\w.]+)/;//遨游
      var r2345 = /(chrome)\/([\w.]+)/;//2345
      var rQQ = /(chrome)\/([\w.]+)/;//QQ
      //var rMetasr =  /(metasr)\/([\w.]+)/;//搜狗
      var rSafari = /version\/([\w.]+).*(safari)/;

      var ua = navigator.userAgent.toLowerCase();


      var matchBS, matchBS2;

      //谷歌浏览器
      matchBS = rChrome.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        matchBS2 = rNewOpera.exec(ua);
        if (matchBS2 == null) {
          return {
            browser: "谷歌",
            version: "Chrome/" + matchBS[2] || "0"
          };
        } else {
          return {
            browser: "Opera",
            version: "opr/" + matchBS2[2] || "0"
          };
        }
      }

      //Safari（苹果）浏览器
      matchBS = rSafari.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent)) && (!(window.chrome)) && (!(window.opera))) {
        return {
          browser: "Safari",
          version: "Safari/" + matchBS[1] || "0"
        };
      }

      //IE 低版
      matchBS = rMsie.exec(ua);
      if (matchBS != null) {
        matchBS2 = rTrident.exec(ua);
        if (matchBS2 != null) {
          switch (matchBS2[2]) {
            case "4.0":
              return {
                browser:
                  "Microsoft IE",
                version: "IE: 8"  //内核版本号
              };
              break;
            case "5.0":
              return {
                browser:
                  "Microsoft IE",
                version: "IE: 9"
              };
              break;
            case "6.0":
              return {
                browser:
                  "Microsoft IE",
                version: "IE: 10"
              };
              break;
            case "7.0":
              return {
                browser:
                  "Microsoft IE",
                version: "IE: 11"
              };
              break;
            default:
              return {
                browser:
                  "Microsoft IE",
                version: "Undefined"
              };
          }
        } else {
          return {
            browser: "Microsoft IE",
            version: "IE:" + matchBS[2] || "0"
          };
        }
      }
      //IE最新版
      matchBS = rEdge.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "Microsoft Edge",
          version: "Chrome/" + matchBS[2] || "0"
        };
      }
      //UC浏览器
      matchBS = rUC.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "UC",
          version: "Chrome/" + matchBS[2] || "0"
        };
      }
      //火狐浏览器
      matchBS = rFirefox.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "火狐",
          version: "Firefox/" + matchBS[2] || "0"
        };
      }
      //Oper浏览器
      matchBS = rOpera.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "Opera",
          version: "Chrome/" + matchBS[2] || "0"
        };
      }
      //遨游
      matchBS = rMaxthon.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "遨游",
          version: "Chrome/" + matchBS[2] || "0"
        };
      }
      //2345浏览器
      matchBS = r2345.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "2345",
          version: "Chrome/ " + matchBS[2] || "0"
        };
      }
      //QQ浏览器
      matchBS = rQQ.exec(ua);
      if ((matchBS != null) && (!(window.attachEvent))) {
        return {
          browser: "QQ",
          version: "Chrome/" + matchBS[2] || "0"
        };
      }

    }
  };
  BrowserMatch.init();
  console.log("当前浏览器为：" + BrowserMatch.browser + "\n版本为：" + BrowserMatch.version + "\n所处操作系统为：" + BrowserMatch.OS + '\n版本号：' + BrowserMatch.digits);
  // alert("当前浏览器为：" + BrowserMatch.browser +"\n版本为："+ BrowserMatch.version + "\n所处操作系统为："+BrowserMatch.OS + '\n版本号：' + BrowserMatch.digits);
  return BrowserMatch
}

export const forEach = (arr, fn) => {
  if (!arr.length || !fn) return
  let i = -1
  let len = arr.length
  while (++i < len) {
    let item = arr[i]
    fn(item, i, arr)
  }
}
