/**
 * 节流throttle(时间戳+定时器)
 * @param {FUNCTION} func
 * @param {NUMBER} delay
 */
export function throttle (func, delay) {
  var timer = null
  var startTime = Date.now()
  return function () {
    var curTime = Date.now()
    var remaining = delay - (curTime - startTime)
    var context = this
    var args = arguments
    clearTimeout(timer)
    if (remaining <= 0) {
      func.apply(context, args)
      startTime = Date.now()
    } else {
      timer = setTimeout(func, remaining)
    }
  }
}
/**
   * 防抖
   * @param {FUNCTION} func
   * @param {NUMBER} wait
   * @param {BOOLEAN} immediate
   */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
   * @param {date} time 需要转换的时间
   * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
   */
export function formatTime (time, fmt) {
  if (!time) return ''
  else {
    const date = new Date(time)
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (const 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
  }
}

/**
   * 动画函数
   * 任意一个元素移动到指定的目标位置
   * @param {*} element 任意一个元素
   * @param {*} direction 移动方向
   * @param {*} target  目标位置(number类型)
   */
export function animate (element, direction, target) {
  // 先清理定时器
  if (element && element.timeId) {
    clearInterval(element.timeId)
  }
  element.timeId = setInterval(function () {
    // 获取移动元素当前位置
    var current = Number(element.style[direction].replace('rem', ''))
    // 每次移动距离
    var step = 0.4
    step = target > current ? step : -step
    // 移动后的距离
    current += step
    // 判断是否到达目标位置
    if (Math.abs(target - current) > Math.abs(step)) {
      element.style[direction] = current + 'rem'
    } else {
      clearInterval(element.timeId)
      element.style[direction] = target + 'rem'
    }
  }, 10)
}
/**
   *
   * @param {Number} value 金额
   * @param {Number} fmt 亿元还是万元
   */
export function formatMoney (value, fmt) {
  if (value === '' || value === null || value === undefined) {
    return '--'
  }
  if (fmt === 4) { // 转万元
    return (Number(value) / 10000).toFixed(0)
  }
  if (fmt === 8) { // 转亿元
    return (Number(value) / 10000 / 10000).toFixed(0)
  }
  if (fmt === 8.01) { // 转亿元
    return (Number(value) / 10000 / 10000).toFixed(2)
  }
}
/**
   * 千分位符转换
   * @param {Number} num
   */
export function numFormat (num) {
  if (num === '--' || num === '' || num === null || num === undefined) {
    return '--'
  }
  var _num = Number(num)
  var c = (_num.toString().indexOf('.') !== -1) ? _num.toLocaleString() : _num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  return c
}