"use strict";

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

var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");

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

var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = buildCrossTreeTable;

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

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

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

var _getOwnPropertySymbols = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols"));

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

var _rxjs = require("rxjs");

var _pipeline = require("../../pipeline");

var _utils = require("../../utils");

var _crossTable = require("../cross-table");

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

var __rest = void 0 && (void 0).__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 _getOwnPropertySymbols.default === "function") for (var i = 0, p = (0, _getOwnPropertySymbols.default)(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;
};

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 ? _utils.isLeafNode : _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 _pipeline.TablePipeline({
    state: {},
    setState: _rxjs.noop,
    ctx: {
      primaryKey: _crossTable.ROW_KEY
    }
  });
  pipeline.input({
    dataSource: getDataSource(),
    columns: getColumns()
  });
  pipeline.use(_pipeline.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 (0, _concat.default)(_context = [(0, _extends2.default)((0, _extends2.default)({}, 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, (0, _toConsumableArray2.default)(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 ((0, _utils.isLeafNode)(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((0, _extends2.default)((0, _extends2.default)({}, 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 (0, _extends2.default)((0, _extends2.default)({}, 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 ((0, _utils.isLeafNode)(node)) {
            var _context2, _result$push;

            result.push((_result$push = {}, (0, _defineProperty2.default)(_result$push, _crossTable.ROW_KEY, node.key), (0, _defineProperty2.default)(_result$push, "node", node), (0, _defineProperty2.default)(_result$push, "nodes", (0, _concat.default)(_context2 = []).call(_context2, (0, _toConsumableArray2.default)(ctx.nodes), [node])), _result$push));
          } else {
            var _context3, _result$push2;

            var _nodes = (0, _concat.default)(_context3 = []).call(_context3, (0, _toConsumableArray2.default)(ctx.nodes), [node]);

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

      return result;
    }
  }
}