export default {
  mounted(el, binding) {
    const { draggable, position = 'absolute', scale, handle } = binding.value;
    // 获取触发拖拽的句柄元素（如标题栏）
    const dragHandle = handle ? el.querySelector(handle) : el;
    if (!draggable || !dragHandle) {
      // 如果拖拽功能被禁用，则不执行任何拖拽相关的逻辑
      return;
    }
    let scaleMethod = scale;
    if (!scaleMethod) {
      scaleMethod = () => {
        return { scaleX: 1, scaleY: 1 };
      };
    }
    el.style.position = position;
    let disX = 0; // 鼠标按下时，鼠标与拖拽元素的左边距
    let disY = 0; // 鼠标按下时，鼠标与拖拽元素的上边距
    dragHandle.style.cursor = 'move';
    dragHandle.onmousedown = (e) => {
      // 鼠标按下，计算当前元素距离可视区的距离
      disX = e.clientX / scaleMethod().scaleX - el.offsetLeft;
      disY = e.clientY / scaleMethod().scaleY - el.offsetTop;

      // 鼠标移动事件
      document.onmousemove = function (e) {
        // 通过事件委托，计算移动的距离
        const l = e.clientX / scaleMethod().scaleX - disX;
        const t = e.clientY / scaleMethod().scaleY - disY;
        // 移动当前元素
        el.style.left = `${l + 'px'}`;
        el.style.top = `${t + 'px'}`;

        // 将此时的位置传出去
        // binding.value({x:e.pageX,y:e.pageY})
      };

      // 鼠标松开事件
      document.onmouseup = function (e) {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  }
};
