// src/hooks/useCalTableHeight.ts
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';

interface TableHeightOptions {
  formRef?: any; // 表单引用，用于监听表单变化
  offsetBottom?: number; // 底部预留空间，默认为50
  minHeight?: number; // 最小高度，默认为300
}

const useCalTableHeight = (options: TableHeightOptions = {}) => {
  const { formRef, offsetBottom = 50, minHeight = 300 } = options;

  const tableHeight = ref(0);
  let formBoxObserver: ResizeObserver | null = null;
  let paginationObserver: MutationObserver | null = null;
  let formContentObserver: MutationObserver | null = null;

  // 防抖处理窗口大小变化
  let resizeTimer: any = null;
  let calHeightTimer: any = null;

  // 计算表格高度的主要函数
  const calTableHeight = () => {
    // 清除之前的定时器
    if (calHeightTimer) {
      clearTimeout(calHeightTimer);
    }

    // 使用防抖确保不会频繁计算
    calHeightTimer = setTimeout(() => {
      requestAnimationFrame(() => {
        nextTick(() => {
          const tableElement = document.querySelector('.ant-table') as HTMLElement;
          const paginationElement = document.querySelector('.ant-pagination') as HTMLElement;

          if (tableElement) {
            const tableOffsetTop = tableElement.getBoundingClientRect().top;
            const windowHeight = window.innerHeight;

            // 计算分页器高度，如果不存在则为0
            const paginationHeight = paginationElement
              ? paginationElement.offsetHeight + 20 // 20是分页器上下间距
              : 40; // 默认分页器高度+间距

            // 为底部留出更多空间，确保分页器可见
            const reservedSpace = paginationHeight + offsetBottom;

            let calculatedHeight = windowHeight - tableOffsetTop - reservedSpace;

            // 确保表格高度不会过小
            if (calculatedHeight < minHeight) {
              calculatedHeight = minHeight;
            }

            tableHeight.value = calculatedHeight;
          }
        });
      });
    }, 100);
  };

  // 监听分页器变化
  const observePagination = () => {
    const paginationWrapper = document.querySelector('.ant-pagination');
    if (paginationWrapper) {
      const observer = new MutationObserver(() => {
        calTableHeight();
      });

      observer.observe(paginationWrapper, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ['style', 'class'],
      });

      return observer;
    }
    return null;
  };

  // 监听 page-form-box 尺寸变化
  const observeFormBox = () => {
    const formBox = document.querySelector('.hb-lib-list-page-form-box');
    if (formBox) {
      // 使用 ResizeObserver 监听元素尺寸变化
      formBoxObserver = new ResizeObserver(() => {
        const tooltips = document.querySelectorAll('.ant-tooltip');
        tooltips.forEach((tooltip) => {
          tooltip.style.display = 'none';
        });
        calTableHeight();
      });
      // 通过ResizeObserver可以指定监听某个盒子的尺寸变化
      formBoxObserver.observe(formBox);
    }
  };

  // 监听表单内容变化
  const observeFormContent = () => {
    const formBox = document.querySelector('.hb-lib-list-page-form-box');
    if (formBox) {
      formContentObserver = new MutationObserver(() => {
        // 延迟执行以确保 DOM 更新完成
        setTimeout(() => {
          calTableHeight();
        }, 100);
      });

      formContentObserver.observe(formBox, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ['style', 'class'],
      });
    }
  };

  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer);
    }
    resizeTimer = setTimeout(() => {
      calTableHeight();
    }, 100);
  };

  // 初始化监听
  const initObserver = () => {
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);

    // 监听 page-form-box 尺寸变化
    nextTick(() => {
      observeFormBox();
      observeFormContent();

      // 观察分页器变化
      paginationObserver = observePagination();
    });
  };

  // 清理事件监听
  const cleanup = () => {
    window.removeEventListener('resize', handleResize);

    if (formBoxObserver) {
      formBoxObserver.disconnect();
    }

    if (formContentObserver) {
      formContentObserver.disconnect();
    }

    if (paginationObserver) {
      paginationObserver.disconnect();
    }

    if (resizeTimer) {
      clearTimeout(resizeTimer);
    }

    if (calHeightTimer) {
      clearTimeout(calHeightTimer);
    }
  };

  // 如果提供了formRef，则监听其变化
  if (formRef) {
    watch(
      () => formRef,
      () => {
        // 表单数据变化时延迟计算高度
        setTimeout(() => {
          calTableHeight();
        }, 200);
      },
      { deep: true }
    );
  }

  // 组件挂载时初始化
  onMounted(() => {
    calTableHeight();
    initObserver();
  });

  // 组件卸载时清理
  onUnmounted(() => {
    cleanup();
  });

  return {
    tableHeight,
    calTableHeight,
  };
};

export default useCalTableHeight;
