import { Directive, DirectiveBinding } from "vue"

const CTX_SCROLL_LOADMORE_HANDLER = 'CTX_SCROLL_LOADMORE_HANDLER'
let LAST_TRIGGER_EVENT = 0
interface CustomHTMLElement extends HTMLElement {
  [CTX_SCROLL_LOADMORE_HANDLER]?: (event: Event) => void
} 

const callbackEvent = (event:any, binding: DirectiveBinding<any>)=>{
    const that = event.target
    if(that.scrollHeight - Math.ceil(that.scrollTop) - that.clientHeight <= 3){
        if(LAST_TRIGGER_EVENT == 0 || (new Date()).getTime() - LAST_TRIGGER_EVENT >= 300){
            binding.value()
            LAST_TRIGGER_EVENT = (new Date()).getTime()
        }
    }
}

const LoadMoreDirective: Directive = {
    mounted(el: CustomHTMLElement, binding) {
        let obj = el.querySelector('.el-scrollbar__wrap')
        if(obj){
            el[CTX_SCROLL_LOADMORE_HANDLER] = (event: Event) => callbackEvent(event, binding)
            obj.addEventListener('scroll', el[CTX_SCROLL_LOADMORE_HANDLER])
        }else{ }
    },
    
    unmounted(el: CustomHTMLElement) {
        if (el[CTX_SCROLL_LOADMORE_HANDLER]) {
            document.removeEventListener('scroll', el[CTX_SCROLL_LOADMORE_HANDLER])
            delete el[CTX_SCROLL_LOADMORE_HANDLER]
        }
    },
  }

  export default LoadMoreDirective