"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.rowDetail = rowDetail;

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

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

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

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

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

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

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

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

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

var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find-index"));

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

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 _console = _interopRequireDefault(require("../../utils/console"));

var _renderTemplates = _interopRequireDefault(require("../../base/renderTemplates"));

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

var rowDetailSymbol = (0, _symbol.default)('row-detail');

var fallbackRenderDetail = function fallbackRenderDetail() {
  return /*#__PURE__*/_react.default.createElement("div", {
    style: {
      margin: '8px 24px'
    }
  }, /*#__PURE__*/_react.default.createElement("b", {
    style: {
      color: 'indianred'
    }
  }, "\u8BBE\u7F6E ", /*#__PURE__*/_react.default.createElement("code", null, "rowDetail.renderDetail"), " \u6765\u81EA\u5B9A\u4E49\u8BE6\u60C5\u5185\u5BB9"));
};

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

    var _a, _b, _c, _d, _e, _f, _g, _h;

    var stateKey = 'rowDetail';
    var rowDetailMetaKey = (_a = opts.rowDetailMetaKey) !== null && _a !== void 0 ? _a : rowDetailSymbol;
    var primaryKey = pipeline.ensurePrimaryKey('rowDetail');
    var indents = pipeline.ctx.indents;
    var textOffset = indents.iconIndent + indents.iconWidth + indents.iconGap;
    var clickArea = (_b = opts.clickArea) !== null && _b !== void 0 ? _b : 'cell';
    var getDetailKey = (_c = opts.getDetailKey) !== null && _c !== void 0 ? _c : function (row, rowIndex) {
      return _internals.internals.safeGetRowKey(primaryKey, row, rowIndex) + '_detail';
    };
    var renderDetail = (_d = opts.renderDetail) !== null && _d !== void 0 ? _d : fallbackRenderDetail;
    var hasDetail = (_e = opts.hasDetail) !== null && _e !== void 0 ? _e : (0, _others.always)(true);
    var openKeys = (_h = (_g = (_f = opts.openKeys) !== null && _f !== void 0 ? _f : pipeline.getStateAtKey(stateKey)) !== null && _g !== void 0 ? _g : opts.defaultOpenAll ? (0, _map.default)(_context = (0, _filter.default)(_context2 = pipeline.getDataSource()).call(_context2, hasDetail)).call(_context, function (row, rowIndex) {
      return _internals.internals.safeGetRowKey(primaryKey, row, rowIndex);
    }) : opts.defaultOpenKeys) !== null && _h !== void 0 ? _h : [];

    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
      });
    };

    var openKeySet = new _set.default(openKeys);

    var toggle = function toggle(rowKey) {
      var expanded = openKeySet.has(rowKey);

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

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

    var detailPrimaryKey = typeof primaryKey === 'string' ? primaryKey : rowDetailMetaKey.toString() + 'PrimaryKey';
    return pipeline.dataSource((0, _flatMapInstanceProperty(_others))(pipeline.getDataSource(), function (row, rowIndex) {
      if (openKeySet.has(_internals.internals.safeGetRowKey(primaryKey, row, rowIndex))) {
        return [row, (0, _extends4.default)((0, _extends4.default)((0, _defineProperty2.default)({}, rowDetailMetaKey, true), row), (0, _defineProperty2.default)({}, detailPrimaryKey, getDetailKey(row, rowIndex)))];
      } else {
        return [row];
      }
    })).columns(processColumns(pipeline.getColumns())).appendRowPropsGetter(function (row) {
      if (row[rowDetailMetaKey]) {
        return {
          className: 'no-hover',
          'data-row-detail-key': row[detailPrimaryKey]
        };
      }
    });

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

      var expandColumnIndex = 0;

      if (opts.expandColumnCode) {
        expandColumnIndex = (0, _findIndex.default)(columns).call(columns, function (col) {
          return col.code === opts.expandColumnCode;
        });

        if (expandColumnIndex < 0) {
          _console.default.warn('没找到可展开的列，请检查设置的展开列code');

          return columns;
        }
      }

      var expandCol = columns[expandColumnIndex];
      var tableColumns = (0, _toConsumableArray2.default)(columns);

      var render = function render(value, row, rowIndex) {
        if (row[rowDetailMetaKey]) {
          // 第一列内容已经渲染
          if (expandColumnIndex !== 0) return;
          var renderRowDetail = (0, _renderTemplates.default)('rowDetail');

          if (typeof renderRowDetail === 'function') {
            return renderRowDetail({
              row: row,
              rowIndex: rowIndex,
              domHelper: pipeline.ref.current.domHelper,
              renderDetail: renderDetail
            });
          }

          return renderDetail(row, rowIndex);
        }

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

        if (!hasDetail(row, rowIndex)) {
          return /*#__PURE__*/_react.default.createElement(_commonViews.InlineFlexCell, {
            style: {
              marginLeft: textOffset
            }
          }, content);
        }

        var rowKey = _internals.internals.safeGetRowKey(primaryKey, row, rowIndex);

        var expanded = openKeySet.has(rowKey);

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

          toggle(rowKey);
        };

        var expandCls = expanded ? _base.Classes.expanded : _base.Classes.collapsed;
        var ExpandIcon = opts.expandIcon;
        return /*#__PURE__*/_react.default.createElement(_commonViews.ExpansionCell, {
          className: (0, _classnames.default)('expansion-cell', expandCls),
          style: {
            cursor: clickArea === 'content' ? 'pointer' : undefined
          },
          onClick: clickArea === 'content' ? onClick : undefined
        }, opts.expandIcon ? /*#__PURE__*/_react.default.createElement(ExpandIcon, {
          expanded: expanded,
          onClick: clickArea === 'icon' ? onClick : undefined
        }) : /*#__PURE__*/_react.default.createElement(_commonViews.icons.CaretRight, {
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indents.iconIndent,
            marginRight: indents.iconGap
          },
          className: (0, _classnames.default)('expansion-icon', expandCls),
          onClick: clickArea === 'icon' ? onClick : undefined
        }), content);
      };

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

        if (row[rowDetailMetaKey]) {
          return {
            style: (0, _extends4.default)({
              '--cell-padding': '0',
              overflow: 'hidden'
            }, opts.detailCellStyle)
          };
        }

        var prevProps = (_a = expandCol.getCellProps) === null || _a === void 0 ? void 0 : _a.call(expandCol, value, row, rowIndex);

        if (!hasDetail(row, rowIndex)) {
          return prevProps;
        }

        return (0, _utils.mergeCellProps)(prevProps, {
          onClick: function onClick(e) {
            if (opts.stopClickEventPropagation) {
              e.stopPropagation();
            }

            toggle(_internals.internals.safeGetRowKey(primaryKey, row, rowIndex));
          },
          style: {
            cursor: 'pointer'
          }
        });
      };

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

      var firstColRender = function firstColRender(value, row, rowIndex) {
        if (row[rowDetailMetaKey]) {
          var renderRowDetail = (0, _renderTemplates.default)('rowDetail');

          if (typeof renderRowDetail === 'function') {
            return renderRowDetail({
              row: row,
              rowIndex: rowIndex,
              domHelper: pipeline.ref.current.domHelper,
              renderDetail: renderDetail
            });
          }

          return renderDetail(row, rowIndex);
        }

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

        return content;
      };

      tableColumns[0] = (0, _extends4.default)((0, _extends4.default)({}, firstCol), {
        render: firstColRender,
        getSpanRect: function getSpanRect(value, row, rowIndex) {
          if (row[rowDetailMetaKey]) {
            // detail 总是成一行
            return {
              top: rowIndex,
              bottom: rowIndex + 1,
              left: 0,
              right: (0, _utils.collectNodes)(pipeline.getColumns(), 'leaf-only').length
            };
          }
        }
      });
      tableColumns[expandColumnIndex] = (0, _extends4.default)((0, _extends4.default)({}, expandCol), {
        title: /*#__PURE__*/_react.default.createElement("div", {
          style: {
            display: 'inline-block',
            marginLeft: textOffset
          }
        }, _internals.internals.safeRenderHeader(expandCol)),
        render: render,
        getCellProps: clickArea === 'cell' ? getCellProps : expandCol.getCellProps,
        getSpanRect: function getSpanRect(value, row, rowIndex) {
          if (row[rowDetailMetaKey]) {
            // detail 总是成一行
            return {
              top: rowIndex,
              bottom: rowIndex + 1,
              left: 0,
              right: (0, _utils.collectNodes)(pipeline.getColumns(), 'leaf-only').length
            };
          }
        }
      });
      return tableColumns;
    }
  };
}