import { Base64 } from 'js-base64';

function formatTime(date) {
  let datee = date.toString();
  return datee.replace(/T/g, ' ').replace(/-/g, '/');
}

function getNowFormatDate(val, type, flag) {
  let i = 1 * val;
  let sp = '-';
  const oneDay = 24 * 60 * 60 * 1000;
  let date = new Date(new Date() - -i * oneDay);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate;
  }
  if (type == 'year') {
    return year;
  } else if (type == 'month') {
    return year + sp + month;
  } else {
    if (flag) {
      return year + '年' + month + '月' + strDate + '日';
    }
    return year + sp + month + sp + strDate;
  }
}

// 将时间改为 *分钟前|*小时前|刚刚……
function translateTime(date) {
  return getDateDiff(formatTime(date));
}

function getDateDiff(date) {
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  // eslint-disable-next-line no-unused-vars
  let halfamonth = day * 15;
  let month = day * 30;
  let result = null;

  var dateTimeStamp = new Date(date);
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  /* if (diffValue < 0) {
        console.log('结束日期不能小于开始日期！');
        console.log(`开始日期：${dateTimeStamp}结束日期：${now}`);
        console.log(`参数为：${date}`);
        return 'null'; // TODO 方便测试
    } */
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  if (monthC >= 1) {
    result = `${parseInt(monthC)}个月前`;
  } else if (weekC >= 1) {
    result = `${parseInt(weekC)}周前`;
  } else if (dayC >= 1) {
    result = `${parseInt(dayC)}天前`;
  } else if (hourC >= 1) {
    result = `${parseInt(hourC)}小时前`;
  } else if (minC >= 1) {
    result = `${parseInt(minC)}分钟前`;
  } else result = '刚刚';
  return result;
}

Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  return fmt;
};

function formatnumber(value, num) {
  let _value = value.toString();
  let _dot = _value.indexOf('.');
  let _valueLen = _value.length;
  if (num == 0) {
    if (_dot != -1) {
      _value = _value.substring(0, _dot);
    }
  } else {
    //如果没有小数点
    if (_dot == -1) {
      _value = _value + '.';
      for (let i = 1; i <= num; i++) {
        _value = _value + '0';
      }
    } else {
      //有小数点，超出位数自动截取，否则补0
      _value = _value.substring(0, _dot + num + 1);
      for (let i = _valueLen; i <= _dot + num; i++) {
        _value = _value + '0';
      }
    }
  }
  return _value;
}

function round(src, pos, type) {
  //src代表要转化的值,pos表示要保留的位数
  let num = Math.floor(src * Math.pow(10, pos)) / Math.pow(10, pos);
  let val = type == 'string' ? formatnumber(num, pos) : parseFloat(formatnumber(num, pos));
  return val;
}

/**
 * 防抖使用，_type,index,item不用管，是changfield的参数
 *  methods: {
    改变场数
        changefield: _debounce(function(_type, index, item) {
            do something ...
        }, 200)
    }
 */
// 防抖
function _debounce(fn, delay) {
  // eslint-disable-next-line no-redeclare
  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);
  };
}

// 节流
function _throttle(fn, interval) {
  var last;
  var timer;
  // eslint-disable-next-line no-redeclare
  var interval = interval || 200;
  return function () {
    var th = this;
    var args = arguments;
    var now = +new Date();
    /* + 隐式类型转换，通过调用 valueOf() 获取时间戳 */
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  };
}

// base64 编码
function base64Encode(str, isURI) {
  if (isURI) {
    return Base64.encodeURI(str);
  }
  return Base64.encode(str);
}

// base64 解码
function base64Decode(str) {
  return Base64.decode(str);
}

/**
 * 判断是否为空
 */
function isNull(o) {
  /*return o === null
        || o === undefined
        || o === ''
        || JSON.stringify(o) === '{}'
        || JSON.stringify(o) === '[]';*/
  if (o === null || o === undefined || o === '') {
    return true;
    // eslint-disable-next-line
  } else if (Array.prototype.isPrototypeOf(o) && o.length === 0) {
    return true;
    // eslint-disable-next-line
  } else if (Object.prototype.isPrototypeOf(o) && Object.keys(o).length === 0) {
    return true;
  }
  return false;
}

/**
 * 判断是否为非空
 */
function isNotNull(o) {
  return !isNull(o);
}

/**
 * 清除 localStorage
 * @param store 要将 $store 传进来
 */
function clearLocalStorage(store) {
  try {
    for (let k in store.getters) {
      store.commit(k, '');
    }
  } catch (e) {
    console.log(e);
  }
}

export default {
  formatTime,
  getDateDiff,
  getNowFormatDate,
  translateTime,
  formatnumber,
  round,
  _debounce,
  _throttle,
  base64Encode,
  base64Decode,
  isNull,
  isNotNull,
  clearLocalStorage
};
