import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
import _toArray from "@babel/runtime-corejs3/helpers/toArray";
import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import cx from 'classnames';
import React from 'react';
import { ExpansionCell, icons, InlineFlexCell } from '../../common-views';
import { internals } from '../../internals';
import { collectNodes, isLeafNode, mergeCellProps } from '../../utils';
import { flatMap } from '../../utils/others';
import { Classes } from '../../base';
var groupingMetaSymbol = _Symbol('row-grouping-meta');
function attachGroupingMeta(row) {
  return _extends(_defineProperty({}, groupingMetaSymbol, {
    expandable: !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'
    };
  }
}
export 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 ? _mapInstanceProperty(_context = pipeline.getDataSource()).call(_context, function (row) {
      return row[primaryKey];
    }) : opts.defaultOpenKeys) !== null && _c !== void 0 ? _c : [];
    var openKeySet = new _Set(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 flatMap(input, function (row) {
        var result = [attachGroupingMeta(row)];
        var expanded = openKeySet.has(row[primaryKey]);
        if (expanded) {
          if (Array.isArray(row.children)) {
            result = _concatInstanceProperty(result).call(result, row.children);
          }
        }
        return result;
      });
    }
    function processColumns(columns) {
      var _context3;
      if (columns.length === 0) {
        return columns;
      }
      var columnFlatCount = collectNodes(columns, 'leaf-only').length;
      var _columns = _toArray(columns),
        firstCol = _columns[0],
        others = _sliceInstanceProperty(_columns).call(_columns, 1);
      var render = function render(value, row, rowIndex) {
        var _a, _b;
        var content = 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.createElement(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 ? Classes.expanded : Classes.collapsed;
        return /*#__PURE__*/React.createElement(ExpansionCell, {
          className: cx('expansion-cell', expandCls)
        }, /*#__PURE__*/React.createElement(icons.CaretRight, {
          className: cx('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(_filterInstanceProperty(openKeys).call(openKeys, function (key) {
                return key !== rowKey;
              }), rowKey, 'collapse');
            } else {
              var _context2;
              onChangeOpenKeys(_concatInstanceProperty(_context2 = []).call(_context2, _toConsumableArray(openKeys), [rowKey]), rowKey, 'expand');
            }
          };
        }
        var prevProps = (_a = firstCol.getCellProps) === null || _a === void 0 ? void 0 : _a.call(firstCol, value, row, rowIndex);
        return mergeCellProps(prevProps, {
          onClick: onClick,
          style: {
            cursor: expandable ? 'pointer' : undefined
          }
        });
      };
      return _concatInstanceProperty(_context3 = [_extends(_extends({}, firstCol), {
        title: (/*#__PURE__*/React.createElement("div", {
          style: {
            display: 'inline-block',
            marginLeft: textOffset
          }
        }, 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, _toConsumableArray(others));
    }
  };
}