/**
 * 节流
 * @param {Function} func 回调函数
 * @param {Number} wait 时间限制
 * @returns 返回函数表达式
 */
export function throttle(func, wait) {
  let timeout
  return function() {
    const context = this
    const args = arguments
    if (!timeout) {
      timeout = setTimeout(function() {
        timeout = null
        func.apply(context, args)
      }, wait)
    }
  }
}

/**
 * 防抖
 * @param {Function} func 回调函数
 * @param {Number} wait 时间限制
 * @param {Boolean} immediate 是否立即执行回调 true：立即执行，false：等待wait秒后执行
 * @returns 返回函数表达式
 */
export function debounce(func, wait, immediate = false) {
  let timeout, result
  return function() {
    const context = this
    const args = arguments
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      const callNow = !timeout
      timeout = setTimeout(function() {
        timeout = null
      }, wait)
      if (callNow) result = func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
    return result
  }
}

/**
 * 生成hash字符串
 * @param {Number} hashLength 生成的hash值的字符长度
 * @returns hash字符串
 */
export function createHash(hashLength) {
  if (!hashLength || typeof Number(hashLength) !== 'number') {
    return
  }
  var ar = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '0',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z'
  ]
  var hs = []
  var hl = Number(hashLength)
  var al = ar.length
  for (var i = 0; i < hl; i++) {
    hs.push(ar[Math.floor(Math.random() * al)])
  }
  return hs.join('')
}

// 通过a标签下载文件
export function downLoadWithATag(href) {
  const downLink = document.createElement('a')
  downLink.href = href
  downLink.style.display = 'none'
  downLink.setAttribute('download', true)
  downLink.click()
}
