export default {
  inserted(el, { value, modifiers }) {
    let [_x, _y] = [0, 0];
    // 当前拖动事务开始前元素的left,top
    let [oleft, otop] = [0, 0];
    // 元素移动后的left,top
    let [left, top] = [0, 0];
    let isDrag = false;

    let moveHandle = function (e) {
      isDrag = true;
      if (modifiers.prevent) {
        e.preventDefault();
      }
      if (modifiers.stop) {
        e.stopPropagation();
      }
      const mLeft = e.pageX - _x;
      const mTop = e.pageY - _y;
      left = oleft + mLeft;
      top = otop + mTop;

      // console.log(left, top);

      if (value && value.mouseMove) {
        value.mouseMove({ left, top, mLeft, mTop });
      } else {
        el.style.left = left + "px";
        el.style.top = top + "px";
      }
    };

    let upHandle = function (e) {
      if (modifiers.prevent) {
        e.preventDefault();
      }
      if (modifiers.stop) {
        e.stopPropagation();
      }
      oleft = left;
      otop = top;

      if (value && value.mouseUp) value.mouseUp({ left, top });
      if (value && value.click && !isDrag) value.click(e);

      document.removeEventListener("mousemove", moveHandle);
      document.removeEventListener("mouseup", upHandle);

      isDrag = false;
    };

    el.addEventListener("mousedown", function (e) {
      if (modifiers.prevent) {
        e.preventDefault();
      }
      if (modifiers.stop) {
        e.stopPropagation();
      }
      _x = e.pageX;
      _y = e.pageY;
      oleft = el.offsetLeft;
      otop = el.offsetTop;
      if (value && value.mouseDown) value.mouseDown({ oleft, otop }, e);

      document.addEventListener("mousemove", moveHandle);
      document.addEventListener("mouseup", upHandle);
    });
  },
};
