import { onMounted, onUnmounted, ref } from "vue";

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

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

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

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

    console.log(e);

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

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

  return { dragContainer };
}
