export default {
  inserted(el, { value, modifiers }, vnode) {
    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();
      }
      left = oleft + e.pageX - _x;
      top = otop + e.pageY - _y;

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

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

      if (value && value.mouseUp) value.mouseUp({ oleft, otop });
      if (value && value.click && !isDrag) value.click();

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

      isDrag = false;
    };

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

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