 /**
  * v-vsroll dom容器滚动指令
  * speed 滚动速度
  * limit dom的可视高度与元素高度的差值限制
  * 
  */
 export default {
    mounted(el, binding, vnode) {
        domUpdate(el, binding, vnode, true)
    },
    updated(el, binding, vnode) {
        domUpdate(el, binding, vnode, !binding.oldValue.VSINTERVAL)
    },
    beforeUnmount(el, binding) {
        
        if (binding.value && binding.value.VSINTERVAL) {
            clearInterval(binding.value.VSINTERVAL);
            return
        }

        if (binding.oldValue && binding.oldValue.VSINTERVAL) {
            clearInterval(binding.oldValue.VSINTERVAL);
        }
    }
}

function domUpdate(el, binding, vnode, flag) {
    const {
        value
    } = binding

    let interval = null;

    let speed = 30;
    let limit = 0;
    if (value?.constructor === Object) {
        speed = value.speed || 30;
        limit = value.limit || 0
    } else {
        binding.value = {}
    }

    if (binding.oldValue && binding.oldValue.VSINTERVAL){
       binding.value.VSINTERVAL = binding.oldValue.VSINTERVAL
    }


    if (el.scrollHeight - el.clientHeight <= limit) return;


    if (flag) {
        interval = rollInterval(el, speed);
        binding.value.VSINTERVAL = interval
        el.addEventListener('mouseenter', () => {
            clearInterval(interval)
        })

        el.addEventListener('mouseleave', () => {
            interval = rollInterval(el, speed);
            binding.value.VSINTERVAL = interval
        })
    }

}

function rollInterval(bodyWrapper, speed) {
    const interval = setInterval(() => {
        bodyWrapper.scrollTop += 1
        if (bodyWrapper.clientHeight + bodyWrapper.scrollTop == bodyWrapper.scrollHeight) {
            bodyWrapper.scrollTop = 0
        }
    }, speed)

    return interval
}