import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context3; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context3 = {}.toString.call(r)).call(_context3, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _findIndexInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find-index";
import cx from 'classnames';
import React from 'react';
import { ExpansionCell, icons, InlineFlexCell } from '../../common-views';
import { internals } from '../../internals';
import { isLeafNode as standardIsLeafNode, mergeCellProps } from '../../utils';
import { Classes } from '../../base/styles';
export var treeMetaSymbol = _Symbol('treeMetaSymbol');
export var treeModeOptionsKey = 'treeModeOptions';
export function treeMode() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function treeModeStep(pipeline) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    var stateKey = 'treeMode';
    var ctx = pipeline.ctx;
    var primaryKey = pipeline.ensurePrimaryKey('treeMode');
    var openKeys = (_c = (_b = (_a = opts.openKeys) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : opts.defaultOpenKeys) !== null && _c !== void 0 ? _c : [];
    var curSort = pipeline.getStateAtKey('sort');
    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
      });
    };
    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 _context;
        onChangeOpenKeys(_concatInstanceProperty(_context = []).call(_context, _toConsumableArray(openKeys), [rowKey]), rowKey, 'expand');
      }
    };
    var isLeafNode = (_d = opts.isLeafNode) !== null && _d !== void 0 ? _d : standardIsLeafNode;
    var clickArea = (_e = opts.clickArea) !== null && _e !== void 0 ? _e : 'cell';
    var treeMetaKey = (_f = opts.treeMetaKey) !== null && _f !== void 0 ? _f : treeMetaSymbol;
    var stopClickEventPropagation = Boolean(opts.stopClickEventPropagation);
    // indents
    var iconWidth = ctx.indents.iconWidth;
    var iconIndent = (_g = opts.iconIndent) !== null && _g !== void 0 ? _g : ctx.indents.iconIndent;
    var iconGap = (_h = opts.iconGap) !== null && _h !== void 0 ? _h : ctx.indents.iconGap;
    var indentSize = (_j = opts.indentSize) !== null && _j !== void 0 ? _j : ctx.indents.indentSize;
    pipeline.setFeatureOptions(treeModeOptionsKey, {
      iconWidth: iconWidth,
      iconIndent: iconIndent,
      iconGap: iconGap,
      indentSize: indentSize,
      treeMetaKey: treeMetaKey,
      isExpanded: function isExpanded(rowKey) {
        return openKeySet.has(rowKey);
      },
      onExpand: function onExpand(rowKey) {
        var _context2;
        onChangeOpenKeys(_concatInstanceProperty(_context2 = []).call(_context2, _toConsumableArray(openKeys), [rowKey]), rowKey, 'expand');
      },
      onCollapse: function onCollapse(rowKey) {
        onChangeOpenKeys(_filterInstanceProperty(openKeys).call(openKeys, function (key) {
          return key !== rowKey;
        }), rowKey, 'collapse');
      }
    });
    var Icon = opts.icon;
    return pipeline.mapDataSource(processDataSource).mapColumns(processColumns);
    function processDataSource(input) {
      if (pipeline.isSameInputDataSource() && openKeys === pipeline.getFeatureOptions('lastOpenKeys') && curSort === pipeline.getFeatureOptions('lastSort')) {
        return pipeline.getFeatureOptions('lastTreeMode');
      }
      pipeline.setFeatureOptions('lastOpenKeys', openKeys);
      pipeline.setFeatureOptions('lastSort', curSort);
      var result = [];
      dfs(input, 0);
      function dfs(nodes, depth) {
        var parentNode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        if (nodes == null) {
          return;
        }
        var _iterator = _createForOfIteratorHelper(nodes),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var node = _step.value;
            var rowKey = internals.safeGetRowKey(primaryKey, node, -1);
            var parentRowKey = parentNode ? internals.safeGetRowKey(primaryKey, parentNode, -1) : null;
            var expanded = openKeySet.has(rowKey);
            var isLeaf = isLeafNode(node, {
              depth: depth,
              expanded: expanded,
              rowKey: rowKey
            });
            var treeMeta = {
              depth: depth,
              isLeaf: isLeaf,
              expanded: expanded,
              rowKey: rowKey,
              parentRowKey: parentRowKey
            };
            result.push(_extends(_defineProperty({}, treeMetaKey, treeMeta), node));
            if (!isLeaf && expanded) {
              dfs(node.children, depth + 1, node);
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
      pipeline.setFeatureOptions('lastTreeMode', result);
      return result;
    }
    function processColumns(columns) {
      if (columns.length === 0) {
        return columns;
      }
      var expandColIndex = _findIndexInstanceProperty(columns).call(columns, function (_ref) {
        var code = _ref.code;
        return code && opts.expandColCode === code;
      });
      expandColIndex = expandColIndex === -1 ? 0 : expandColIndex;
      var expandCol = columns[expandColIndex];
      var render = function render(value, record, recordIndex) {
        var content = internals.safeRender(expandCol, record, recordIndex);
        if (record[treeMetaKey] == null) {
          // 没有 treeMeta 信息的话，就返回原先的渲染结果
          return content;
        }
        var _record$treeMetaKey = record[treeMetaKey],
          rowKey = _record$treeMetaKey.rowKey,
          depth = _record$treeMetaKey.depth,
          isLeaf = _record$treeMetaKey.isLeaf,
          expanded = _record$treeMetaKey.expanded;
        var indent = iconIndent + depth * indentSize;
        if (isLeaf) {
          return /*#__PURE__*/React.createElement(InlineFlexCell, {
            className: cx('expansion-cell', Classes.leaf)
          }, /*#__PURE__*/React.createElement("span", {
            style: {
              marginLeft: indent + iconWidth + iconGap
            }
          }, content));
        }
        var onClick = function onClick(e) {
          if (stopClickEventPropagation) {
            e.stopPropagation();
          }
          toggle(rowKey);
        };
        var expandCls = expanded ? Classes.expanded : Classes.collapsed;
        return /*#__PURE__*/React.createElement(ExpansionCell, {
          className: cx('expansion-cell', expandCls),
          style: {
            cursor: clickArea === 'content' ? 'pointer' : undefined
          },
          onClick: clickArea === 'content' ? onClick : undefined
        }, Icon ? /*#__PURE__*/React.createElement(Icon, {
          expanded: expanded,
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indent,
            marginRight: iconGap,
            width: iconWidth
          },
          onClick: clickArea === 'icon' ? onClick : undefined
        }) : /*#__PURE__*/React.createElement(icons.CaretRight, {
          className: cx('expansion-icon', expandCls),
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indent,
            marginRight: iconGap
          },
          onClick: clickArea === 'icon' ? onClick : undefined
        }), content);
      };
      var getCellProps = function getCellProps(value, record, rowIndex) {
        var prevProps = internals.safeGetCellProps(expandCol, record, rowIndex);
        if (record[treeMetaKey] == null || clickArea !== 'cell') {
          // 没有 treeMeta 信息的话，就返回原先的 cellProps
          return mergeCellProps(prevProps, {
            className: Classes.tableExtendCell
          });
        }
        var _record$treeMetaKey2 = record[treeMetaKey],
          isLeaf = _record$treeMetaKey2.isLeaf,
          rowKey = _record$treeMetaKey2.rowKey;
        if (isLeaf) {
          return mergeCellProps(prevProps, {
            className: Classes.tableExtendCell
          });
        }
        return mergeCellProps(prevProps, {
          onClick: function onClick(e) {
            if (stopClickEventPropagation) {
              e.stopPropagation();
            }
            toggle(rowKey);
          },
          style: {
            cursor: 'pointer'
          },
          className: Classes.tableExtendCell
        });
      };
      columns[expandColIndex] = _extends(_extends({}, expandCol), {
        title: (/*#__PURE__*/React.createElement("span", {
          style: {
            marginLeft: iconIndent + iconWidth + iconGap,
            display: 'flex'
          }
        }, internals.safeRenderHeader(expandCol))),
        render: render,
        getCellProps: getCellProps
      });
      return _toConsumableArray(columns);
    }
  };
}