import { ref, onBeforeUnmount } from 'vue';

export default function useDrag() {
  const isDragging = ref(false); // 是否正在拖动
  const offsetX = ref(0); // 鼠标按下时的 X 坐标偏移
  const offsetY = ref(0); // 鼠标按下时的 Y 坐标偏移
  const style = ref({
    position: 'absolute', // 设置为绝对定位
    top: '200px', // 初始位置
    left: '70px', // 初始位置
  });

  // 鼠标按下时，记录偏移量并开始拖动
  const startDrag = (event: MouseEvent) => {
    isDragging.value = true;
    offsetX.value = event.clientX - (event.target as HTMLElement).getBoundingClientRect().left;
    offsetY.value = event.clientY - (event.target as HTMLElement).getBoundingClientRect().top;

    // 添加鼠标移动和鼠标松开事件监听
    document.addEventListener('mousemove', onDrag);
    document.addEventListener('mouseup', stopDrag);
  };

  // 鼠标移动时，更新元素的位置
  const onDrag = (event: MouseEvent) => {
    if (isDragging.value) {

        if(event.clientX - offsetX.value + 280 > window.innerWidth){
            return null;
        }
        if(event.clientY - offsetY.value + 20 > window.innerHeight){
            return null;
        }
        style.value.left  =  (event.clientX - offsetX.value - 200) > 0 ? `${event.clientX - offsetX.value - 200}px` : '0px'
        style.value.top = (event.clientY - offsetY.value - 100) > 0 ?   `${event.clientY - offsetY.value - 100}px` : '0px';

        
    }
  };

  // 鼠标松开时，停止拖动
  const stopDrag = () => {
    isDragging.value = false;
    document.removeEventListener('mousemove', onDrag);
    document.removeEventListener('mouseup', stopDrag);
  };

  // 在组件卸载时移除事件监听
  onBeforeUnmount(() => {
    document.removeEventListener('mousemove', onDrag);
    document.removeEventListener('mouseup', stopDrag);
  });

  return {
    style,
    startDrag,
  };
}
