"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.convertDrillTreeToCrossTree = convertDrillTreeToCrossTree;

var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/set"));

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

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

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

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

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

var _react = _interopRequireDefault(require("react"));

var _rxjs = require("rxjs");

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _classnames = _interopRequireDefault(require("classnames"));

var _commonViews = require("../../common-views");

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

var _simpleEncode = _interopRequireDefault(require("./simpleEncode"));

var _styles = require("../../base/styles");

var _templateObject;

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

var ExpandSpan = _styledComponents.default.span(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["\n  display: inline-flex;\n  align-items: center;\n  padding: 2px 8px 2px 0;\n  cursor: pointer;\n\n  .icon {\n    fill: #999;\n    margin-right: 4px;\n\n    &.", " {\n      transform-origin: center center;\n      transform: rotate(90deg);\n    }\n  }\n"])), _styles.Classes.expanded);

function convertDrillTreeToCrossTree(drillTree) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      indicators = _ref.indicators,
      _ref$encode = _ref.encode,
      encode = _ref$encode === void 0 ? _simpleEncode.default : _ref$encode,
      generateSubtotalNode = _ref.generateSubtotalNode,
      _ref$enforceExpandTot = _ref.enforceExpandTotalNode,
      enforceExpandTotalNode = _ref$enforceExpandTot === void 0 ? true : _ref$enforceExpandTot,
      expandKeys = _ref.expandKeys,
      _ref$onChangeExpandKe = _ref.onChangeExpandKeys,
      onChangeExpandKeys = _ref$onChangeExpandKe === void 0 ? _rxjs.noop : _ref$onChangeExpandKe,
      supportsExpand = _ref.supportsExpand;

  var totalKey = encode([]);

  if (supportsExpand && expandKeys == null) {
    throw new Error('[ali-react-table] convertDrillTreeToCrossTree(...) 设置 supportsExpand=true 时，expandKeys 不能为 null/undefined.');
  }

  var expandKeySet = new _set.default(expandKeys);
  return dfs(drillTree, 0);
  /** 在 indicators 非空的情况下获取指标对应的 CrossTreeNode */

  function getIndicators(node, nodeData) {
    return (0, _map.default)(indicators).call(indicators, function (indicator) {
      var _context;

      return (0, _extends2.default)({
        key: encode((0, _concat.default)(_context = node.path).call(_context, [indicator.code])),
        value: indicator.name,
        data: (0, _extends2.default)((0, _extends2.default)({}, nodeData), {
          indicator: indicator
        })
      }, indicator);
    });
  }

  function drillNodeToTreeNode(node, nodeData) {
    if (indicators != null) {
      return {
        key: node.key,
        value: node.value,
        data: nodeData,
        children: getIndicators(node, nodeData)
      };
    } else {
      return {
        key: node.key,
        value: node.value,
        data: nodeData
      };
    }
  }

  function dfs(drillNodes, depth) {
    var result = [];

    var _iterator = _createForOfIteratorHelper(drillNodes),
        _step;

    try {
      var _loop = function _loop() {
        var node = _step.value;
        var nodeData = {
          dataKey: node.key,
          dataPath: node.path
        };

        if ((0, _utils.isLeafNode)(node) && !node.hasChild) {
          result.push(drillNodeToTreeNode(node, nodeData));
        } else {
          var needProcessChildren = true;
          var crossTreeNode = {
            key: node.key,
            value: node.value,
            data: nodeData
          };

          if (!supportsExpand || enforceExpandTotalNode && node.key === totalKey) {
            // 不支持展开功能 或是强制展开
            crossTreeNode.children = dfs(node.children, depth + 1);
          } else if (expandKeySet.has(node.key)) {
            // 展开的父节点
            // @ts-ignore
            crossTreeNode.title = /*#__PURE__*/_react.default.createElement(ExpandSpan, {
              onClick: function onClick() {
                onChangeExpandKeys((0, _filter.default)(expandKeys).call(expandKeys, function (k) {
                  return k !== node.key;
                }), node, 'collapse');
              }
            }, /*#__PURE__*/_react.default.createElement(_commonViews.icons.CaretRight, {
              className: (0, _classnames.default)('icon', _styles.Classes.expanded)
            }), node.value);
            crossTreeNode.children = dfs(node.children, depth + 1);
          } else {
            // 收拢的父节点
            needProcessChildren = false;
            crossTreeNode.title = /*#__PURE__*/_react.default.createElement(ExpandSpan, {
              onClick: function onClick() {
                onChangeExpandKeys((0, _concat.default)(expandKeys).call(expandKeys, [node.key]), node, 'expand');
              }
            }, /*#__PURE__*/_react.default.createElement(_commonViews.icons.CaretRight, {
              className: "icon collapsed"
            }), node.value);

            if (indicators != null) {
              crossTreeNode.children = getIndicators(node, nodeData);
            }
          }

          if (needProcessChildren) {
            var subtotalNodeData = generateSubtotalNode === null || generateSubtotalNode === void 0 ? void 0 : generateSubtotalNode(node);

            if (subtotalNodeData) {
              var _context2;

              var _subtotalNodeData$pos = subtotalNodeData.position,
                  position = _subtotalNodeData$pos === void 0 ? 'start' : _subtotalNodeData$pos,
                  value = subtotalNodeData.value;
              var subtotalPath = (0, _concat.default)(_context2 = node.path).call(_context2, [value]);
              var subtotalDrillNode = {
                key: encode(subtotalPath),
                path: subtotalPath,
                value: value
              };
              var subtotalTreeNode = drillNodeToTreeNode(subtotalDrillNode, nodeData);

              if (position === 'start') {
                crossTreeNode.children.unshift(subtotalTreeNode);
              } else {
                crossTreeNode.children.push(subtotalTreeNode);
              }
            }
          }

          result.push(crossTreeNode);
        }
      };

      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        _loop();
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return result;
  }
}