// 长按指令
//eg: v-longpress="{ handler: onLongPressItem, args: item, duration: 1000 }"
let start,cancel;
const LongPressDirective = {
  beforeMount(el, binding) {
    let pressTimer = null;

    // 长按开始
    start = (event) => {
      if (event.type === 'click' && event.button !== 0) {
        return;
      }

      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          binding.value.handler(binding.value.args);
        }, binding.value.duration || 500); // 默认长按时间为500毫秒，可通过value.duration修改
      }
    };

    // 长按结束
    cancel = () => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    };

    el.addEventListener('mousedown', start);
    el.addEventListener('touchstart', start);

    el.addEventListener('click', cancel);
    el.addEventListener('mouseout', cancel);
    el.addEventListener('touchend', cancel);
    el.addEventListener('touchcancel', cancel);
  },

  beforeUnmount(el) {
    if(!start) return
    el.removeEventListener('mousedown', start);
    el.removeEventListener('touchstart', start);

    el.removeEventListener('click', cancel);
    el.removeEventListener('mouseout', cancel);
    el.removeEventListener('touchend', cancel);
    el.removeEventListener('touchcancel', cancel);
  }
};

export default LongPressDirective