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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context4; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context4 = Object.prototype.toString.call(o)).call(_context4, 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 _Object$getOwnPropertySymbols from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";

var __rest = this && this.__rest || function (s, e) {
  var t = {};

  for (var p in s) {
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  }

  if (s != null && typeof _Object$getOwnPropertySymbols === "function") for (var i = 0, p = _Object$getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};

import { noop } from 'rxjs';
import { features, TablePipeline } from '../../pipeline';
import { isLeafNode as standardIsLeafNode } from '../../utils';
import { ROW_KEY } from '../cross-table';
export default function buildCrossTreeTable(options) {
  var _a, _b;

  var primaryColumn = options.primaryColumn,
      openKeys = options.openKeys,
      onChangeOpenKeys = options.onChangeOpenKeys,
      indentSize = options.indentSize,
      _options$isLeafNode = options.isLeafNode,
      isLeafNodeOpt = _options$isLeafNode === void 0 ? standardIsLeafNode : _options$isLeafNode; // 有的时候 leftTree/topTree 是通过 node.children 传入的
  // 此时 leftTree/topTree 等于 null 和等于空数组是等价的
  // 故在这里兼容 leftTree/topTree 为空的情况

  var leftTree = (_a = options.leftTree) !== null && _a !== void 0 ? _a : [];
  var topTree = (_b = options.topTree) !== null && _b !== void 0 ? _b : [];
  var pipeline = new TablePipeline({
    state: {},
    setState: noop,
    ctx: {
      primaryKey: ROW_KEY
    }
  });
  pipeline.input({
    dataSource: getDataSource(),
    columns: getColumns()
  });
  pipeline.use(features.treeMode({
    openKeys: openKeys,
    onChangeOpenKeys: onChangeOpenKeys,
    indentSize: indentSize,
    isLeafNode: function isLeafNode(row, nodeMeta) {
      // 调用上层 isLeafNodeOpt 时，会从 row.node 中读取该表格行对应的 leftTreeNode
      return isLeafNodeOpt(row.node, nodeMeta);
    }
  }));
  return {
    dataSource: pipeline.getDataSource(),
    columns: pipeline.getColumns()
  };
  /** 获取表格的列配置 */

  function getColumns() {
    var _context;

    return _concatInstanceProperty(_context = [_extends(_extends({}, primaryColumn), {
      getValue: function getValue(row) {
        return row.node.value;
      },
      getCellProps: function getCellProps(value, row) {
        if (primaryColumn.getCellProps) {
          return primaryColumn.getCellProps(row.node, row.nodes.length - 1);
        }
      },
      render: function render(value, row) {
        if (primaryColumn.render) {
          return primaryColumn.render(row.node, row.nodes.length - 1);
        }

        return value;
      }
    })]).call(_context, _toConsumableArray(getDataPartColumns()));
    /** 获取表格数据部分的列配置 */

    function getDataPartColumns() {
      return dfs(topTree, {
        depth: 0
      });

      function dfs(nodes, ctx) {
        var result = [];

        var _iterator = _createForOfIteratorHelper(nodes),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var node = _step.value;

            if (standardIsLeafNode(node)) {
              result.push(getDataColumn(node, ctx.depth));
            } else {
              var key = node.key,
                  value = node.value,
                  children = node.children,
                  others = __rest(node, ["key", "value", "children"]);

              result.push(_extends(_extends({}, others), {
                name: value,
                children: dfs(children, {
                  depth: ctx.depth + 1
                })
              }));
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }

        return result;
      }
    }

    function getDataColumn(topNode, topDepth) {
      var columnGetValue = function columnGetValue(row) {
        var leftDepth = row.nodes.length - 1;
        var leftNode = row.node;
        return options.getValue(leftNode, topNode, leftDepth, topDepth);
      };

      var key = topNode.key,
          value = topNode.value,
          children = topNode.children,
          others = __rest(topNode, ["key", "value", "children"]);

      return _extends(_extends({}, others), {
        getValue: columnGetValue,
        name: value,
        children: null,
        render: function render(value, row) {
          if (options.render) {
            var leftDepth = row.nodes.length - 1;
            var leftNode = row.node;
            return options.render(value, leftNode, topNode, leftDepth, topDepth);
          }

          return value;
        },
        getCellProps: function getCellProps(value, row) {
          if (options.getCellProps) {
            var leftDepth = row.nodes.length - 1;
            var leftNode = row.node;
            return options.getCellProps(value, leftNode, topNode, leftDepth, topDepth);
          }
        }
      });
    }
  }

  function getDataSource() {
    return dfs(leftTree, {
      nodes: []
    });

    function dfs(nodes, ctx) {
      var result = [];

      var _iterator2 = _createForOfIteratorHelper(nodes),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var node = _step2.value;

          if (node.hidden) {
            // 跳过被隐藏的节点
            continue;
          }

          if (standardIsLeafNode(node)) {
            var _context2, _result$push;

            result.push((_result$push = {}, _defineProperty(_result$push, ROW_KEY, node.key), _defineProperty(_result$push, "node", node), _defineProperty(_result$push, "nodes", _concatInstanceProperty(_context2 = []).call(_context2, _toConsumableArray(ctx.nodes), [node])), _result$push));
          } else {
            var _context3, _result$push2;

            var _nodes = _concatInstanceProperty(_context3 = []).call(_context3, _toConsumableArray(ctx.nodes), [node]);

            ctx.nodes.push(node);
            var children = dfs(node.children, ctx);
            result.push((_result$push2 = {}, _defineProperty(_result$push2, ROW_KEY, node.key), _defineProperty(_result$push2, "node", node), _defineProperty(_result$push2, "nodes", _nodes), _defineProperty(_result$push2, "children", children), _result$push2));
            ctx.nodes.pop();
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }

      return result;
    }
  }
}