import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Map from "@babel/runtime-corejs3/core-js-stable/map";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _valuesInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/values";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import React from 'react';
import cx from 'classnames';
import { internals } from '../../internals';
import { isLeafNode, collectNodes } from '../../utils';
import { Filter, DEFAULT_FILTER_OPTIONS } from './filter';
import { Classes } from '../../base/styles';
var stateKey = 'filter';
export function filter() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function step(pipeline) {
    var _a, _b;
    var dataSource = pipeline.getDataSource();
    var columns = pipeline.getColumns();
    var filters = opts.filters,
      defaultFilters = opts.defaultFilters,
      onChangeFilters = opts.onChangeFilters,
      keepDataSource = opts.keepDataSource,
      mode = opts.mode,
      filterIcon = opts.filterIcon,
      stopClickEventPropagation = opts.stopClickEventPropagation,
      stopESCKeyDownEventPropagation = opts.stopESCKeyDownEventPropagation,
      hideFilterPopupHeader = opts.hideFilterPopupHeader,
      getPopupParent = opts.getPopupParent;
    var inputFilters = (_b = (_a = filters !== null && filters !== void 0 ? filters : pipeline.getStateAtKey(stateKey)) !== null && _a !== void 0 ? _a : defaultFilters) !== null && _b !== void 0 ? _b : [];
    inputFilters = mode === 'single' ? _sliceInstanceProperty(inputFilters).call(inputFilters, 0, 1) : inputFilters;
    var inputFiltersMap = new _Map(_mapInstanceProperty(inputFilters).call(inputFilters, function (filterItem) {
      return [filterItem.code, _extends({}, filterItem)];
    }));
    var localeText = pipeline.ctx.localeText;
    function processColumns(columns) {
      return _mapInstanceProperty(columns).call(columns, dfs);
      function dfs(col) {
        var _a, _b, _c, _d, _e;
        var result = _extends({}, col);
        var filterable = col.code && ((_a = col.features) === null || _a === void 0 ? void 0 : _a.filterable);
        var filterActive = !!(filterable && (inputFiltersMap === null || inputFiltersMap === void 0 ? void 0 : inputFiltersMap.get(col.code)));
        if (filterable) {
          var handleFilterChanged = function handleFilterChanged(filterItem) {
            var nextFiltersMap = new _Map(inputFiltersMap);
            var currentFilter = _extends({
              code: col.code
            }, filterItem);
            if (filterItem == null) {
              nextFiltersMap.delete(col.code);
            } else {
              if (mode === 'single') {
                nextFiltersMap.clear();
              }
              nextFiltersMap.set(col.code, currentFilter);
            }
            var nextFilters = _Array$from(_valuesInstanceProperty(nextFiltersMap).call(nextFiltersMap));
            onChangeFilters === null || onChangeFilters === void 0 ? void 0 : onChangeFilters(nextFilters, currentFilter);
            pipeline.setStateAtKey(stateKey, nextFilters);
          };
          var setFilter = function setFilter(filter, filterCondition) {
            handleFilterChanged(!filter ? undefined : {
              code: col.code,
              filter: filter,
              filterCondition: filterCondition
            });
          };
          var filterPanel = (_b = col.features) === null || _b === void 0 ? void 0 : _b.filterPanel;
          var colFilterIcon = (_d = (_c = col.features) === null || _c === void 0 ? void 0 : _c.filterIcon) !== null && _d !== void 0 ? _d : filterIcon;
          var _Filter = /*#__PURE__*/React.createElement(Filter, {
            key: "".concat(col.code, "_filter"),
            FilterPanelContent: filterPanel,
            filterIcon: colFilterIcon,
            filterModel: inputFiltersMap.get(col.code),
            setFilterModel: handleFilterChanged,
            setFilter: setFilter,
            isFilterActive: filterActive,
            className: cx(_defineProperty(_defineProperty({}, Classes.tableFilterTrigger, true), "active", filterActive)),
            stopClickEventPropagation: stopClickEventPropagation,
            stopESCKeyDownEventPropagation: stopESCKeyDownEventPropagation,
            hideFilterPopupHeader: hideFilterPopupHeader,
            getPopupParent: getPopupParent,
            localeText: localeText
          });
          if (col.renderHeader) {
            result.title = col.renderHeader(result.title, _Filter);
          } else {
            var _context, _context2;
            result.title = _concatInstanceProperty(_context = []).call(_context, _toConsumableArray(_concatInstanceProperty(_context2 = []).call(_context2, (_e = result.title) !== null && _e !== void 0 ? _e : [internals.safeRenderHeader(_extends({}, col))])), [_Filter]);
          }
          // result.headerCellProps = mergeCellProps(col.headerCellProps, {
          //   style: {
          //     paddingRight: '18px'
          //   }
          // })
        }
        if (!isLeafNode(col)) {
          var _context3;
          result.children = _mapInstanceProperty(_context3 = col.children).call(_context3, dfs);
        }
        return result;
      }
    }
    function processDataSource(dataSource) {
      var _context4, _context5;
      var filtersKeys = [];
      inputFiltersMap.forEach(function (value, key) {
        filtersKeys.push(key);
      });
      if (keepDataSource || filtersKeys.length <= 0) {
        return dataSource;
      }
      var columns = pipeline.getColumns();
      var columnsMap = new _Map(_mapInstanceProperty(_context4 = _filterInstanceProperty(_context5 = collectNodes(columns, 'leaf-only')).call(_context5, function (col) {
        var _a, _b;
        return ((_a = col.features) === null || _a === void 0 ? void 0 : _a.filterable) !== false && ((_b = col.features) === null || _b === void 0 ? void 0 : _b.filterable) != null;
      })).call(_context4, function (col) {
        return [col.code, col];
      }));
      var defaultFilterOptionsMap = new _Map(_mapInstanceProperty(DEFAULT_FILTER_OPTIONS).call(DEFAULT_FILTER_OPTIONS, function (item) {
        return [item.key, _extends({}, item)];
      }));
      function isMatchedFilterCondition(record) {
        return filtersKeys.every(function (key) {
          var _a, _b;
          var filterItem = inputFiltersMap.get(key);
          var filterable = (_b = (_a = columnsMap.get(key)) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.filterable;
          var comparisonFn;
          if (typeof filterable === 'function') {
            comparisonFn = filterable;
          } else if (defaultFilterOptionsMap.get(filterItem.filterCondition)) {
            comparisonFn = _filterInstanceProperty(defaultFilterOptionsMap.get(filterItem.filterCondition));
          } else {
            console.warn("\u5217[".concat(key, "]\u672A\u914D\u7F6E\u7B5B\u9009\u51FD\u6570\uFF0C\u8BF7\u8BBE\u7F6E column.features.filterable \u6765\u4F5C\u4E3A\u8BE5\u5217\u7684\u7B5B\u9009\u51FD\u6570, \u76EE\u524D\u4F7F\u7528\u9ED8\u8BA4\u5305\u542B\u7B5B\u9009\u51FD\u6570"));
            comparisonFn = _filterInstanceProperty(defaultFilterOptionsMap.get('contain'));
          }
          return comparisonFn(_filterInstanceProperty(filterItem), filterItem)(internals.safeGetValue(columnsMap.get(key), record, -1), record);
        });
      }
      return layeredFilter(dataSource, isMatchedFilterCondition);
    }
    pipeline.dataSource(processDataSource(dataSource));
    pipeline.columns(processColumns(columns));
    return pipeline;
  };
}
function layeredFilter(array, matchFn) {
  return dfs(array);
  function dfs(rows) {
    var _context6;
    var parentMatched = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return _filterInstanceProperty(_context6 = _mapInstanceProperty(rows).call(rows, function (row) {
      var currentMatched = matchFn(row);
      if (isLeafNode(row)) {
        return (parentMatched || currentMatched) && _extends({}, row);
      }
      var children = row.children;
      var rowAfterFilterChildren = _extends(_extends({}, row), {
        children: dfs(children, parentMatched || currentMatched)
      });
      var matchedByChildren = !isLeafNode(rowAfterFilterChildren);
      return (parentMatched || currentMatched || matchedByChildren) && rowAfterFilterChildren;
    })).call(_context6, Boolean);
  }
}