'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
var iconsVue = require('@ant-design/icons-vue');
require('../../../../utils/index.cjs');
var context = require('../context.cjs');
var index$5 = require('../../../button/index.cjs');
var index = require('../../../menu/index.cjs');
var index$1 = require('../../../checkbox/index.cjs');
var index$2 = require('../../../radio/index.cjs');
var index$6 = require('../../../dropdown/index.cjs');
var index$3 = require('../../../empty/index.cjs');
var useConfigInject = require('../../../config-provider/src/hooks/useConfigInject.cjs');
var index$4 = require('../../../tree/index.cjs');
var FilterSearch = require('./FilterSearch.cjs');
var FilterWrapper = require('./FilterWrapper.cjs');
var utils = require('./utils.cjs');
var log = require('../../../../utils/log.cjs');
var is = require('../../../../utils/is.cjs');
var _class = require('../../../../utils/dom/class.cjs');

const {
  SubMenu,
  Item: MenuItem
} = index.Menu;
function hasSubMenu(filters) {
  return filters.some(({
    children
  }) => children && children.length > 0);
}
function searchValueMatched(searchValue, text) {
  if (typeof text === "string" || typeof text === "number")
    return text == null ? void 0 : text.toString().toLowerCase().includes(searchValue.trim().toLowerCase());
  return false;
}
function renderFilterItems({
  filters,
  prefixCls,
  filteredKeys,
  filterMultiple,
  searchValue,
  filterSearch
}) {
  return filters.map((filter, index) => {
    const key = String(filter.value);
    if (filter.children) {
      return vue.createVNode(SubMenu, {
        "key": key || index,
        "title": filter.text,
        "popupClassName": `${prefixCls}-dropdown-submenu`
      }, {
        default: () => [renderFilterItems({
          filters: filter.children,
          prefixCls,
          filteredKeys,
          filterMultiple,
          searchValue,
          filterSearch
        })]
      });
    }
    const Component = filterMultiple ? index$1.Checkbox : index$2.Radio;
    const item = vue.createVNode(MenuItem, {
      "key": filter.value !== void 0 ? key : index
    }, {
      default: () => [vue.createVNode(Component, {
        "checked": filteredKeys.includes(key)
      }, null), vue.createVNode("span", null, [filter.text])]
    });
    if (searchValue.trim()) {
      if (typeof filterSearch === "function")
        return filterSearch(searchValue, filter) ? item : void 0;
      return searchValueMatched(searchValue, filter.text) ? item : void 0;
    }
    return item;
  });
}
var FilterDropdown = /* @__PURE__ */ vue.defineComponent({
  name: "FilterDropdown",
  props: ["tablePrefixCls", "prefixCls", "dropdownPrefixCls", "column", "filterState", "filterMultiple", "filterMode", "filterSearch", "columnKey", "triggerFilter", "locale", "getPopupContainer"],
  setup(props, {
    slots
  }) {
    const contextSlots = context.useInjectSlots();
    const filterMode = vue.computed(() => {
      var _a;
      return (_a = props.filterMode) != null ? _a : "menu";
    });
    const filterSearch = vue.computed(() => {
      var _a;
      return (_a = props.filterSearch) != null ? _a : false;
    });
    const filterDropdownOpen = vue.computed(() => props.column.filterDropdownOpen || props.column.filterDropdownVisible);
    const onFilterDropdownOpenChange = vue.computed(() => props.column.onFilterDropdownOpenChange || props.column.onFilterDropdownVisibleChange);
    if (process.env.NODE_ENV !== "production") {
      [["filterDropdownVisible", "filterDropdownOpen", props.column.filterDropdownVisible], ["onFilterDropdownVisibleChange", "onFilterDropdownOpenChange", props.column.onFilterDropdownVisibleChange]].forEach(([deprecatedName, newName, prop]) => {
        log.devWarning(prop === void 0 || prop === null, "Table", `\`${deprecatedName}\` is deprecated. Please use \`${newName}\` instead.`);
      });
    }
    const visible = vue.shallowRef(false);
    const filtered = vue.computed(() => {
      var _a;
      return !!(props.filterState && (((_a = props.filterState.filteredKeys) == null ? void 0 : _a.length) || props.filterState.forceFiltered));
    });
    const filterFlattenKeys = vue.computed(() => {
      var _a;
      return utils.flattenKeys((_a = props.column) == null ? void 0 : _a.filters);
    });
    const filterDropdownRef = vue.computed(() => {
      const {
        filterDropdown,
        slots: slots2 = {},
        customFilterDropdown
      } = props.column;
      return filterDropdown || slots2.filterDropdown && contextSlots.value[slots2.filterDropdown] || customFilterDropdown && contextSlots.value.customFilterDropdown;
    });
    const filterIconRef = vue.computed(() => {
      const {
        filterIcon,
        slots: slots2 = {}
      } = props.column;
      return filterIcon || slots2.filterIcon && contextSlots.value[slots2.filterIcon] || contextSlots.value.customFilterIcon;
    });
    const triggerVisible = (newVisible) => {
      var _a;
      visible.value = newVisible;
      (_a = onFilterDropdownOpenChange.value) == null ? void 0 : _a.call(onFilterDropdownOpenChange, newVisible);
    };
    const mergedVisible = vue.computed(() => typeof filterDropdownOpen.value === "boolean" ? filterDropdownOpen.value : visible.value);
    const propFilteredKeys = vue.computed(() => {
      var _a;
      return (_a = props.filterState) == null ? void 0 : _a.filteredKeys;
    });
    const filteredKeys = vue.shallowRef([]);
    const onSelectKeys = ({
      selectedKeys
    }) => {
      filteredKeys.value = selectedKeys;
    };
    const onCheck = (keys, {
      node,
      checked
    }) => {
      if (!props.filterMultiple)
        onSelectKeys({
          selectedKeys: checked && node.key ? [node.key] : []
        });
      else
        onSelectKeys({
          selectedKeys: keys
        });
    };
    vue.watch(propFilteredKeys, () => {
      if (!visible.value)
        return;
      onSelectKeys({
        selectedKeys: propFilteredKeys.value || []
      });
    }, {
      immediate: true
    });
    const openKeys = vue.shallowRef([]);
    const openRef = vue.shallowRef();
    const onOpenChange = (keys) => {
      openRef.value = setTimeout(() => {
        openKeys.value = keys;
      });
    };
    const onMenuClick = () => {
      clearTimeout(openRef.value);
    };
    vue.onBeforeUnmount(() => {
      clearTimeout(openRef.value);
    });
    const searchValue = vue.shallowRef("");
    const onSearch = (e) => {
      const {
        value
      } = e.target;
      searchValue.value = value;
    };
    vue.watch(visible, () => {
      if (!visible.value)
        searchValue.value = "";
    });
    const internalTriggerFilter = (keys) => {
      const {
        column,
        columnKey,
        filterState
      } = props;
      const mergedKeys = keys && keys.length ? keys : null;
      if (mergedKeys === null && (!filterState || !filterState.filteredKeys))
        return null;
      if (is.isEqual(mergedKeys, filterState == null ? void 0 : filterState.filteredKeys, true))
        return null;
      props.triggerFilter({
        column,
        key: columnKey,
        filteredKeys: mergedKeys
      });
    };
    const onConfirm = () => {
      triggerVisible(false);
      internalTriggerFilter(filteredKeys.value);
    };
    const onReset = ({
      confirm,
      closeDropdown
    } = {
      confirm: false,
      closeDropdown: false
    }) => {
      if (confirm)
        internalTriggerFilter([]);
      if (closeDropdown)
        triggerVisible(false);
      searchValue.value = "";
      if (props.column.filterResetToDefaultFilteredValue)
        filteredKeys.value = (props.column.defaultFilteredValue || []).map((key) => String(key));
      else
        filteredKeys.value = [];
    };
    const doFilter = ({
      closeDropdown
    } = {
      closeDropdown: true
    }) => {
      if (closeDropdown)
        triggerVisible(false);
      internalTriggerFilter(filteredKeys.value);
    };
    const onVisibleChange = (newVisible) => {
      if (newVisible && propFilteredKeys.value !== void 0) {
        filteredKeys.value = propFilteredKeys.value || [];
      }
      triggerVisible(newVisible);
      if (!newVisible && !filterDropdownRef.value)
        onConfirm();
    };
    const {
      direction
    } = useConfigInject.default("", props);
    const onCheckAll = (e) => {
      if (e.target.checked) {
        const allFilterKeys = filterFlattenKeys.value;
        filteredKeys.value = allFilterKeys;
      } else {
        filteredKeys.value = [];
      }
    };
    const getTreeData = ({
      filters
    }) => (filters || []).map((filter, index) => {
      const key = String(filter.value);
      const item = {
        title: filter.text,
        key: filter.value !== void 0 ? key : index
      };
      if (filter.children)
        item.children = getTreeData({
          filters: filter.children
        });
      return item;
    });
    const getFilterData = (node) => {
      var _a;
      return {
        ...node,
        text: node.title,
        value: node.key,
        children: ((_a = node.children) == null ? void 0 : _a.map((item) => getFilterData(item))) || []
      };
    };
    const treeData = vue.computed(() => getTreeData({
      filters: props.column.filters
    }));
    const dropdownMenuClass = vue.computed(() => _class.classNames({
      [`${props.dropdownPrefixCls}-menu-without-submenu`]: !hasSubMenu(props.column.filters || [])
    }));
    const getFilterComponent = () => {
      const selectedKeys = filteredKeys.value;
      const {
        column,
        locale,
        tablePrefixCls,
        filterMultiple,
        dropdownPrefixCls,
        getPopupContainer,
        prefixCls
      } = props;
      if ((column.filters || []).length === 0) {
        return vue.createVNode(index$3.Empty, {
          "image": index$3.Empty.PRESENTED_IMAGE_SIMPLE,
          "description": locale.filterEmptyText,
          "imageStyle": {
            height: 24
          },
          "style": {
            margin: 0,
            padding: "16px 0"
          }
        }, null);
      }
      if (filterMode.value === "tree") {
        return vue.createVNode(vue.Fragment, null, [vue.createVNode(FilterSearch.default, {
          "filterSearch": filterSearch.value,
          "value": searchValue.value,
          "onChange": onSearch,
          "tablePrefixCls": tablePrefixCls,
          "locale": locale
        }, null), vue.createVNode("div", {
          "class": `${tablePrefixCls}-filter-dropdown-tree`
        }, [filterMultiple ? vue.createVNode(index$1.Checkbox, {
          "class": `${tablePrefixCls}-filter-dropdown-checkall`,
          "onChange": onCheckAll,
          "checked": selectedKeys.length === filterFlattenKeys.value.length,
          "indeterminate": selectedKeys.length > 0 && selectedKeys.length < filterFlattenKeys.value.length
        }, {
          default: () => [locale.filterCheckAll]
        }) : null, vue.createVNode(index$4.Tree, {
          "checkable": true,
          "selectable": false,
          "blockNode": true,
          "multiple": filterMultiple,
          "checkStrictly": !filterMultiple,
          "class": `${dropdownPrefixCls}-menu`,
          "onCheck": onCheck,
          "checkedKeys": selectedKeys,
          "selectedKeys": selectedKeys,
          "showIcon": false,
          "treeData": treeData.value,
          "autoExpandParent": true,
          "defaultExpandAll": true,
          "filterTreeNode": searchValue.value.trim() ? (node) => {
            if (typeof filterSearch.value === "function")
              return filterSearch.value(searchValue.value, getFilterData(node));
            return searchValueMatched(searchValue.value, node.title);
          } : void 0
        }, null)])]);
      }
      return vue.createVNode(vue.Fragment, null, [vue.createVNode(FilterSearch.default, {
        "filterSearch": filterSearch.value,
        "value": searchValue.value,
        "onChange": onSearch,
        "tablePrefixCls": tablePrefixCls,
        "locale": locale
      }, null), vue.createVNode(index.Menu, {
        "multiple": filterMultiple,
        "prefixCls": `${dropdownPrefixCls}-menu`,
        "class": dropdownMenuClass.value,
        "onClick": onMenuClick,
        "onSelect": onSelectKeys,
        "onDeselect": onSelectKeys,
        "selectedKeys": selectedKeys,
        "getPopupContainer": getPopupContainer,
        "openKeys": openKeys.value,
        "onOpenChange": onOpenChange
      }, {
        default: () => renderFilterItems({
          filters: column.filters || [],
          filterSearch: filterSearch.value,
          prefixCls,
          filteredKeys: filteredKeys.value,
          filterMultiple,
          searchValue: searchValue.value
        })
      })]);
    };
    const resetDisabled = vue.computed(() => {
      const selectedKeys = filteredKeys.value;
      if (props.column.filterResetToDefaultFilteredValue) {
        return is.isEqual((props.column.defaultFilteredValue || []).map((key) => String(key)), selectedKeys, true);
      }
      return selectedKeys.length === 0;
    });
    return () => {
      var _a;
      const {
        tablePrefixCls,
        prefixCls,
        column,
        dropdownPrefixCls,
        locale,
        getPopupContainer
      } = props;
      let dropdownContent;
      if (typeof filterDropdownRef.value === "function") {
        dropdownContent = filterDropdownRef.value({
          prefixCls: `${dropdownPrefixCls}-custom`,
          setSelectedKeys: (selectedKeys) => onSelectKeys({
            selectedKeys
          }),
          selectedKeys: filteredKeys.value,
          confirm: doFilter,
          clearFilters: onReset,
          filters: column.filters,
          visible: mergedVisible.value,
          column: column.__originColumn__,
          close: () => {
            triggerVisible(false);
          }
        });
      } else if (filterDropdownRef.value) {
        dropdownContent = filterDropdownRef.value;
      } else {
        dropdownContent = vue.createVNode(vue.Fragment, null, [getFilterComponent(), vue.createVNode("div", {
          "class": `${prefixCls}-dropdown-btns`
        }, [vue.createVNode(index$5.Button, {
          "type": "link",
          "size": "small",
          "disabled": resetDisabled.value,
          "onClick": () => onReset()
        }, {
          default: () => [locale.filterReset]
        }), vue.createVNode(index$5.Button, {
          "type": "primary",
          "size": "small",
          "onClick": onConfirm
        }, {
          default: () => [locale.filterConfirm]
        })])]);
      }
      const menu = vue.createVNode(FilterWrapper.default, {
        "class": `${prefixCls}-dropdown`
      }, {
        default: () => [dropdownContent]
      });
      let filterIcon;
      if (typeof filterIconRef.value === "function") {
        filterIcon = filterIconRef.value({
          filtered: filtered.value,
          column: column.__originColumn__
        });
      } else if (filterIconRef.value) {
        filterIcon = filterIconRef.value;
      } else {
        filterIcon = vue.createVNode(iconsVue.FilterFilled, null, null);
      }
      return vue.createVNode("div", {
        "class": `${prefixCls}-column`
      }, [vue.createVNode("span", {
        "class": `${tablePrefixCls}-column-title`
      }, [(_a = slots.default) == null ? void 0 : _a.call(slots)]), vue.createVNode(index$6.Dropdown, {
        "overlay": menu,
        "trigger": ["click"],
        "open": mergedVisible.value,
        "onOpenChange": onVisibleChange,
        "getPopupContainer": getPopupContainer,
        "placement": direction.value === "rtl" ? "bottomLeft" : "bottomRight"
      }, {
        default: () => [vue.createVNode("span", {
          "role": "button",
          "tabindex": -1,
          "class": _class.classNames(`${prefixCls}-trigger`, {
            active: filtered.value
          }),
          "onClick": (e) => {
            e.stopPropagation();
          }
        }, [filterIcon])]
      })]);
    };
  }
});

exports.default = FilterDropdown;
//# sourceMappingURL=FilterDropdown.cjs.map
