import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import { resolveDirective as _resolveDirective, Fragment as _Fragment, createVNode as _createVNode } from "vue";
import isEqual from 'lodash-es/isEqual';
import FilterFilled from '@ant-design/icons-vue/FilterFilled';
import Button from '../../../button';
import Menu from '../../../menu';
import Checkbox from '../../../checkbox';
import Radio from '../../../radio';
import Dropdown from '../../../dropdown';
import Empty from '../../../empty';
import FilterDropdownMenuWrapper from './FilterWrapper';
import { computed, defineComponent, onBeforeUnmount, ref, watch } from 'vue';
import classNames from '../../../_util/classNames';
import useConfigInject from '../../../_util/hooks/useConfigInject';
import { useInjectSlots } from '../../context';
var SubMenu = Menu.SubMenu,
    MenuItem = Menu.Item;

function hasSubMenu(filters) {
  return filters.some(function (_ref) {
    var children = _ref.children;
    return children && children.length > 0;
  });
}

function renderFilterItems(_ref2) {
  var filters = _ref2.filters,
      prefixCls = _ref2.prefixCls,
      filteredKeys = _ref2.filteredKeys,
      filterMultiple = _ref2.filterMultiple,
      locale = _ref2.locale;

  if (filters.length === 0) {
    // wrapped with <div /> to avoid react warning
    // https://github.com/ant-design/ant-design/issues/25979
    return _createVNode(MenuItem, {
      "key": "empty"
    }, {
      default: function _default() {
        return [_createVNode("div", {
          "style": {
            margin: '16px 0'
          }
        }, [_createVNode(Empty, {
          "image": Empty.PRESENTED_IMAGE_SIMPLE,
          "description": locale.filterEmptyText,
          "imageStyle": {
            height: 24
          }
        }, null)])];
      }
    });
  }

  return filters.map(function (filter, index) {
    var key = String(filter.value);

    if (filter.children) {
      return _createVNode(SubMenu, {
        "key": key || index,
        "title": filter.text,
        "popupClassName": "".concat(prefixCls, "-dropdown-submenu")
      }, {
        default: function _default() {
          return [renderFilterItems({
            filters: filter.children,
            prefixCls: prefixCls,
            filteredKeys: filteredKeys,
            filterMultiple: filterMultiple,
            locale: locale
          })];
        }
      });
    }

    var Component = filterMultiple ? Checkbox : Radio;
    return _createVNode(MenuItem, {
      "key": filter.value !== undefined ? key : index
    }, {
      default: function _default() {
        return [_createVNode(Component, {
          "checked": filteredKeys.includes(key)
        }, null), _createVNode("span", null, [filter.text])];
      }
    });
  });
}

