"use strict";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var _commonViews = require("../../common-views");

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

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

var _others = require("../../utils/others");

var _base = require("../../base");

var groupingMetaSymbol = (0, _symbol.default)('row-grouping-meta');

function attachGroupingMeta(row) {
  return (0, _extends3.default)((0, _defineProperty2.default)({}, groupingMetaSymbol, {
    expandable: !(0, _utils.isLeafNode)(row)
  }), row);
}

function getGroupingMeta(row) {
  if (row[groupingMetaSymbol] == null) {
    return {
      isGroupHeader: false,
      expandable: false
    };
  }

  return {
    isGroupHeader: true,
    expandable: row[groupingMetaSymbol].expandable
  };
}

function rowGroupingRowPropsGetter(row) {
  if (getGroupingMeta(row).isGroupHeader) {
    return {
      className: 'alternative'
    };
  }
}

function rowGrouping() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (pipeline) {
    var _context;

    var _a, _b, _c;

    var stateKey = 'rowGrouping';
    var indents = pipeline.ctx.indents;
    var textOffset = indents.iconIndent + indents.iconWidth + indents.iconGap;
    var primaryKey = pipeline.ensurePrimaryKey('rowGrouping');

    if (typeof primaryKey !== 'string') {
      throw new Error('rowGrouping 仅支持字符串作为 primaryKey');
    }

    var openKeys = (_c = (_b = (_a = opts.openKeys) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : opts.defaultOpenAll ? (0, _map.default)(_context = pipeline.getDataSource()).call(_context, function (row) {
      return row[primaryKey];
    }) : opts.defaultOpenKeys) !== null && _c !== void 0 ? _c : [];
    var openKeySet = new _set.default(openKeys);

    var onChangeOpenKeys = function onChangeOpenKeys(nextKeys, key, action) {
      var _a;

      (_a = opts.onChangeOpenKeys) === null || _a === void 0 ? void 0 : _a.call(opts, nextKeys, key, action);
      pipeline.setStateAtKey(stateKey, nextKeys, {
        key: key,
        action: action
      });
    };

    return pipeline.mapDataSource(processDataSource).mapColumns(processColumns).appendRowPropsGetter(rowGroupingRowPropsGetter);

    function processDataSource(input) {
      return (0, _flatMapInstanceProperty(_others))(input, function (row) {
        var result = [attachGroupingMeta(row)];
        var expanded = openKeySet.has(row[primaryKey]);

        if (expanded) {
          if (Array.isArray(row.children)) {
            result = (0, _concat.default)(result).call(result, row.children);
          }
        }

        return result;
      });
    }

    function processColumns(columns) {
      var _context3;

      if (columns.length === 0) {
        return columns;
      }

      var columnFlatCount = (0, _utils.collectNodes)(columns, 'leaf-only').length;

      var _columns = (0, _toArray2.default)(columns),
          firstCol = _columns[0],
          others = (0, _slice.default)(_columns).call(_columns, 1);

      var render = function render(value, row, rowIndex) {
        var _a, _b;

        var content = _internals.internals.safeRender(firstCol, row, rowIndex);

        var meta = getGroupingMeta(row);

        if (!meta.isGroupHeader || !meta.expandable) {
          var marginLeft = textOffset + (meta.isGroupHeader ? 0 : indents.indentSize);
          return /*#__PURE__*/_react.default.createElement(_commonViews.InlineFlexCell, {
            style: {
              marginLeft: marginLeft
            }
          }, meta.isGroupHeader ? (_a = row.groupTitle) !== null && _a !== void 0 ? _a : content : content);
        }

        var expanded = openKeySet.has(row[primaryKey]);
        var expandCls = expanded ? _base.Classes.expanded : _base.Classes.collapsed;
        return /*#__PURE__*/_react.default.createElement(_commonViews.ExpansionCell, {
          className: (0, _classnames.default)('expansion-cell', expandCls)
        }, /*#__PURE__*/_react.default.createElement(_commonViews.icons.CaretRight, {
          className: (0, _classnames.default)('expansion-icon', expandCls),
          style: {
            marginLeft: indents.iconIndent,
            marginRight: indents.iconGap
          }
        }), (_b = row.groupTitle) !== null && _b !== void 0 ? _b : content);
      };

      var getCellProps = function getCellProps(value, row, rowIndex) {
        var _a;

        var meta = getGroupingMeta(row);

        if (!meta.isGroupHeader) {
          return;
        }

        var expandable = meta.expandable;
        var rowKey = row[primaryKey];
        var expanded = openKeySet.has(rowKey);
        var onClick;

        if (expandable) {
          onClick = function onClick(e) {
            if (opts.stopClickEventPropagation) {
              e.stopPropagation();
            }

            if (expanded) {
              onChangeOpenKeys((0, _filter.default)(openKeys).call(openKeys, function (key) {
                return key !== rowKey;
              }), rowKey, 'collapse');
            } else {
              var _context2;

              onChangeOpenKeys((0, _concat.default)(_context2 = []).call(_context2, (0, _toConsumableArray2.default)(openKeys), [rowKey]), rowKey, 'expand');
            }
          };
        }

        var prevProps = (_a = firstCol.getCellProps) === null || _a === void 0 ? void 0 : _a.call(firstCol, value, row, rowIndex);
        return (0, _utils.mergeCellProps)(prevProps, {
          onClick: onClick,
          style: {
            cursor: expandable ? 'pointer' : undefined
          }
        });
      };

      return (0, _concat.default)(_context3 = [(0, _extends3.default)((0, _extends3.default)({}, firstCol), {
        title: /*#__PURE__*/_react.default.createElement("div", {
          style: {
            display: 'inline-block',
            marginLeft: textOffset
          }
        }, _internals.internals.safeRenderHeader(firstCol)),
        render: render,
        getCellProps: getCellProps,
        getSpanRect: function getSpanRect(value, row, rowIndex) {
          if (getGroupingMeta(row).isGroupHeader) {
            return {
              top: rowIndex,
              bottom: rowIndex + 1,
              left: 0,
              right: columnFlatCount
            };
          }
        }
      })]).call(_context3, (0, _toConsumableArray2.default)(others));
    }
  };
}