/**
 * 防抖：在连续的操作中，无论进行了多长时间，只有某一次的操作后在指定的时间内没有再操作，这一次才被判定有效。
 * 使用：
 * <el-button v-debounce:click.delay[2000]="testDebounce">按钮防抖</el-button>
 * <el-button v-debounce:click.delay[2000]="()=>testDebounce('debounce')">按钮防抖传参</el-button>
 */
import { ObjectDirective } from 'vue'
interface DebounceEl extends HTMLElement {
  debounceEvent: () => void
}
// 防抖指令封装
const debounceDirective: ObjectDirective = {
  beforeMount(el: DebounceEl, binding: any) {
    let timer: number
    let delay: number = 1000
    const keys = Object.keys(binding.modifiers)
    if (keys) {
      const key: string | undefined = keys.find((key) => key.includes('delay'))?.toString()
      const value = (key ?? '').match(/(?<=\[).*?(?=\])/)
      if (value) delay = parseInt(value[0])
    }
    el.debounceEvent = () => {
      clearTimeout(timer)
      timer = window.setTimeout(() => {
        binding.value()
      }, delay)
    }
    el.addEventListener(binding.arg, el.debounceEvent)
  },
  beforeUnmount(el: DebounceEl, binding: any) {
    el.removeEventListener(binding.arg, el.debounceEvent)
  },
}

export default debounceDirective
