import _Object$keys2 from "@babel/runtime-corejs3/core-js-stable/object/keys";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import { groupBy } from '../../utils';
import { always } from '../../utils/others';
import simpleEncode from './simpleEncode';
/** 根据指定的 code 序列计算下钻树 */
export default function buildDrillTree(data, codes) {
  var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
    _ref$encode = _ref.encode,
    encode = _ref$encode === void 0 ? simpleEncode : _ref$encode,
    _ref$totalValue = _ref.totalValue,
    totalValue = _ref$totalValue === void 0 ? '总计' : _ref$totalValue,
    _ref$includeTopWrappe = _ref.includeTopWrapper,
    includeTopWrapper = _ref$includeTopWrappe === void 0 ? false : _ref$includeTopWrappe,
    _ref$isExpand = _ref.isExpand,
    isExpand = _ref$isExpand === void 0 ? always(true) : _ref$isExpand,
    _ref$enforceExpandTot = _ref.enforceExpandTotalNode,
    enforceExpandTotalNode = _ref$enforceExpandTot === void 0 ? true : _ref$enforceExpandTot;
  var emptyPath = [];
  var totalKey = encode(emptyPath);
  var array;
  var hasChild = false;
  if (codes.length === 0) {
    array = [];
  } else if (!enforceExpandTotalNode && !isExpand(totalKey)) {
    array = [];
    hasChild = data.length > 0;
  } else {
    array = dfs(data, []);
  }
  if (includeTopWrapper) {
    var rootNode = {
      key: totalKey,
      value: totalValue,
      path: emptyPath,
      children: array
    };
    if (hasChild) {
      rootNode.hasChild = hasChild;
    }
    return [rootNode];
  }
  if (includeTopWrapper) {
    return [{
      key: totalKey,
      value: totalValue,
      path: emptyPath,
      children: array
    }];
  }
  return array;
  function dfs(slice, path) {
    var depth = path.length;
    var array = [];
    var code = codes[depth];
    var groups = groupBy(slice, function (row) {
      return row[code];
    });
    for (var _i = 0, _Object$keys = _Object$keys2(groups); _i < _Object$keys.length; _i++) {
      var groupKey = _Object$keys[_i];
      path.push(groupKey);
      var node = {
        key: encode(path),
        value: groupKey,
        path: _sliceInstanceProperty(path).call(path)
      };
      array.push(node);
      var group = groups[groupKey];
      if (group.length > 0 && depth < codes.length - 1) {
        if (isExpand(node.key)) {
          node.children = dfs(group, path);
        } else {
          node.hasChild = true;
        }
      }
      path.pop();
    }
    return array;
  }
}