/*
 * @Descripttion: 
 * @version: 
 * @Author: ysh
 * @Date: 2023-06-28 14:17:04
 * @LastEditors: 
 * @LastEditTime: 2023-07-17 11:24:07
 */
import type { App, Directive, DirectiveBinding, ref } from 'vue';

const vDrag: Directive<any, void> = (el: HTMLElement, bingding: DirectiveBinding) => {
  // let moveEl = el.firstElementChild as HTMLElement;
  let moveEl = el as HTMLElement;

  let positionX: Number, positionY: Number;
  const mouseDown = (e: MouseEvent) => {
    //鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
    // 鼠标点击物体那一刻相对于物体上边框的距离 = 点击时的位置相对于浏览器最上边的距离 - 物体上边框相对于浏览器最上边的距离
    // console.log(e.clientX, e.clientY, "-----起始", el.offsetLeft);
    let X = e.clientX - el.offsetLeft;//clientX 事件属性返回当事件被触发时鼠标指针相对于浏览器页面（或客户区）的水平坐标
    let Y = e.clientY - el.offsetTop;
    const move = (e: MouseEvent) => {
      // 获取拖拽元素的位置
      let left = e.clientX - X;
      let top = e.clientY - Y;
      positionX = left;
      positionY = top;
      if (left <= 0) {
        left = 0
      } else if (left >= document.documentElement.clientWidth - el.offsetWidth) {
        left = document.documentElement.clientWidth - el.offsetWidth
      }

      if (top <= 0) {
        top = 0
      } else if (top > document.documentElement.clientHeight - el.offsetHeight) {
        top = document.documentElement.clientHeight - el.offsetHeight
      }

      el.style.left = left + "px";
      el.style.top = top + "px";
    };
    document.addEventListener("mousemove", move);
    document.addEventListener("mouseup", () => {
      document.removeEventListener("mousemove", move);
    });
    document.body.onselectstart = document.body.ondrag = () => { return false }
  };
  moveEl.addEventListener("mousedown", mouseDown);
  document.body.onselectstart = document.body.ondrag = () => { return true }
};
export function setupDragDirective(app: App) {
  app.directive('drag', vDrag);
}