"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.filter = filter;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));

var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));

var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));

var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/map"));

var _map2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));

var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));

var _from = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/from"));

var _values = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/values"));

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

var _react = _interopRequireDefault(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _internals = require("../../internals");

var _utils = require("../../utils");

var _filter2 = require("./filter");

var _styles = require("../../base/styles");

var stateKey = 'filter';

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,
        hideFilterPopupHeader = opts.hideFilterPopupHeader;
    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' ? (0, _slice.default)(inputFilters).call(inputFilters, 0, 1) : inputFilters;
    var inputFiltersMap = new _map.default((0, _map2.default)(inputFilters).call(inputFilters, function (filterItem) {
      return [filterItem.code, (0, _extends2.default)({}, filterItem)];
    }));

    function processColumns(columns) {
      return (0, _map2.default)(columns).call(columns, dfs);

      function dfs(col) {
        var _a, _b, _c, _d, _e, _f, _g;

        var result = (0, _extends2.default)({}, col);
        var filterable = col.code && ((_a = col.features) === null || _a === void 0 ? void 0 : _a.filterable);
        var filterActive = filterable && ((_c = (_b = inputFiltersMap === null || inputFiltersMap === void 0 ? void 0 : inputFiltersMap.get(col.code)) === null || _b === void 0 ? void 0 : (0, _filter.default)(_b)) === null || _c === void 0 ? void 0 : _c.length) > 0;

        if (filterable) {
          var _context, _context2, _cx;

          var handleFilterChanged = function handleFilterChanged(filterItem) {
            var nextFiltersMap = new _map.default(inputFiltersMap);
            var currentFilter = (0, _extends2.default)({
              code: col.code
            }, filterItem);

            if (filterItem == null) {
              nextFiltersMap.delete(col.code);
            } else {
              if (mode === 'single') {
                nextFiltersMap.clear();
              }

              nextFiltersMap.set(col.code, currentFilter);
            }

            var nextFilters = (0, _from.default)((0, _values.default)(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 = (_d = col.features) === null || _d === void 0 ? void 0 : _d.filterPanel;
          var colFilterIcon = (_f = (_e = col.features) === null || _e === void 0 ? void 0 : _e.filterIcon) !== null && _f !== void 0 ? _f : filterIcon;
          result.title = (0, _concat.default)(_context = []).call(_context, (0, _toConsumableArray2.default)((0, _concat.default)(_context2 = []).call(_context2, (_g = result.title) !== null && _g !== void 0 ? _g : [_internals.internals.safeRenderHeader((0, _extends2.default)({}, col))])), [/*#__PURE__*/_react.default.createElement(_filter2.Filter, {
            key: "filter",
            FilterPanelContent: filterPanel,
            filterIcon: colFilterIcon,
            filterModel: inputFiltersMap.get(col.code),
            setFilterModel: handleFilterChanged,
            setFilter: setFilter,
            isFilterActive: filterActive,
            className: (0, _classnames.default)((_cx = {}, (0, _defineProperty2.default)(_cx, _styles.Classes.tableFilterTrigger, true), (0, _defineProperty2.default)(_cx, "active", filterActive), _cx)),
            stopClickEventPropagation: stopClickEventPropagation,
            hideFilterPopupHeader: hideFilterPopupHeader
          })]); // result.headerCellProps = mergeCellProps(col.headerCellProps, {
          //   style: {
          //     paddingRight: '18px'
          //   }
          // })
        }

        if (!(0, _utils.isLeafNode)(col)) {
          var _context3;

          result.children = (0, _map2.default)(_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.default((0, _map2.default)(_context4 = (0, _filter.default)(_context5 = (0, _utils.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.default((0, _map2.default)(_filter2.DEFAULT_FILTER_OPTIONS).call(_filter2.DEFAULT_FILTER_OPTIONS, function (item) {
        return [item.key, (0, _extends2.default)({}, 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 = (0, _filter.default)(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 = (0, _filter.default)(defaultFilterOptionsMap.get('contain'));
          }

          return comparisonFn((0, _filter.default)(filterItem), filterItem)(_internals.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 (0, _filter.default)(_context6 = (0, _map2.default)(rows).call(rows, function (row) {
      var currentMatched = matchFn(row);

      if ((0, _utils.isLeafNode)(row)) {
        return (parentMatched || currentMatched) && (0, _extends2.default)({}, row);
      }

      var children = row.children;
      var rowAfterFilterChildren = (0, _extends2.default)((0, _extends2.default)({}, row), {
        children: dfs(children, parentMatched || currentMatched)
      });
      var matchedByChildren = !(0, _utils.isLeafNode)(rowAfterFilterChildren);
      return (parentMatched || currentMatched || matchedByChildren) && rowAfterFilterChildren;
    })).call(_context6, Boolean);
  }
}