import { XMessage } from '@/hooks'

// eslint-disable-next-line max-params
export const debounce = function (
  fn: (...args: any[]) => void,
  delay = 200,
  immediate = true,
  toast = false,
) {
  let timer: number | null
  return function (this: any, ...args: any[]) {
    if (timer) {
      toast && XMessage.info('请勿频繁操作')
      clearTimeout(timer)
    }
    if (immediate) {
      !timer && fn.apply(this, args)
      timer = setTimeout(() => {
        timer = null
      }, delay)
    } else {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, delay)
    }
  }
}
