import _defineProperty from '@babel/runtime/helpers/esm/defineProperty';
import { ref } from 'vue';
import { throttle } from 'lodash-es';
import { useEventListener } from '@vueuse/core';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const usePreviewImageDrag = transform => {
  const isDragging = ref(false);
  let startX;
  let startY;
  let imgOffsetX;
  let imgOffsetY;
  const handleMouseDown = event => {
    // 取消默认图片拖拽的行为
    event.preventDefault();
    isDragging.value = true;
    // 存储鼠标按下的偏移量和事件发生坐标
    const {
      offsetX,
      offsetY
    } = transform.value;
    startX = event.pageX;
    startY = event.pageY;
    imgOffsetX = offsetX;
    imgOffsetY = offsetY;
    transform.value.enableTransition = false;
  };
  const handleDrag = throttle(event => {
    transform.value = _objectSpread(_objectSpread({}, transform.value), {}, {
      offsetX: imgOffsetX + event.pageX - startX,
      offsetY: imgOffsetY + event.pageY - startY
    });
  });

  // mousemove 事件监听 document 拖拽效果更流畅
  useEventListener(document, 'mousemove', event => {
    if (!isDragging.value) {
      return;
    }
    handleDrag(event);
  });
  useEventListener(document, 'mouseup', () => {
    if (!isDragging.value) {
      return;
    }
    isDragging.value = false;
  });
  return {
    isDragging,
    handleMouseDown
  };
};

export { usePreviewImageDrag as default };
