import { computed, ref, onBeforeUnmount, watch, Ref, nextTick } from 'vue';
import { debounce } from 'lodash-es';
import type { DynamicTableProps } from '../dynamic-table';
import type { TableMethods } from '@/components/lt-a-table/src';

type UseScrollParams = {
  props: DynamicTableProps;
  tableID: string;
  tableData: Ref<any[]>;
  tableMethods: TableMethods;
};

export type UseScrollType = ReturnType<typeof useScroll>;

// 获取元素到顶部距离-通用方法
export const getPositionTop = (node: HTMLElement) => {
  let top = node.offsetTop;
  let parent = node.offsetParent as HTMLElement;
  while (parent != null) {
    top += parent.offsetTop;
    parent = parent.offsetParent as HTMLElement;
  }
  return top; // 所有的父元素top和
};

export const useScroll = ({ props, tableID, tableData, tableMethods }: UseScrollParams) => {
  // const currIns = getCurrentInstance();
  const { initColumnFilter } = tableMethods;
  const scrollY = ref<number>();
  const scroll = computed(() => {
    return {
      y: scrollY.value,
      x: '100%', //使滚动条为所有列之和
      ...props.scroll,
    };
  });

  const getScrollY = debounce(() => {
    //自动计算表格滚动高度
    if (!props.autoHeight) return;
    const targetTable = $('#' + tableID);
    const el =
      targetTable.find('.ant-table-body').get(0) || targetTable.find('.ant-table-tbody').get(0); //表格主体
    if (el) {
      const y = document.documentElement.offsetHeight - getPositionTop(el as HTMLDivElement);
      // 简单粗糙的实现
      scrollY.value = y - 52;
    }
    nextTick(() => {
      initColumnFilter(tableID, props);
    });
  });

  window.addEventListener('resize', getScrollY);
  watch(() => tableData.value, getScrollY);

  onBeforeUnmount(() => {
    window.removeEventListener('resize', getScrollY);
  });

  return {
    scroll,
  };
};
