import { ref, onMounted, onBeforeUnmount } from 'vue';

export function useClickOutside(popoverRef: any) {
  const popoverVisible = ref(false);

  const handleClickOutside = (event: Event) => {
    const popover = popoverRef.value;
    if (!popover) return;

    const triggerEl = popover.popperRef?.triggerRef;
    const popperEl = popover.popperRef?.popperRef;

    // 检查是否点击在当前popover内
    if (triggerEl?.contains(event.target as Node) || popperEl?.contains(event.target as Node)) {
      return;
    }

    // 检查是否点击在其他popper类组件内（包括时间选择器等）
    const target = event.target as HTMLElement;
    const isInPopper =
      target.closest('.el-popper') ||
      target.closest('.el-picker-panel') ||
      target.closest('.el-select-dropdown') ||
      target.closest('.el-cascader-panel');

    if (isInPopper) {
      return;
    }

    // 点击外部时关闭 popover
    popoverVisible.value = false;
  };

  onMounted(() => {
    document.addEventListener('click', handleClickOutside);
  });

  onBeforeUnmount(() => {
    document.removeEventListener('click', handleClickOutside);
  });

  return {
    popoverVisible,
  };
}
