module.exports = {
  inserted(el, { value, modifiers }) {
    let [_x, _y] = [0, 0];
    // 只允许鼠标左键触发
    let moveHandle = function (e) {
      if (e.button !== 0) return;
      if (modifiers.prevent) {
        e.preventDefault();
      }
      if (modifiers.stop) {
        e.stopPropagation();
      }

      let left = e.pageX - _x;
      let top = e.pageY - _y;

      value.moveElement({ left, top });
    };

    let upHandle = function (e) {
      if (e.button !== 0) return;
      if (modifiers.prevent) {
        e.preventDefault();
      }
      if (modifiers.stop) {
        e.stopPropagation();
      }
      value.moveStop && value.moveStop();
      document.removeEventListener("mousemove", moveHandle);
      document.removeEventListener("mouseup", upHandle);
    };

    el.addEventListener("mousedown", function (e) {
      if (e.button !== 0) return;
      if (modifiers.prevent) {
        e.preventDefault();
      }
      if (modifiers.stop) {
        e.stopPropagation();
      }
      _x = e.pageX;
      _y = e.pageY;
      value.moveStart && value.moveStart();

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