import { defineComponent, computed, toRef, reactive, watchEffect, nextTick, ref, watch, createVNode } from 'vue';
import '../../../utils/index.mjs';
import '../../../locale/index.mjs';
import '../../../hooks/index.mjs';
import '../../../vue-components/index.mjs';
import VcTable, { INTERNAL_HOOKS } from '../../../vue-components/vc-table/src/Table.mjs';
import { Spin } from '../../spin/index.mjs';
import { Pagination } from '../../pagination/index.mjs';
import useConfigInject from '../../config-provider/src/hooks/useConfigInject.mjs';
import { useLocaleReceiver } from '../../locale-provider/src/useLocaleReceiver.mjs';
import useStyle from '../style/index.mjs';
import usePagination, { getPaginationParam, DEFAULT_PAGE_SIZE } from './hooks/usePagination.mjs';
import useLazyKVMap from './hooks/useLazyKVMap.mjs';
import useSelection from './hooks/useSelection.mjs';
import useFilterSorter, { getSortData } from './hooks/useSorter.mjs';
import useFilter, { getFilterData } from './hooks/useFilter.mjs';
import useTitleColumns from './hooks/useTitleColumns.mjs';
import renderExpandIcon from './ExpandIcon.mjs';
import { useProvideSlots, useProvideTableContext } from './context.mjs';
import useColumns from './hooks/useColumns.mjs';
import { tableProps } from './props.mjs';
import { initDefaultProps } from '../../../utils/vue/initDefaultProps.mjs';
import { objectType } from '../../../utils/vue/propType.mjs';
import { devWarning } from '../../../utils/log.mjs';
import { useBreakpoint } from '../../../hooks/use-breakpoint/index.mjs';
import localeValues from '../../../locale/lang/en_US.mjs';
import { scrollTo } from '../../../utils/scroll/scrollTo.mjs';
import { classNames } from '../../../utils/dom/class.mjs';
import { omit } from '../../../utils/lang/omit.mjs';

