import type { ComputedRef, Slots } from 'vue';
import type { BasicTableProps, InnerHandlers } from '../types/table';
import { Ref, unref, computed, h } from 'vue';
import TableHeader from '../components/TableHeaderErp.vue';
import { isString } from '/@/utils/is';
import { getSlot } from '/@/utils/helper/tsxHelper';
import { useDesign } from '/@/hooks/web/useDesign';
export function useTableHeaderErp(
  propsRef: ComputedRef<BasicTableProps>,
  slots: Slots,
  handlers: InnerHandlers,
  tableElRef: Ref<ComponentRef>,
) {
  const calcToolBarWidth = computed((): number => {
    const { prefixCls } = useDesign('basic-table-header');

    const table = unref(tableElRef);
    if (!table) return 0;

    const tableEl: Element = table.$el;

    if (!tableEl) return 0;

    return tableEl.querySelector('.' + prefixCls + '__toolbarBox')?.clientWidth || 0;
  });
  const getHeaderProps = computed((): Recordable => {
    const { title, showTableSetting, titleHelpMessage, tableSetting } = unref(propsRef);
    const hideTitle = !slots.tableTitle && !title && !slots.toolbar && !showTableSetting;
    if (hideTitle && !isString(title)) {
      return {};
    }

    return {
      title: hideTitle
        ? null
        : () =>
            h(
              TableHeader,
              {
                title,
                titleHelpMessage,
                showTableSetting,
                tableSetting,
                onColumnsChange: handlers.onColumnsChange,
              } as Recordable,
              {
                ...(slots.toolbar
                  ? {
                      toolbar: () => getSlot(slots, 'toolbar'),
                    }
                  : {}),
                ...(slots.tableTitle
                  ? {
                      tableTitle: () => getSlot(slots, 'tableTitle'),
                    }
                  : {}),
                ...(slots.headerTop
                  ? {
                      headerTop: () => getSlot(slots, 'headerTop'),
                    }
                  : {}),
                ...(slots.headerContent
                  ? {
                      headerContent: () => getSlot(slots, 'headerContent'),
                    }
                  : {}),
              },
            ),
    };
  });
  return { getHeaderProps, calcToolBarWidth };
}
