/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ygp
 */
const baseURL = process.env.VUE_APP_BASE_API

// 日期格式化
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), '/');
    }
    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(/{(y|m|d|h|i|s|a)+}/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
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
  } else {
    search.params['begin' + propName] = dateRange[0];
    search.params['end' + propName] = dateRange[1];
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue == ('' + value)) {
      actions.push(datas[key].dictLabel);
      return true;
    }
  })
  return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == ('' + temp[val])) {
        actions.push(datas[key].dictLabel + currentSeparator);
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

// 通用下载方法
export function download(fileName) {
  window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 获取20位长度的随机字符串
export function randomStr20() {
  for (var e = "0123456789abcdef", t = "", n = 0; n < 20; n++) t += e[Math.floor(16 * Math.random())];
  return t;
}

/*
    * 参数说明：
    * number：要转换的数字
    * thousand：千分位符号
    * */
   //千分位转正常数字
export function toNumber(number,thousand){

  number = number.split(thousand).join("");
  return parseFloat(number)
}

//除法去除精度损失
export function accDiv(arg1, arg2) {
  if(!arg1 || !arg2){
    if(arg2 == 0){
      return Infinity
    }
    return arg1/arg2
  }
	var t1 = 0, t2 = 0, r1, r2;
	try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
	try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  if(r2==0){
    return Infinity;
  }else{
    return (r1 / r2) * Math.pow(10, t2 - t1);
	}
}

//乘法去除精度损失
export function accMul(arg1, arg2) {
  if(!arg1 || !arg2){
    return arg1*arg2
  }
	var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
	try { m += s1.split(".")[1].length } catch (e) { }
	try { m += s2.split(".")[1].length } catch (e) { }

	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

export function numberFormat(number, decimals = 2, dec_point = '.', thousands_sep = ',') {
  /*
    * 参数说明：
    * number：要格式化的数字
    * decimals：保留几位小数
    * dec_point：小数点符号
    * thousands_sep：千分位符号
    * */
   number = accDiv(number,100)
   number = (number + '').replace(/[^0-9+-Ee.]/g, '');
   var n = !isFinite(+number) ? 0 : +number,
	   prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
	   sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
	   dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
	   s = '',
	   toFixedFix = function (n, prec) {

		   var k = Math.pow(10, prec);
		   return '' + Math.round(n * k) / k;
	   };
   s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
   var re = /(-?\d+)(\d{3})/;
   while (re.test(s[0])) {
	   s[0] = s[0].replace(re, "$1" + sep + "$2");
   }
   if ((s[1] || '').length < prec) {
	   s[1] = s[1] || '';
	   s[1] += new Array(prec - s[1].length + 1).join('0');
   }

   return s.join(dec);
}

export function newNumberFormat(number, decimals, dec_point, thousands_sep) {
  /*
    * 参数说明：
    * number：要格式化的数字
    * decimals：保留几位小数
    * dec_point：小数点符号
    * thousands_sep：千分位符号
    * */
   number = (number + '').replace(/[^0-9+-Ee.]/g, '');
   var n = !isFinite(+number) ? 0 : +number,
	   prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
	   sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
	   dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
	   s = '',
	   toFixedFix = function (n, prec) {

		   var k = Math.pow(10, prec);
		   return '' + Math.round(n * k) / k;
	   };
   s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
   var re = /(-?\d+)(\d{3})/;
   while (re.test(s[0])) {
	   s[0] = s[0].replace(re, "$1" + sep + "$2");
   }
   if ((s[1] || '').length < prec) {
	   s[1] = s[1] || '';
	   s[1] += new Array(prec - s[1].length + 1).join('0');
   }

   return s.join(dec);
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

// 关闭当前页 关联tagView
export function closePage(store, router, route) {
  var currentView = store.state.tagsView.visitedViews[0]
  for (currentView of store.state.tagsView.visitedViews) {
    if (currentView.path === route.path) {
      break
    }
  }
  store.dispatch('tagsView/delView', currentView)
  .then(({ visitedViews }) => {
    if (currentView.path === route.path) {
      const latestView = store.state.tagsView.visitedViews.slice(-1)[0]
      if (latestView) {
        router.push(latestView)
      } else {
        if (currentView.name === '首页') {
          router.replace({ path: '/redirect' + currentView.fullPath })
        } else {
          router.push('/')
        }
      }
    }
  })
}

export function getTimeResult(time){
  //当前的时间戳
  var ctime = new Date().getTime();
  // console.log("time:"+time);
  // console.log("ctime"+ctime)
  //当前时间戳-传入的时间戳=时间差
  var difference = ctime-time;
  // console.log(difference)
  //把时间差转换成天数
  var day = Math.floor(difference/3600/24/1000);
  //如果天数大于等于1小于7
  if(day>=1 && day<7){
      return day+'天前';
  }

  if(day<1){
      var hour = Math.floor(difference/3600/1000);
      if(hour<1){
          var min = Math.floor(difference/60/1000);
          if(min<1){
            return '刚刚'
          }
          return min+'分钟前';
      }else{
          return hour+'小时前';
      }
  }

  if(day>=7){
    return parseTime(time,'{y}.{m}.{d}');
  }
}
