export default {
  bind(el) {
    let startPosition = { x: 0, y: 0 };
    let dialogPosition = { x: 0, y: 0 };
    let dragging = false;
    
    const dialogHeaderEl = el.querySelector('.el-dialog__header');
    const dialogDom = el.querySelector('.el-dialog');
    
    if (!dialogHeaderEl || !dialogDom) return;
    
    // 设置鼠标样式
    dialogHeaderEl.style.cursor = 'move';

    const handleMouseDown = (e) => {
      if (e.button !== 0) return; // 只响应左键
      
      startPosition.x = e.clientX;
      startPosition.y = e.clientY;
      
      // 获取当前对话框位置
      dialogPosition.x = parseInt(dialogDom.style.left) || 0;
      dialogPosition.y = parseInt(dialogDom.style.top) || 0;
      console.log("打印当前对话框位置",dialogPosition);

      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      
      dragging = true;
      
      e.preventDefault();
      e.stopPropagation();
    };

    const handleMouseMove = (e) => {
      if (!dragging) return;
      
      e.preventDefault();
      
      const deltaX = e.clientX - startPosition.x;
      const deltaY = e.clientY - startPosition.y;
      
      // 计算新位置
      let newLeft = dialogPosition.x + deltaX;
      let newTop = dialogPosition.y + deltaY;

      console.log("打印当前对话框位置",dialogPosition);
      console.log("打印鼠标移动的距离",deltaX,deltaY);
      console.log("打印鼠标移动后的位置",newLeft,newTop);
      
      // 获取对话框和屏幕尺寸
      const dialogWidth = dialogDom.offsetWidth;
      const dialogHeight = dialogDom.offsetHeight;
      const screenWidth = window.innerWidth;
      const screenHeight = window.innerHeight;
      
      // 设置边界 - 允许对话框边缘稍微超出屏幕边界
      const margin = 100; // 允许超出的像素数
      const leftMin = -dialogWidth + margin;
      const leftMax = screenWidth - margin;
      const topMin = -dialogHeight + margin;
      const topMax = screenHeight - margin;
      
      // 应用边界限制
      // newLeft = Math.max(leftMin, Math.min(newLeft, leftMax));
      // newTop = Math.max(topMin, Math.min(newTop, topMax));
      // console.log("打印当前的newLeft,newTop",newLeft, newTop);
      
      dialogDom.style.left = newLeft + 'px';
      dialogDom.style.top = newTop + 'px';
    };

    const handleMouseUp = () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      dragging = false;
    };

    dialogHeaderEl.addEventListener('mousedown', handleMouseDown);
    
    // 清理函数
    el._cleanup = () => {
      dialogHeaderEl.removeEventListener('mousedown', handleMouseDown);
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  },
  
  unbind(el) {
    if (el._cleanup) {
      el._cleanup();
      delete el._cleanup;
    }
  }
};