import { createVNode, computed } from 'vue';
import '../../../../utils/index.mjs';
import '../../../../hooks/index.mjs';
import { getColumnPos, getColumnKey, renderColumnTitle } from '../util.mjs';
import FilterDropdown from './FilterDropdown.mjs';
import { flattenKeys } from './utils.mjs';
import { useState } from '../../../../hooks/use-state/index.mjs';
import { devWarning } from '../../../../utils/log.mjs';

function collectFilterStates(columns, init, pos) {
  let filterStates = [];
  (columns || []).forEach((column, index) => {
    var _a, _b;
    const columnPos = getColumnPos(index, pos);
    const hasFilterDropdown = column.filterDropdown || ((_a = column == null ? void 0 : column.slots) == null ? void 0 : _a.filterDropdown) || column.customFilterDropdown;
    if (column.filters || hasFilterDropdown || "onFilter" in column) {
      if ("filteredValue" in column) {
        let filteredValues = column.filteredValue;
        if (!hasFilterDropdown)
          filteredValues = (_b = filteredValues == null ? void 0 : filteredValues.map(String)) != null ? _b : filteredValues;
        filterStates.push({
          column,
          key: getColumnKey(column, columnPos),
          filteredKeys: filteredValues,
          forceFiltered: column.filtered
        });
      } else {
        filterStates.push({
          column,
          key: getColumnKey(column, columnPos),
          filteredKeys: init && column.defaultFilteredValue ? column.defaultFilteredValue : void 0,
          forceFiltered: column.filtered
        });
      }
    }
    if ("children" in column)
      filterStates = [...filterStates, ...collectFilterStates(column.children, init, columnPos)];
  });
  return filterStates;
}
function injectFilter(prefixCls, dropdownPrefixCls, columns, filterStates, locale, triggerFilter, getPopupContainer, pos) {
  return columns.map((column, index) => {
    var _a;
    const columnPos = getColumnPos(index, pos);
    const {
      filterMultiple = true,
      filterMode,
      filterSearch
    } = column;
    let newColumn = column;
    const hasFilterDropdown = column.filterDropdown || ((_a = column == null ? void 0 : column.slots) == null ? void 0 : _a.filterDropdown) || column.customFilterDropdown;
    if (newColumn.filters || hasFilterDropdown) {
      const columnKey = getColumnKey(newColumn, columnPos);
      const filterState = filterStates.find(({
        key
      }) => columnKey === key);
      newColumn = {
        ...newColumn,
        title: (renderProps) => createVNode(FilterDropdown, {
          "tablePrefixCls": prefixCls,
          "prefixCls": `${prefixCls}-filter`,
          "dropdownPrefixCls": dropdownPrefixCls,
          "column": newColumn,
          "columnKey": columnKey,
          "filterState": filterState,
          "filterMultiple": filterMultiple,
          "filterMode": filterMode,
          "filterSearch": filterSearch,
          "triggerFilter": triggerFilter,
          "locale": locale,
          "getPopupContainer": getPopupContainer
        }, {
          default: () => [renderColumnTitle(column.title, renderProps)]
        })
      };
    }
    if ("children" in newColumn) {
      newColumn = {
        ...newColumn,
        children: injectFilter(prefixCls, dropdownPrefixCls, newColumn.children, filterStates, locale, triggerFilter, getPopupContainer, columnPos)
      };
    }
    return newColumn;
  });
}
function generateFilterInfo(filterStates) {
  const currentFilters = {};
  filterStates.forEach(({
    key,
    filteredKeys,
    column
  }) => {
    var _a;
    const hasFilterDropdown = column.filterDropdown || ((_a = column == null ? void 0 : column.slots) == null ? void 0 : _a.filterDropdown) || column.customFilterDropdown;
    const {
      filters
    } = column;
    if (hasFilterDropdown) {
      currentFilters[key] = filteredKeys || null;
    } else if (Array.isArray(filteredKeys)) {
      const keys = flattenKeys(filters);
      currentFilters[key] = keys.filter((originKey) => filteredKeys.includes(String(originKey)));
    } else {
      currentFilters[key] = null;
    }
  });
  return currentFilters;
}
function getFilterData(data, filterStates) {
  return filterStates.reduce((currentData, filterState) => {
    const {
      column: {
        onFilter,
        filters
      },
      filteredKeys
    } = filterState;
    if (onFilter && filteredKeys && filteredKeys.length) {
      return currentData.filter((record) => filteredKeys.some((key) => {
        const keys = flattenKeys(filters);
        const keyIndex = keys.findIndex((k) => String(k) === String(key));
        const realKey = keyIndex !== -1 ? keys[keyIndex] : key;
        return onFilter(realKey, record);
      }));
    }
    return currentData;
  }, data);
}
function useFilter({
  prefixCls,
  dropdownPrefixCls,
  mergedColumns,
  locale,
  onFilterChange,
  getPopupContainer
}) {
  const [filterStates, setFilterStates] = useState(collectFilterStates(mergedColumns.value, true));
  const mergedFilterStates = computed(() => {
    const collectedStates = collectFilterStates(mergedColumns.value, false);
    if (collectedStates.length === 0)
      return collectedStates;
    let filteredKeysIsAllNotControlled = true;
    let filteredKeysIsAllControlled = true;
    collectedStates.forEach(({
      filteredKeys
    }) => {
      if (filteredKeys !== void 0)
        filteredKeysIsAllNotControlled = false;
      else
        filteredKeysIsAllControlled = false;
    });
    if (filteredKeysIsAllNotControlled) {
      const keyList = (mergedColumns.value || []).map((column, index) => getColumnKey(column, getColumnPos(index)));
      return filterStates.value.filter(({
        key
      }) => keyList.includes(key)).map((item) => {
        const col = mergedColumns.value[keyList.findIndex((key) => key === item.key)];
        return {
          ...item,
          column: {
            ...item.column,
            ...col
          },
          forceFiltered: col.filtered
        };
      });
    }
    devWarning(filteredKeysIsAllControlled, "Table", "Columns should all contain `filteredValue` or not contain `filteredValue`.");
    return collectedStates;
  });
  const filters = computed(() => generateFilterInfo(mergedFilterStates.value));
  const triggerFilter = (filterState) => {
    const newFilterStates = mergedFilterStates.value.filter(({
      key
    }) => key !== filterState.key);
    newFilterStates.push(filterState);
    setFilterStates(newFilterStates);
    onFilterChange(generateFilterInfo(newFilterStates), newFilterStates);
  };
  const transformColumns = (innerColumns) => {
    return injectFilter(prefixCls.value, dropdownPrefixCls.value, innerColumns, mergedFilterStates.value, locale.value, triggerFilter, getPopupContainer.value);
  };
  return [transformColumns, mergedFilterStates, filters];
}

export { useFilter as default, getFilterData };
//# sourceMappingURL=useFilter.mjs.map
