import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
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";

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context3; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context3 = Object.prototype.toString.call(o)).call(_context3, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

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 _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 { isLeafNode as standardIsLeafNode, mergeCellProps } from '../../utils';
import { Classes } from '../../base/styles';
export var treeMetaSymbol = _Symbol('treeMetaSymbol');
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');

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

    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 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;
    var Icon = opts.icon;
    return pipeline.mapDataSource(processDataSource).mapColumns(processColumns);

    function processDataSource(input) {
      var result = [];
      dfs(input, 0);

      function dfs(nodes, depth) {
        if (nodes == null) {
          return;
        }

        var _iterator = _createForOfIteratorHelper(nodes),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var node = _step.value;
            var rowKey = node[primaryKey];
            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
            };
            result.push(_extends(_defineProperty({}, treeMetaKey, treeMeta), node));

            if (!isLeaf && expanded) {
              dfs(node.children, depth + 1);
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }

      return result;
    }

    function processColumns(columns) {
      var _context2;

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

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

      var render = function render(value, record, recordIndex) {
        var content = internals.safeRender(firstCol, 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(firstCol, record, rowIndex);

        if (record[treeMetaKey] == null) {
          // 没有 treeMeta 信息的话，就返回原先的 cellProps
          return prevProps;
        }

        var _record$treeMetaKey2 = record[treeMetaKey],
            isLeaf = _record$treeMetaKey2.isLeaf,
            rowKey = _record$treeMetaKey2.rowKey;

        if (isLeaf) {
          return prevProps;
        }

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

            toggle(rowKey);
          },
          style: {
            cursor: 'pointer'
          }
        });
      };

      return _concatInstanceProperty(_context2 = [_extends(_extends({}, firstCol), {
        title: /*#__PURE__*/React.createElement("span", {
          style: {
            marginLeft: iconIndent + iconWidth + iconGap
          }
        }, internals.safeRenderHeader(firstCol)),
        render: render,
        getCellProps: clickArea === 'cell' ? getCellProps : firstCol.getCellProps
      })]).call(_context2, _toConsumableArray(others));
    }
  };
}