const EMPTY_LIST = [];
var InternalTable = /* @__PURE__ */ defineComponent({
  name: "InternalTable",
  inheritAttrs: false,
  props: initDefaultProps({
    ...tableProps(),
    contextSlots: objectType()
  }, {
    rowKey: "key"
  }),
  setup(props, {
    attrs,
    slots,
    expose,
    emit
  }) {
    devWarning(!(typeof props.rowKey === "function" && props.rowKey.length > 1), "Table", "`index` parameter of `rowKey` function is deprecated. There is no guarantee that it will work as expected.");
    useProvideSlots(computed(() => props.contextSlots));
    useProvideTableContext({
      onResizeColumn: (w, col) => {
        emit("resizeColumn", w, col);
      }
    });
    const screens = useBreakpoint();
    const mergedColumns = computed(() => {
      const matched = new Set(Object.keys(screens.value).filter((m) => screens.value[m]));
      return props.columns.filter((c) => !c.responsive || c.responsive.some((r) => matched.has(r)));
    });
    const {
      size: mergedSize,
      renderEmpty,
      direction,
      prefixCls,
      configProvider
    } = useConfigInject("table", props);
    const [wrapSSR, hashId] = useStyle(prefixCls);
    const transformCellText = computed(() => {
      var _a;
      return props.transformCellText || ((_a = configProvider.transformCellText) == null ? void 0 : _a.value);
    });
    const [tableLocale] = useLocaleReceiver("Table", localeValues.Table, toRef(props, "locale"));
    const rawData = computed(() => props.dataSource || EMPTY_LIST);
    const dropdownPrefixCls = computed(() => configProvider.getPrefixCls("dropdown", props.dropdownPrefixCls));
    const childrenColumnName = computed(() => props.childrenColumnName || "children");
    const expandType = computed(() => {
      if (rawData.value.some((item) => item == null ? void 0 : item[childrenColumnName.value]))
        return "nest";
      if (props.expandedRowRender)
        return "row";
      return null;
    });
    const internalRefs = reactive({
      body: null
    });
    const updateInternalRefs = (refs) => {
      Object.assign(internalRefs, refs);
    };
    const getRowKey = computed(() => {
      if (typeof props.rowKey === "function")
        return props.rowKey;
      return (record) => record == null ? void 0 : record[props.rowKey];
    });
    const [getRecordByKey] = useLazyKVMap(rawData, childrenColumnName, getRowKey);
    const changeEventInfo = {};
    const triggerOnChange = (info, action, reset = false) => {
      const {
        pagination,
        scroll,
        onChange
      } = props;
      const changeInfo = {
        ...changeEventInfo,
        ...info
      };
      if (reset) {
        changeEventInfo.resetPagination();
        if (changeInfo.pagination.current)
          changeInfo.pagination.current = 1;
        if (pagination && pagination.onChange)
          pagination.onChange(1, changeInfo.pagination.pageSize);
      }
      if (scroll && scroll.scrollToFirstRowOnChange !== false && internalRefs.body) {
        scrollTo(0, {
          getContainer: () => internalRefs.body
        });
      }
      onChange == null ? void 0 : onChange(changeInfo.pagination, changeInfo.filters, changeInfo.sorter, {
        currentDataSource: getFilterData(getSortData(rawData.value, changeInfo.sorterStates, childrenColumnName.value), changeInfo.filterStates),
        action
      });
    };
    const onSorterChange = (sorter, sorterStates) => {
      triggerOnChange({
        sorter,
        sorterStates
      }, "sort", false);
    };
    const [transformSorterColumns, sortStates, sorterTitleProps, sorters] = useFilterSorter({
      prefixCls,
      mergedColumns,
      onSorterChange,
      sortDirections: computed(() => props.sortDirections || ["ascend", "descend"]),
      tableLocale,
      showSorterTooltip: toRef(props, "showSorterTooltip")
    });
    const sortedData = computed(() => getSortData(rawData.value, sortStates.value, childrenColumnName.value));
    const onFilterChange = (filters2, filterStates2) => {
      triggerOnChange({
        filters: filters2,
        filterStates: filterStates2
      }, "filter", true);
    };
    const [transformFilterColumns, filterStates, filters] = useFilter({
      prefixCls,
      locale: tableLocale,
      dropdownPrefixCls,
      mergedColumns,
      onFilterChange,
      getPopupContainer: toRef(props, "getPopupContainer")
    });
    const mergedData = computed(() => getFilterData(sortedData.value, filterStates.value));
    const [transformBasicColumns] = useColumns(toRef(props, "contextSlots"));
    const columnTitleProps = computed(() => {
      const mergedFilters = {};
      const filtersValue = filters.value;
      Object.keys(filtersValue).forEach((filterKey) => {
        if (filtersValue[filterKey] !== null)
          mergedFilters[filterKey] = filtersValue[filterKey];
      });
      return {
        ...sorterTitleProps.value,
        filters: mergedFilters
      };
    });
    const [transformTitleColumns] = useTitleColumns(columnTitleProps);
    const onPaginationChange = (current, pageSize) => {
      triggerOnChange({
        pagination: {
          ...changeEventInfo.pagination,
          current,
          pageSize
        }
      }, "paginate");
    };
    const [mergedPagination, resetPagination] = usePagination(computed(() => mergedData.value.length), toRef(props, "pagination"), onPaginationChange);
    watchEffect(() => {
      changeEventInfo.sorter = sorters.value;
      changeEventInfo.sorterStates = sortStates.value;
      changeEventInfo.filters = filters.value;
      changeEventInfo.filterStates = filterStates.value;
      changeEventInfo.pagination = props.pagination === false ? {} : getPaginationParam(mergedPagination.value, props.pagination);
      changeEventInfo.resetPagination = resetPagination;
    });
    const pageData = computed(() => {
      if (props.pagination === false || !mergedPagination.value.pageSize)
        return mergedData.value;
      const {
        current = 1,
        total,
        pageSize = DEFAULT_PAGE_SIZE
      } = mergedPagination.value;
      devWarning(current > 0, "Table", "`current` should be positive number.");
      if (mergedData.value.length < total) {
        if (mergedData.value.length > pageSize)
          return mergedData.value.slice((current - 1) * pageSize, current * pageSize);
        return mergedData.value;
      }
      return mergedData.value.slice((current - 1) * pageSize, current * pageSize);
    });
    watchEffect(() => {
      nextTick(() => {
        const {
          total,
          pageSize = DEFAULT_PAGE_SIZE
        } = mergedPagination.value;
        if (mergedData.value.length < total) {
          if (mergedData.value.length > pageSize) {
            devWarning(false, "Table", "`dataSource` length is less than `pagination.total` but large than `pagination.pageSize`. Please make sure your config correct data with async mode.");
          }
        }
      });
    }, {
      flush: "post"
    });
    const expandIconColumnIndex = computed(() => {
      if (props.showExpandColumn === false)
        return -1;
      if (expandType.value === "nest" && props.expandIconColumnIndex === void 0)
        return props.rowSelection ? 1 : 0;
      else if (props.expandIconColumnIndex > 0 && props.rowSelection)
        return props.expandIconColumnIndex - 1;
      return props.expandIconColumnIndex;
    });
    const rowSelection = ref();
    watch(() => props.rowSelection, () => {
      rowSelection.value = props.rowSelection ? {
        ...props.rowSelection
      } : props.rowSelection;
    }, {
      deep: true,
      immediate: true
    });
    const [transformSelectionColumns, selectedKeySet] = useSelection(rowSelection, {
      prefixCls,
      data: mergedData,
      pageData,
      getRowKey,
      getRecordByKey,
      expandType,
      childrenColumnName,
      locale: tableLocale,
      getPopupContainer: computed(() => props.getPopupContainer)
    });
    const internalRowClassName = (record, index, indent) => {
      let mergedRowClassName;
      const {
        rowClassName
      } = props;
      if (typeof rowClassName === "function")
        mergedRowClassName = classNames(rowClassName(record, index, indent));
      else
        mergedRowClassName = classNames(rowClassName);
      return classNames({
        [`${prefixCls.value}-row-selected`]: selectedKeySet.value.has(getRowKey.value(record, index))
      }, mergedRowClassName);
    };
    expose({
      selectedKeySet
    });
    const indentSize = computed(() => {
      return typeof props.indentSize === "number" ? props.indentSize : 15;
    });
    const transformColumns = (innerColumns) => {
      const res = transformTitleColumns(transformSelectionColumns(transformFilterColumns(transformSorterColumns(transformBasicColumns(innerColumns)))));
      return res;
    };
    return () => {
      var _a;
      const {
        expandIcon = slots.expandIcon || renderExpandIcon(tableLocale.value),
        pagination,
        loading,
        bordered
      } = props;
      let topPaginationNode;
      let bottomPaginationNode;
      if (pagination !== false && ((_a = mergedPagination.value) == null ? void 0 : _a.total)) {
        let paginationSize;
        if (mergedPagination.value.size) {
          paginationSize = mergedPagination.value.size;
        } else {
          paginationSize = mergedSize.value === "small" || mergedSize.value === "middle" ? "small" : void 0;
        }
        const renderPagination = (position2) => createVNode(Pagination, {
          ...mergedPagination.value,
          "class": [`${prefixCls.value}-pagination ${prefixCls.value}-pagination-${position2}`, mergedPagination.value.class],
          "size": paginationSize
        }, null);
        const defaultPosition = direction.value === "rtl" ? "left" : "right";
        const {
          position
        } = mergedPagination.value;
        if (position !== null && Array.isArray(position)) {
          const topPos = position.find((p) => p.includes("top"));
          const bottomPos = position.find((p) => p.includes("bottom"));
          const isDisable = position.every((p) => `${p}` === "none");
          if (!topPos && !bottomPos && !isDisable)
            bottomPaginationNode = renderPagination(defaultPosition);
          if (topPos)
            topPaginationNode = renderPagination(topPos.toLowerCase().replace("top", ""));
          if (bottomPos)
            bottomPaginationNode = renderPagination(bottomPos.toLowerCase().replace("bottom", ""));
        } else {
          bottomPaginationNode = renderPagination(defaultPosition);
        }
      }
      let spinProps;
      if (typeof loading === "boolean") {
        spinProps = {
          spinning: loading
        };
      } else if (typeof loading === "object") {
        spinProps = {
          spinning: true,
          ...loading
        };
      }
      const wrapperClassNames = classNames(`${prefixCls.value}-wrapper`, {
        [`${prefixCls.value}-wrapper-rtl`]: direction.value === "rtl"
      }, attrs.class, hashId.value);
      const getTableProps = omit(props, ["columns"]);
      return wrapSSR(createVNode("div", {
        "class": wrapperClassNames,
        "style": attrs.style
      }, [createVNode(Spin, {
        "spinning": false,
        ...spinProps
      }, {
        default: () => [topPaginationNode, createVNode(VcTable, {
          ...attrs,
          ...getTableProps,
          "expandedRowKeys": props.expandedRowKeys,
          "defaultExpandedRowKeys": props.defaultExpandedRowKeys,
          "expandIconColumnIndex": expandIconColumnIndex.value,
          "indentSize": indentSize.value,
          "expandIcon": expandIcon,
          "columns": mergedColumns.value,
          "direction": direction.value,
          "prefixCls": prefixCls.value,
          "class": classNames({
            [`${prefixCls.value}-middle`]: mergedSize.value === "middle",
            [`${prefixCls.value}-small`]: mergedSize.value === "small",
            [`${prefixCls.value}-bordered`]: bordered,
            [`${prefixCls.value}-empty`]: rawData.value.length === 0
          }),
          "data": pageData.value,
          "rowKey": getRowKey.value,
          "rowClassName": internalRowClassName,
          "internalHooks": INTERNAL_HOOKS,
          "internalRefs": internalRefs,
          "onUpdateInternalRefs": updateInternalRefs,
          "transformColumns": transformColumns,
          "transformCellText": transformCellText.value
        }, {
          ...slots,
          emptyText: () => {
            var _a2, _b;
            return ((_a2 = slots.emptyText) == null ? void 0 : _a2.call(slots)) || ((_b = props.locale) == null ? void 0 : _b.emptyText) || renderEmpty("Table");
          }
        }), bottomPaginationNode]
      })]));
    };
  }
});

export { InternalTable as default };
//# sourceMappingURL=InternalTable.mjs.map
