import $axios from 'axios'
import config from './config'
import Big from './big.min.js'
import Vue from 'vue';
var util = {
  /**
   * 格式化时间
   */
  formatTime: date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  },

  formatNumber: n => {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  /**
   * 清除详情富文本自带样式
   */
  formatHtml: content => {
    content = content.replace(/\<img/gi, '<img style="width:100% !important;height:auto !important;margin:0;display:flex;" ');
    content = content.replace(/\<video/gi, '<video style="width:100% !important;height:auto !important;margin:0;display:flex;" ');
    content = content.replace(/style="/gi, 'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break;break-word;');
    // content = content.replace(/\<table/gi, '<table style="table-layout:fixed;word-wrap:break-word;word-break;break-all;" ');
    // content = content.replace(/\<td/gi, '<td  cellspacing="0" cellpadding="0" border="0" style="display:block;vertical-align:top;margin: 0px; padding: 0px; border: 0px;outline-width:0px;" ');
    content = content.replace(/width=/gi, 'sss=');
    content = content.replace(/height=/gi, 'sss=');
    content = content.replace(/class=/gi, 'sss=');
    content = content.replace(/ \/\>/gi, ' style="max-width:100% !important;height:auto !important;margin:0;display:block;" \/\>');
    return content;
  },
  /**
   * 根据相隔时间戳，计算相隔时间
   */
  betweenTime: (betweenTimestamp) => {
    // 正的时间还是负的时间
    let signs = 1
    if (betweenTimestamp < 0) {
      betweenTimestamp = -betweenTimestamp
      signs = 0
    }

    if (betweenTimestamp > 1000) {
      let time = betweenTimestamp / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      return {
        day: `${util.timeFormat(day)}`,
        hou: `${util.timeFormat(hou)}`,
        min: `${util.timeFormat(min)}`,
        sec: `${util.timeFormat(sec)}`,
        signs: signs
      }
    }
    return {
      day: '00',
      hou: '00',
      min: '00',
      sec: '00',
      signs: signs
    }
  },
  /**
   * 计算相隔时间戳
   */
  betweenTimestamp (startTime, endTime) {
    let newTime = new Date().getTime()
    let betweenTime = 0;
    // 还没开始 相差时间为负数
    if (newTime < startTime) {
      betweenTime = newTime - startTime
    }
    // 还没结束
    else {
      betweenTime = endTime - newTime
    }
    return betweenTime;
  },
  /**
   * 小于10的格式化函数
   */
  timeFormat: (times) => {
    return times < 10 ? '0' + times : times;
  },

  /**
   * 日期转时间戳
   */
  dateToTimestamp: (dateStr) => {
    if (!dateStr) {
      return ''
    }
    let newDataStr = dateStr.replace(/\.|\-/g, '/')
    let date = new Date(newDataStr);
    let timestamp = date.getTime();
    return timestamp
  },

  /**
   * 改变日期
   */
    tsToDate(number, format) {
    var formateArr = ["Y", "M", "D", "h", "m", "s"];
    var returnArr = [];

    var date = new Date(number);
    returnArr.push(date.getFullYear());
    returnArr.push(
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1
    );
    returnArr.push(
      date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
    );

    returnArr.push(
      date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
    );
    returnArr.push(
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
    );
    returnArr.push(
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
    );

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  },
  /**
   * 价格处理
   */
  parsePrice: (value) => {
    var val = Number(value)
    if (!val) {
      val = 0;
    }
    // 截取小数点后两位，并以小数点为切割点将val转化为数组
    return val.toFixed(2).split(".");
  },

  /**
   * 手机号正则校验
   */
  checkPhoneNumber: (phoneNumber) => {
    var regexp = /^[1][0-9]{10}$/
    return regexp.test(phoneNumber)
  },

  /**
   * 用户名正则校验
   */
  checkUserName: (userName) => {
    var regexp = /^([a-zA-Z0-9_]{4,16})$/
    return regexp.test(userName)
  },

  /**
   * 处理参数
   * @param {obj}  to: 目标页面路由信息
   */
  getPageInfo: (to) => {
    var pathName = to.name
    var params = to.params
    var pageInfo = {}
    if (pathName === 'index') {
      pageInfo.pageId = 1
    } else if (pathName === 'detail-prodId') {
      pageInfo.pageId = params.bannerEnter === '1' ? 2 : params.groupActivityId ? 5: 3
      pageInfo.bizType = params.groupActivityId ? 1 : 0
      pageInfo.bizData = params.prodId
    } else if (pathName === 'secdetail-seckillId') {
      pageInfo.pageId = 4
      pageInfo.bizType = 2
      pageInfo.bizData = params.seckillId
    } else if (pathName === 'list') {
      pageInfo.pageId = 6
    } else if (pathName === 'special-discount') {
      pageInfo.pageId = 7
    } else if (pathName === 'cart') {
      pageInfo.pageId = 8
    } else if (pathName === 'order-detail') {
      pageInfo.pageId = 9
    } else if (pathName === 'payment') {
      pageInfo.pageId = 10
      pageInfo.bizData = sessionStorage.getItem('pay_orderNumber')
    }
    // else if (pathName === 'uc-order' && query.total_amount) {
    //   pageInfo.pageId = 11
    //   pageInfo.bizData = sessionStorage.getItem('pay_orderNumber')
    // }
    else if (pathName === 'user-center') {
      pageInfo.pageId = 12
    } else if (pathName === 'user-center-uc-order') {
      pageInfo.pageId = 13
    }
    return pageInfo
  },

  /**
   * 获取唯一值
   */
  getUuid: () => {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  },

  saveLog(flowData, visitType) {
    const token = Cookies.get('token')
    var flowAnalysisLogDto = Object.assign(flowData)
    flowAnalysisLogDto.visitType = visitType
    $axios({
      method: 'POST',
      url: token ? '/p/flowAnalysisLog' : '/flowAnalysisLog',
      data: flowAnalysisLogDto,
      baseURL: config.path,
      headers: {
        Authorization: token
      }
    }).then(({ data }) => {})
  },

  /**
   * 记录页面点击次数
   */
  tapLog(visitType, orderNumbers, isPayRes, prodNum) {
    // 更新会话时间
    localStorage.setItem('sessionTimeStamp', new Date().getTime())
    var flowAnalysisLogDto = JSON.parse(localStorage.getItem('flowAnalysisLogDto'))

	flowAnalysisLogDto.visitType = visitType || 3
	flowAnalysisLogDto.nums = prodNum || undefined
    // 支付页面单独处理
    if (orderNumbers) {
      visitType = 1
      flowAnalysisLogDto.orderNumbers = orderNumbers
      flowAnalysisLogDto.step = flowAnalysisLogDto.step + 1
      flowAnalysisLogDto.pageId = !isPayRes ? 10 : 11
    }
    this.saveLog(flowAnalysisLogDto, visitType)
  },

  /**
   * 修改favico图标
   */
   changeFavicon () {
    const link = JSON.parse(localStorage.getItem('webConfig'))? JSON.parse(localStorage.getItem('webConfig')).pcTitleImg : ''
    if (!link) {
      return
    }
    let favicon = document.querySelector('link[rel="icon"]')
    if (favicon !== null) {
      favicon.href = link
    } else {
      favicon = document.createElement('link')
      favicon.rel = 'icon'
      favicon.href = link
      document.head.appendChild(favicon)
    }
  },

  /**
   * 请求系统支付开关
   * @param {Boolean} forcedRefresh 是否强制刷新数据
   * @param {Function} fn 回调
   */
  getSysPaySwitch(forcedRefresh, fn) {
    // 获取缓存中的配置
    const paySwitchInfo = JSON.parse(localStorage.getItem('paySwitchInfo')) || {}
    if (!paySwitchInfo.expiredTime || new Date().getTime() > paySwitchInfo.expiredTime || forcedRefresh) {
      $axios.get(config.path + '/sys/config/info/getSysPaySwitch').then(({ data }) => {
        const paySwitchInfo = {
          switchInfo: data,
          expiredTime: 5 * 60 * 60 * 1000 + new Date().getTime()
        }
        localStorage.setItem('paySwitchInfo', JSON.stringify(paySwitchInfo))
        if (fn) fn()
      })
    }
  }
}


export default util

/**
 * 防抖
 */
export function _debounce (fn, delay) {
  var delay = delay || 200;
  var timer;
  return function () {
    var th = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}

import Cookies from 'js-cookie'

const LangKey = 'hb_lang' // 语言

export function getLanguage() {
  return Cookies.get(LangKey)
}

export function setLanguage(data) {
  return Cookies.set(LangKey, data)
}

export function removeLanguage() {
  return Cookies.remove(LangKey)
}


/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export function _throttle (fn, t) {
  let last;
  let timer;
  let interval = t || 500;
  return function () {
    let args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        last = now;
        fn.apply(this, args);
      }, interval);
    } else {
      last = now;
      fn.apply(this, args);
    }
  }
};

