import { onBeforeUnmount } from "vue";

export default function useDisableScroll() {
  let el;
  const bodyTouchMove = (evt) => {
    if (!evt._isScroller) {
      evt.preventDefault();
    }
  };
  const elTouchstart = () => {
    var top = el.scrollTop,
      totalScroll = el.scrollHeight,
      currentScroll = top + el.offsetHeight;
    if (top === 0) {
      el.scrollTop = 1;
    } else if (currentScroll === totalScroll) {
      el.scrollTop = top - 1;
    }
  };

  const elTouchmove = (evt) => {
    if (el.offsetHeight < el.scrollHeight) evt._isScroller = true;
  };
  const overscroll = function (el) {
    if (!el) return;
    el.addEventListener("touchstart", elTouchstart);
    el.addEventListener("touchmove", elTouchmove);
  };

  const addScrollEvent = (tagName) => {
    el = document.querySelector(tagName);
    console.log(tagName, el);
    overscroll(el);
    document.body.addEventListener("touchmove", bodyTouchMove, {
      passive: false,
    });
  };

  const removeElEvent = () => {
    if (!el) return;
    el.removeEventListener("touchstart", elTouchstart);
    el.removeEventListener("touchmove", elTouchmove);
  };
  onBeforeUnmount(() => {
    document.body.removeEventListener("touchmove", bodyTouchMove, {
      passive: false,
    });
    removeElEvent();
  });
  return {
    addScrollEvent,
    removeElEvent,
  };
}