export default defineComponent({
  name: 'FilterDropdown',
  props: ['tablePrefixCls', 'prefixCls', 'dropdownPrefixCls', 'column', 'filterState', 'filterMultiple', 'columnKey', 'triggerFilter', 'locale', 'getPopupContainer'],
  setup: function setup(props, _ref3) {
    var slots = _ref3.slots;
    var contextSlots = useInjectSlots();
    var filterDropdownVisible = computed(function () {
      return props.column.filterDropdownVisible;
    });
    var visible = ref(false);
    var filtered = computed(function () {
      var _props$filterState$fi;

      return !!(props.filterState && ((_props$filterState$fi = props.filterState.filteredKeys) !== null && _props$filterState$fi !== void 0 && _props$filterState$fi.length || props.filterState.forceFiltered));
    });
    var filterDropdownRef = computed(function () {
      var _props$column = props.column,
          filterDropdown = _props$column.filterDropdown,
          _props$column$slots = _props$column.slots,
          slots = _props$column$slots === void 0 ? {} : _props$column$slots,
          customFilterDropdown = _props$column.customFilterDropdown;
      return filterDropdown || slots.filterDropdown && contextSlots.value[slots.filterDropdown] || customFilterDropdown && contextSlots.value.customFilterDropdown;
    });
    var filterIconRef = computed(function () {
      var _props$column2 = props.column,
          filterIcon = _props$column2.filterIcon,
          _props$column2$slots = _props$column2.slots,
          slots = _props$column2$slots === void 0 ? {} : _props$column2$slots;
      return filterIcon || slots.filterIcon && contextSlots.value[slots.filterIcon] || contextSlots.value.customFilterIcon;
    });

    var triggerVisible = function triggerVisible(newVisible) {
      var _props$column$onFilte, _props$column3;

      visible.value = newVisible;
      (_props$column$onFilte = (_props$column3 = props.column).onFilterDropdownVisibleChange) === null || _props$column$onFilte === void 0 ? void 0 : _props$column$onFilte.call(_props$column3, newVisible);
    };

    var mergedVisible = computed(function () {
      return typeof filterDropdownVisible.value === 'boolean' ? filterDropdownVisible.value : visible.value;
    });
    var propFilteredKeys = computed(function () {
      var _props$filterState;

      return (_props$filterState = props.filterState) === null || _props$filterState === void 0 ? void 0 : _props$filterState.filteredKeys;
    });
    var filteredKeys = ref([]);

    var onSelectKeys = function onSelectKeys(_ref4) {
      var selectedKeys = _ref4.selectedKeys;
      filteredKeys.value = selectedKeys;
    };

    watch(propFilteredKeys, function () {
      onSelectKeys({
        selectedKeys: propFilteredKeys.value || []
      });
    }, {
      immediate: true
    });
    var openKeys = ref([]);
    var openRef = ref();

    var onOpenChange = function onOpenChange(keys) {
      openRef.value = window.setTimeout(function () {
        openKeys.value = keys;
      });
    };

    var onMenuClick = function onMenuClick() {
      window.clearTimeout(openRef.value);
    };

    onBeforeUnmount(function () {
      window.clearTimeout(openRef.value);
    }); // ======================= Submit ========================

    var internalTriggerFilter = function internalTriggerFilter(keys) {
      var column = props.column,
          columnKey = props.columnKey,
          filterState = props.filterState;
      var mergedKeys = keys && keys.length ? keys : null;

      if (mergedKeys === null && (!filterState || !filterState.filteredKeys)) {
        return null;
      }

      if (isEqual(mergedKeys, filterState === null || filterState === void 0 ? void 0 : filterState.filteredKeys)) {
        return null;
      }

      props.triggerFilter({
        column: column,
        key: columnKey,
        filteredKeys: mergedKeys
      });
    };

    var onConfirm = function onConfirm() {
      triggerVisible(false);
      internalTriggerFilter(filteredKeys.value);
    };

    var onReset = function onReset() {
      filteredKeys.value = [];
      triggerVisible(false);
      internalTriggerFilter([]);
    };

    var doFilter = function doFilter() {
      var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
        closeDropdown: true
      },
          closeDropdown = _ref5.closeDropdown;

      if (closeDropdown) {
        triggerVisible(false);
      }

      internalTriggerFilter(filteredKeys.value);
    };

    var onVisibleChange = function onVisibleChange(newVisible) {
      if (newVisible && propFilteredKeys.value !== undefined) {
        // Sync filteredKeys on appear in controlled mode (propFilteredKeys.value !== undefiend)
        filteredKeys.value = propFilteredKeys.value || [];
      }

      triggerVisible(newVisible); // Default will filter when closed

      if (!newVisible && !filterDropdownRef.value) {
        onConfirm();
      }
    };

    var _useConfigInject = useConfigInject('', props),
        direction = _useConfigInject.direction;

    return function () {
      var _slots$default;

      var tablePrefixCls = props.tablePrefixCls,
          prefixCls = props.prefixCls,
          column = props.column,
          dropdownPrefixCls = props.dropdownPrefixCls,
          filterMultiple = props.filterMultiple,
          locale = props.locale,
          getPopupContainer = props.getPopupContainer; // ======================== Style ========================

      var dropdownMenuClass = classNames(_defineProperty({}, "".concat(dropdownPrefixCls, "-menu-without-submenu"), !hasSubMenu(column.filters || [])));
      var dropdownContent;

      if (typeof filterDropdownRef.value === 'function') {
        dropdownContent = filterDropdownRef.value({
          prefixCls: "".concat(dropdownPrefixCls, "-custom"),
          setSelectedKeys: function setSelectedKeys(selectedKeys) {
            return onSelectKeys({
              selectedKeys: selectedKeys
            });
          },
          selectedKeys: filteredKeys.value,
          confirm: doFilter,
          clearFilters: onReset,
          filters: column.filters,
          visible: mergedVisible.value,
          column: column.__originColumn__
        });
      } else if (filterDropdownRef.value) {
        dropdownContent = filterDropdownRef.value;
      } else {
        var selectedKeys = filteredKeys.value;
        dropdownContent = _createVNode(_Fragment, null, [_createVNode(Menu, {
          "multiple": filterMultiple,
          "prefixCls": "".concat(dropdownPrefixCls, "-menu"),
          "class": dropdownMenuClass,
          "onClick": onMenuClick,
          "onSelect": onSelectKeys,
          "onDeselect": onSelectKeys,
          "selectedKeys": selectedKeys,
          "getPopupContainer": getPopupContainer,
          "openKeys": openKeys.value,
          "onOpenChange": onOpenChange
        }, {
          default: function _default() {
            return renderFilterItems({
              filters: column.filters || [],
              prefixCls: prefixCls,
              filteredKeys: filteredKeys.value,
              filterMultiple: filterMultiple,
              locale: locale
            });
          }
        }), _createVNode("div", {
          "class": "".concat(prefixCls, "-dropdown-btns")
        }, [_createVNode(Button, {
          "type": "link",
          "size": "small",
          "disabled": selectedKeys.length === 0,
          "onClick": onReset
        }, {
          default: function _default() {
            return [locale.filterReset];
          }
        }), _createVNode(Button, {
          "type": "primary",
          "size": "small",
          "onClick": onConfirm
        }, {
          default: function _default() {
            return [locale.filterConfirm];
          }
        })])]);
      }

      var menu = _createVNode(FilterDropdownMenuWrapper, {
        "class": "".concat(prefixCls, "-dropdown")
      }, {
        default: function _default() {
          return [dropdownContent];
        }
      });

      var filterIcon;

      if (typeof filterIconRef.value === 'function') {
        filterIcon = filterIconRef.value({
          filtered: filtered.value,
          column: column.__originColumn__
        });
      } else if (filterIconRef.value) {
        filterIcon = filterIconRef.value;
      } else {
        filterIcon = _createVNode(FilterFilled, null, null);
      }

      return _createVNode("div", {
        "class": "".concat(prefixCls, "-column")
      }, [_createVNode("span", {
        "class": "".concat(tablePrefixCls, "-column-title")
      }, [(_slots$default = slots.default) === null || _slots$default === void 0 ? void 0 : _slots$default.call(slots)]), _createVNode(Dropdown, {
        "overlay": menu,
        "trigger": ['click'],
        "visible": mergedVisible.value,
        "onVisibleChange": onVisibleChange,
        "getPopupContainer": getPopupContainer,
        "placement": direction.value === 'rtl' ? 'bottomLeft' : 'bottomRight'
      }, {
        default: function _default() {
          return [_createVNode("span", {
            "role": "button",
            "tabindex": -1,
            "class": classNames("".concat(prefixCls, "-trigger"), {
              active: filtered.value
            }),
            "onClick": function onClick(e) {
              e.stopPropagation();
            }
          }, [filterIcon])];
        }
      })]);
    };
  }
});