export function addUrlParam(uri, key, value) {
	if(!value) {
		return uri;
	}
	var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
	var separator = uri.indexOf('?') !== -1 ? "&" : "?";
	if (uri.match(re)) {
		return uri.replace(re, '$1' + key + "=" + value + '$2');
	}
	else {
		return uri + separator + key + "=" + value;
	}
}

/**
 * 精度运算
 * @param {*} a 第一个计算数(例如:被除数/被减数)
 * @param {*} b 第二个计算数(例如:除数/减数)
 * @param {*} countMode 计算方式(0:加 1:减 2:乘 3:除)
 */
  export function accuracyCount (a, b, countMode) {
  let finalResult = 0
  if (countMode === 0) {
    finalResult = new Big(a).plus(b).valueOf()
  } else if (countMode === 1) {
    finalResult = new Big(a).minus(b).valueOf()
  } else if (countMode === 2) {
    finalResult = new Big(a).times(b).valueOf()
  } else if (countMode === 3) {
    finalResult = new Big(a).div(b).valueOf()
  } else {
    return
  }
  return finalResult
}

// 解决四舍五入精度问题
Number.prototype.toFixxed=function (d) {
	var s=this+"";
	if(!d)d=0;
	if(s.indexOf(".")==-1)s+=".";
	s+=new Array(d+1).join("0");
	if(new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+(d+1)+"})?)\\d*$").test(s)){
		 var s="0"+RegExp.$2,pm=RegExp.$1,a=RegExp.$3.length,b=true;
		 if(a==d+2){
				 a=s.match(/\d/g);
				 if(parseInt(a[a.length-1])>4){
						 for(var i=a.length-2;i>=0;i--){
								 a[i]=parseInt(a[i])+1;
								 if(a[i]==10){
										 a[i]=0;
										 b=i!=1;
								 }else break;
						 }
				 }
				 s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");

		 }if(b)s=s.substr(1);
		 return (pm+s).replace(/\.$/,"");
} return this+"";

};

// Vue.prototype.toFixxed = val => {
// 	if (!val) {
// 	  val = 0
// 	}
// 	return val.toFixxed(2)
// }
