import { onMounted, onUnmounted } from "vue";

export function dragImage() {
  // grab moving
  let pos = { top: 0, left: 0, x: 0, y: 0 };
  const dragContainer = $ref<HTMLDivElement>();
  // let isGrabbing = $ref(false);

  const mouseDownHandler = function (e: MouseEvent) {
    // 防止鼠标左键激发
    if (e.button !== 0) return;
    pos = {
      // The current scroll
      left: dragContainer.scrollLeft,
      top: dragContainer.scrollTop,
      // Get the current mouse position
      x: e.clientX,
      y: e.clientY,
    };
    // isGrabbing = true;
    if (dragContainer) {
      dragContainer.style.cursor = "grabbing";

      dragContainer.addEventListener("mousemove", mouseMoveHandler);
      dragContainer.addEventListener("mouseup", mouseUpHandler);
    }
  };

  const mouseMoveHandler = function (e: MouseEvent) {
    // if (!isGrabbing) return;
    // How far the mouse has been moved
    const dx = e.clientX - pos.x;
    const dy = e.clientY - pos.y;

    // Scroll the element
    dragContainer.scrollTop = pos.top - dy;
    dragContainer.scrollLeft = pos.left - dx;
  };
  const mouseUpHandler = function () {
    // isGrabbing = false;
    if (dragContainer) {
      dragContainer.removeEventListener("mousemove", mouseMoveHandler);
      dragContainer.removeEventListener("mouseup", mouseUpHandler);
      dragContainer.style.cursor = "auto";
    }
  };

  onMounted(() => {
    if (dragContainer) {
      dragContainer.addEventListener("mousedown", mouseDownHandler);
    }
  });
  onUnmounted(() => {
    if (dragContainer) {
      dragContainer.removeEventListener("mousedown", mouseDownHandler);
      dragContainer.removeEventListener("mousemove", mouseMoveHandler);
      dragContainer.removeEventListener("mouseup", mouseUpHandler);
    }
  });

  return $$({ dragContainer });
}
