// 长按手势指令
import { ref } from 'vue';

const longPressDuration = ref(500); // 长按时间阈值，单位毫秒
let start = null; // 按下函数
let move = null; // 移动函数
let cancel = null; // 取消函数
let isMove = false // 是否移动

export default {
  beforeMount(el, binding) {
    let pressTimer = null;

    start = (e) => {
      isMove = false;

      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          // 长按定时器触发，先不执行函数，等待 touchend 判断坐标
          !isMove && binding.value();
        }, longPressDuration.value);
      }
    };

    move = (e) => {
      isMove = true
    }

    cancel = (e) => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    };

    el.addEventListener('touchstart', start);
    el.addEventListener('touchmove', move)
    el.addEventListener('touchend', cancel);
    el.addEventListener('touchcancel', cancel);
  },
  unmounted(el) {
    el.removeEventListener('touchstart', start);
    el.removeEventListener('touchmove', move)
    el.removeEventListener('touchend', cancel);
    el.removeEventListener('touchcancel', cancel);
  }
};