export default {
  /**
   * 返回一个自带消抖效果的函数，用res表示。
   *
   * fn: 需要被消抖的函数
   * delay: 消抖时长
   * isImmediateCall: 是否在一组操作中的第一次调用时立即执行fn
   * isRememberLastCall：是否在一组中最后一次调用后等delay时长再执行fn
   */
  debounce(fn, delay = 250, isImmediateCall = true, isRememberLastCall = true) {
    console.assert(isImmediateCall || isRememberLastCall, 'isImmediateCall 和 isRememberLastCall 至少应有一个是true，否则没有意义！')
    let timer = null
    // 上次调用的时刻
    let lastCallTime = 0

    if (isImmediateCall && !isRememberLastCall) {
      return function (...args) {
        const currentTime = Date.now()
        if (currentTime - lastCallTime >= delay) {
          fn.apply(this, args)
        }
        lastCallTime = currentTime
      }
    } else if (!isImmediateCall && isRememberLastCall) {
      return function (...args) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, args)
        }, delay)
      }
    } else if (isImmediateCall && isRememberLastCall) {
      return function (...args) {
        const currentTime = Date.now()
        if (currentTime - lastCallTime >= delay) { // 一组操作中的第一次
          fn.apply(this, args)
          lastCallTime = currentTime
          return
        } else { // 一组中的后续调用
          if (timer) { // 在此之前存在中间调用
            lastCallTime = currentTime
            clearTimeout(timer)
          }
          timer = setTimeout(() => {
            fn.apply(this, args)
            lastCallTime = 0
            timer = null
          }, delay)
        }
      }
    } else {
      console.error('不应该执行到这里！')
    }
  },
  throttle(fn, interval = 250) {
    let lastRunTime = 0

    return function (...args) {
      let elapsedTime = Date.now() - lastRunTime
      if (elapsedTime < interval) {
        return null
      }

      let context = this
      lastRunTime = Date.now()
      return fn.apply(context, args)
    }
  },
  getRandomString(length = 32) {
    let charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    let ret = ""
    for (let i = 0; i < length; i++) {
      ret += charSet.charAt(Math.floor(Math.random() * charSet.length))
    }
    return ret
  }
}