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";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _taggedTemplateLiteral from "@babel/runtime-corejs3/helpers/taggedTemplateLiteral";
var _templateObject;
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 _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import React from 'react';
import { noop } from 'rxjs';
import styled from 'styled-components';
import cx from 'classnames';
import { icons } from '../../common-views';
import { isLeafNode } from '../../utils';
import simpleEncode from './simpleEncode';
import { Classes } from '../../base/styles';
var ExpandSpan = styled.span(_templateObject || (_templateObject = _taggedTemplateLiteral(["\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"])), Classes.expanded);
export 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 : _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 ? 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(expandKeys);
  return dfs(drillTree, 0);
  /** 在 indicators 非空的情况下获取指标对应的 CrossTreeNode */
  function getIndicators(node, nodeData) {
    return _mapInstanceProperty(indicators).call(indicators, function (indicator) {
      var _context;
      return _extends({
        key: encode(_concatInstanceProperty(_context = node.path).call(_context, [indicator.code])),
        value: indicator.name,
        data: _extends(_extends({}, 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 (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.createElement(ExpandSpan, {
              onClick: function onClick() {
                onChangeExpandKeys(_filterInstanceProperty(expandKeys).call(expandKeys, function (k) {
                  return k !== node.key;
                }), node, 'collapse');
              }
            }, /*#__PURE__*/React.createElement(icons.CaretRight, {
              className: cx('icon', Classes.expanded)
            }), node.value);
            crossTreeNode.children = dfs(node.children, depth + 1);
          } else {
            // 收拢的父节点
            needProcessChildren = false;
            crossTreeNode.title = /*#__PURE__*/React.createElement(ExpandSpan, {
              onClick: function onClick() {
                onChangeExpandKeys(_concatInstanceProperty(expandKeys).call(expandKeys, [node.key]), node, 'expand');
              }
            }, /*#__PURE__*/React.createElement(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 = _concatInstanceProperty(_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;
  }
}