
import moment from 'moment' // 时间库
//获取年月日
const 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: year,
    month: [year, month].map(formatNumber).join('-'),
    day: [year, month, day].map(formatNumber).join('-'),
    month_tow: month,
    allDate: [year, month, day].map(formatNumber).join('-') + " " + hour + ":" + minute
  }
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//删除数组的某一项
const arrRemoveObj = (array, obj) => {
  let length = array.length;
  for (let i = 0; i < length; i++) {
    if (array[i] === obj) {
      if (i === 0) {
        array.shift();
        return array;
      } else if (i === length - 1) {
        array.pop();
        return array;
      } else {
        array.splice(i, 1);
        return array;
      }
    }
  }
}
//获取对应积分类型
const getTypeItem = (arr, id) => {
  var item = arr.filter(element => {
    return typeof (id) == 'string' ? element.code == id : element.id == id
  });
  return item[0]
}
// 获取唯一标识（uid）
const generateUUID = () => {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
};
// 根据传入的时间戳返回日期
const returnStr = (time) => {
  if(!time){
    return ''
  }
  let date = `${time}000`
  let res = moment(Number(date)).format('YYYY-MM-DD HH:mm');
  return fnTime(res);
};
function fnTime(time) {
  let staer = time.slice(0, 11);
  let ptime = new Date(time).getTime()
  const twentyFourHours = 24 * 60 * 60 * 1000;
  const fortyEightHours = 24 * 60 * 60 * 1000 * 2;
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const today = `${year}-${month}-${day}`;
  const todayTime = new Date(today).getTime();
  const yesterdayTime = new Date(todayTime - twentyFourHours).getTime();
  const lastYesterdayTime = new Date(todayTime - fortyEightHours).getTime();
  let day2 = moment().format('YYYY-MM-DD');
  if (ptime >= todayTime) {
    return '今天 ' + time.split(' ')[1] + ' 更新了执行计划';
  }
  else if (ptime < todayTime && yesterdayTime <= ptime) {
    return '昨天 ' + time.split(' ')[1] + ' 更新了执行计划';
  }
  else if (ptime < yesterdayTime && lastYesterdayTime <= ptime) {
    return '前天 ' + time.split(' ')[1] + ' 更新了执行计划';
  } else if (dateSum(day2, staer) > 30) {
    return '近30天无计划更新';
  } else {
    return time + ' 更新了执行计划';
  }
}
function dateSum(sDate1, sDate2) {   //sDate1和sDate2是2008-12-13格式
  var aDate, oDate1, oDate2, iDays
  aDate = sDate1.split("-")
  oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])   //转换为12-13-2008格式
  aDate = sDate2.split("-")
  oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)   //把相差的毫秒数转换为天数
  return iDays
}

// 获取当前登录者在绩效系统中的身份
const getRole=(type)=>{
  /* type为判断哪些角色*/
  var role = getCache('role')
  let is = false
  switch (type) {
    case 1: // 判断是否是主子管理员
      if (role == 'masterAdministrator' || role == 'childAdministrator') {
        is = true
      }
      break
    case 2: // 判断是否是部门管理员
      if (role == 'deptManager') {
        is = true
      }
      break
    case 3: // 判断是否是员工
      if (role == 'employee') {
        is = true
      }
      break
    case 4: // 判断是否是创始人
      if (role == 'creator') {
        is = true
      }
      break
  }
  return is
}

// 设置缓存
const setCache = (key, val) => {
  dd.setStorageSync({
    key: key,
    data: val
  });
}
// 获取缓存
const getCache = (key) => {
  return dd.getStorageSync({ key: key }).data;
}
// 防抖
const _debounce = (fn, delay = 500) => {
  let timeout = null; // 创建一个标记用来存放定时器的返回值
  return function () {
    // 每当用户输入的时候把前一个setTimeout clear掉
    clearTimeout(timeout);
    // 然后又创建一个新的setTimeout，
    // 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行fn函数
    timeout = setTimeout(() => {
      // 关键在第一个参数，为了确保上下文环境为当前的this，所以不能直接用fn
      fn.apply(this, arguments);
    }, delay);
  }
}
// 节流
const _throttle = (fn, interval = 500) => {
  var last;
  var timer;
  return function () {
    var th = this;
    var args = arguments;
    var now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () { //用户最后一次点击时间间隔小于设置时间执行
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  }
}
module.exports = {
  getRole,
  _debounce,
  _throttle,
  setCache,
  getCache,
  returnStr,
  formatTime,
  arrRemoveObj,
  getTypeItem,
  generateUUID
}
