// 外层元素点击拖拽
const itemDrag = (
  ev: any,
  emit: Function,
  props: any,
  style: any,
  moveing: any
): void => {
  let press_x = ev.clientX;
  let press_y = ev.clientY;
  let target: any = ev.target || ev.srcElement;
  ev.stopPropagation();
  ev.preventDefault();

  emit("downHandler", {
    // 点击元素事件回调
    el: target,
    e: ev,
  });
  if (!props.isDraggable) return;
  //鼠标按下并移动的事件

  interface IMoveParam {
    movementX: number;
    movementY: number;
    clientX: number;
    clientY: number;
  }

  const onmove = (param: any) => {
    if (param.movementX || param.movementY) {
      moveing.value = true;

      let offset_left = press_x - param.clientX;
      let offset_top = press_y - param.clientY;
      press_x = param.clientX;
      press_y = param.clientY;

      //绑定元素位置到positionX和positionY上面

      //移动当前元素
      style.top -= offset_top;
      style.left -= offset_left;
      emit("moveHandler", {
        // 移动事件回调
        el: target,
        param,
        top: style.top,
        left: style.left,
      });
    }
  };

  document.onmousemove = (e: any) => {
    onmove(e);
  };

  if ((<any>window).touchPriority) {
    if ("ontouchmove" in document.documentElement === true) {
      document.ontouchmove = (e: TouchEvent) => {
        if (e.changedTouches && e.changedTouches.length) {
          onmove({
            movementX: 1,
            movementY: 1,
            clientX: e.changedTouches[0].clientX,
            clientY: e.changedTouches[0].clientY,
          });
        }
      };
    }
  }

  const onmoveend = (e: any) => {
    moveing.value = false;
    if (style.left == style.back_left && style.top == style.back_top) {
      style.left = style.back_left;
      style.top = style.back_top;
    } else {
      emit("moveEndHandler", {
        // 抬起事件回调
        el: target,
        e,
        top: style.top,
        left: style.left,
      });
    }

    document.onmousemove = null;
    document.onmouseup = null;
    if ("ontouchmove" in document.documentElement === true) {
      document.ontouchmove = null;
    }
    if ("ontouchend" in document.documentElement === true) {
      document.ontouchend = null;
    }
  };

  document.onmouseup = onmoveend;
  if ((<any>window).touchPriority) {
    if ("ontouchend" in document.documentElement === true) {
      document.ontouchend = (e) => onmoveend(e);
    }
  }
};
export default itemDrag;
