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 _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _findIndexInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find-index";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import cx from 'classnames';
import React from 'react';
import { ExpansionCell, icons, InlineFlexCell } from '../../common-views';
import { internals } from '../../internals';
import { collectNodes, mergeCellProps } from '../../utils';
import { always, flatMap } from '../../utils/others';
import console from '../../utils/console';
import getTableRenderTemplate from '../../base/renderTemplates';
import { Classes } from '../../base';

var rowDetailSymbol = _Symbol('row-detail');

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

export 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.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 : always(true);
    var openKeys = (_h = (_g = (_f = opts.openKeys) !== null && _f !== void 0 ? _f : pipeline.getStateAtKey(stateKey)) !== null && _g !== void 0 ? _g : opts.defaultOpenAll ? _mapInstanceProperty(_context = _filterInstanceProperty(_context2 = pipeline.getDataSource()).call(_context2, hasDetail)).call(_context, function (row, rowIndex) {
      return 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(openKeys);

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

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

        onChangeOpenKeys(_concatInstanceProperty(_context3 = []).call(_context3, _toConsumableArray(openKeys), [rowKey]), rowKey, 'expand');
      }
    };

    var detailPrimaryKey = typeof primaryKey === 'string' ? primaryKey : rowDetailMetaKey.toString() + 'PrimaryKey';
    return pipeline.dataSource(flatMap(pipeline.getDataSource(), function (row, rowIndex) {
      if (openKeySet.has(internals.safeGetRowKey(primaryKey, row, rowIndex))) {
        return [row, _extends(_extends(_defineProperty({}, rowDetailMetaKey, true), row), _defineProperty({}, 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 = _findIndexInstanceProperty(columns).call(columns, function (col) {
          return col.code === opts.expandColumnCode;
        });

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

      var expandCol = columns[expandColumnIndex];

      var tableColumns = _toConsumableArray(columns);

      var render = function render(value, row, rowIndex) {
        if (row[rowDetailMetaKey]) {
          // 第一列内容已经渲染
          if (expandColumnIndex !== 0) return;
          var renderRowDetail = getTableRenderTemplate('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.safeRender(expandCol, row, rowIndex);

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

        var rowKey = 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 ? Classes.expanded : Classes.collapsed;
        var ExpandIcon = opts.expandIcon;
        return /*#__PURE__*/React.createElement(ExpansionCell, {
          className: cx('expansion-cell', expandCls),
          style: {
            cursor: clickArea === 'content' ? 'pointer' : undefined
          },
          onClick: clickArea === 'content' ? onClick : undefined
        }, opts.expandIcon ? /*#__PURE__*/React.createElement(ExpandIcon, {
          expanded: expanded,
          onClick: clickArea === 'icon' ? onClick : undefined
        }) : /*#__PURE__*/React.createElement(icons.CaretRight, {
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indents.iconIndent,
            marginRight: indents.iconGap
          },
          className: cx('expansion-icon', expandCls),
          onClick: clickArea === 'icon' ? onClick : undefined
        }), content);
      };

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

        if (row[rowDetailMetaKey]) {
          return {
            style: _extends({
              '--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 mergeCellProps(prevProps, {
          onClick: function onClick(e) {
            if (opts.stopClickEventPropagation) {
              e.stopPropagation();
            }

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

      var _tableColumns = _toArray(tableColumns),
          firstCol = _tableColumns[0],
          others = _sliceInstanceProperty(_tableColumns).call(_tableColumns, 1);

      var firstColRender = function firstColRender(value, row, rowIndex) {
        if (row[rowDetailMetaKey]) {
          var renderRowDetail = getTableRenderTemplate('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.safeRender(firstCol, row, rowIndex);
        return content;
      };

      tableColumns[0] = _extends(_extends({}, firstCol), {
        render: firstColRender,
        getSpanRect: function getSpanRect(value, row, rowIndex) {
          if (row[rowDetailMetaKey]) {
            // detail 总是成一行
            return {
              top: rowIndex,
              bottom: rowIndex + 1,
              left: 0,
              right: collectNodes(pipeline.getColumns(), 'leaf-only').length
            };
          }
        }
      });
      tableColumns[expandColumnIndex] = _extends(_extends({}, expandCol), {
        title: /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'inline-block',
            marginLeft: textOffset
          }
        }, 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: collectNodes(pipeline.getColumns(), 'leaf-only').length
            };
          }
        }
      });
      return tableColumns;
    }
  };
}