"use strict";

var __assign = void 0 && (void 0).__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

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

    return t;
  };

  return __assign.apply(this, arguments);
};

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  Object.defineProperty(o, k2, {
    enumerable: true,
    get: function get() {
      return m[k];
    }
  });
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});

var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});

var __importStar = void 0 && (void 0).__importStar || function (mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k in mod) {
    if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  }

  __setModuleDefault(result, mod);

  return result;
};

var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CascadeModifiedList = exports.CascadeCheckListWrap = exports.CascadeCheckListMemo = void 0;

var jsx_runtime_1 = require("react/jsx-runtime");

var React = __importStar(require("react"));

var react_1 = require("react");

var CascadeCheckList_1 = require("./components/CascadeCheckList"); // 保证遍历单例运行


var onProcessing = false;
var debug = false; // eslint-disable-next-line

var console = debug ? window.console : __assign(__assign({}, window.console), {
  log: function log() {
    var _args = [];

    for (var _i = 0; _i < arguments.length; _i++) {
      _args[_i] = arguments[_i];
    }
  }
});
var tempLeafNodeRouteIds = {};

var generateObjFromArr = function generateObjFromArr(arr, level) {
  var tempObj = {};
  var len = arr.length;

  for (var i = 0; i < len; i++) {
    var item = arr[i];
    var val = item.val,
        id = item.id,
        _id = item._id;
    tempObj[id] = {
      id: id,
      _id: _id,
      val: val,
      level: level
    };
  }

  return tempObj;
};

var generateFinalSubNodeStatistic = function generateFinalSubNodeStatistic(nodes) {
  return nodes.reduce(function (acc, node) {
    var _id = node._id,
        id = node.id;
    acc[id] = _id || id;
    return acc;
  }, {});
};

var CascadeCheckListWrap = function CascadeCheckListWrap(props) {
  var _a = props.levelTitles,
      levelTitles = _a === void 0 ? [] : _a,
      data = props.data,
      showSearchLevel = props.showSearchLevel,
      levelSearchInputPlaceholder = props.levelSearchInputPlaceholder,
      levelShowCheckbox = props.levelShowCheckbox,
      levelSelectAll = props.levelSelectAll,
      levelSelectAllText = props.levelSelectAllText,
      renderer = props.renderer,
      customRendererLevel = props.customRendererLevel,
      checkedIds = props.checkedIds,
      initCheckedIds = props.initCheckedIds,
      onChange = props.onChange,
      rowWidth = props.rowWidth,
      rowMinWidth = props.rowMinWidth,
      rowMaxWidth = props.rowMaxWidth,
      _b = props.triggerType,
      triggerType = _b === void 0 ? 'hover' : _b;
  var initIds = react_1.useMemo(function () {
    var ids = checkedIds || initCheckedIds;

    if (ids) {
      return ids.reduce(function (acc, id) {
        acc[id] = id;
        return acc;
      }, {});
    }

    return {};
  }, [checkedIds, initCheckedIds]); // 层级节点数据（非叶子节点的直接子孩子数据汇总）

  var _c = react_1.useState({}),
      leveNodesStatistic = _c[0],
      setLeveNodesStatistic = _c[1]; // 子节点统计（所有节点的子节点汇总）用于计算勾选


  var _d = react_1.useState({}),
      subNodesStatistic = _d[0],
      setSubNodesStatistic = _d[1]; // 选中节点 id 汇总


  var _e = react_1.useState(initIds),
      checkedNodesIdsObj = _e[0],
      setCheckedNodesIdsObj = _e[1];

  var _f = react_1.useState(0),
      maxLevel = _f[0],
      setMaxLevel = _f[1]; // 遍历数据计算每个节点的子节点汇总，用于计算每一层子节点和节点勾选状态


  var traversalNode = react_1.useCallback(function (trees) {
    onProcessing = true; // 非叶子节点

    var noLeafNodeIds = [];
    var levelNodesStatistic = {};
    var subNodesStatistic = {};
    var partialFinalNodeStatistic = {}; // 树高为1的节点统计

    var filterNodesObj = {};
    var treeLen = trees.length;
    console.time('dfs'); // DFS 统计树高为1的子树的根节点（以减少最后统计非叶子节点拥有的叶子节点时间)

    for (var i = 0; i < treeLen; i++) {
      var tree = trees[i]; // 子树高度统计

      var subTreeHeight = {};
      var subTreeHeightIndexMapId = {};
      var tempStack = [tree];
      var index = 0;

      while (tempStack.length) {
        var _a = tempStack[tempStack.length - 1],
            id = _a.id,
            children = _a.children;
        var nodeTreeHeightInfo = subTreeHeight[id];

        if (children.length) {
          if (nodeTreeHeightInfo) {
            // NOT LAST
            var curNodeIndex = nodeTreeHeightInfo.index;
            var nextId = subTreeHeightIndexMapId[curNodeIndex + 1];

            if (nextId) {
              nodeTreeHeightInfo.height = subTreeHeight[nextId].height + 1;
            } else {
              // LAST
              nodeTreeHeightInfo.height = nodeTreeHeightInfo.height + 1;
            }

            tempStack.pop();
          } else {
            // First traversal
            tempStack.push.apply(tempStack, children.reverse());
            subTreeHeight[id] = {
              index: index,
              height: 0
            };
            subTreeHeightIndexMapId[index] = id;
            index++;
          }
        } else {
          tempStack.pop();
        }
      }

      console.log('subTreeHeight: ', subTreeHeight);
      var ids = Object.keys(subTreeHeight);
      var idsCnt = ids.length;

      for (var i_1 = 0; i_1 < idsCnt; i_1++) {
        var id = ids[i_1];
        var height = subTreeHeight[id].height;

        if (height === 1) {
          filterNodesObj[id] = id;
        }
      }
    }

    console.log('filterNodesObj: ', filterNodesObj);
    console.timeEnd('dfs');
    console.time('bfs');

    var _loop_1 = function _loop_1(i) {
      var level = 1;
      var tree = trees[i];
      var id = tree.id;
      var children = [];

      if ('children' in tree) {
        children = tree.children;
      }

      if (children.length) {
        var iterationFn = function iterationFn(acc, node) {
          var id = node.id,
              children = node.children;

          if (children.length) {
            var tempObj_1 = generateObjFromArr(children, level);
            levelNodesStatistic[id] = tempObj_1;
            subNodesStatistic[id] = tempObj_1;

            if (id in filterNodesObj) {
              partialFinalNodeStatistic[id] = generateFinalSubNodeStatistic(children);
            }

            noLeafNodeIds.push(id);
          }

          acc.push.apply(acc, children);
          return acc;
        };

        var tempObj = generateObjFromArr(children, level++);
        levelNodesStatistic[id] = tempObj;
        subNodesStatistic[id] = tempObj; // 对于树高为1的非叶子节点直接生成对应最终数据结构

        if (id in filterNodesObj) {
          partialFinalNodeStatistic[id] = generateFinalSubNodeStatistic(children);
        }

        noLeafNodeIds.push(id);
        var tempStack = children;

        while (tempStack.length) {
          tempStack = tempStack.reduce(iterationFn, []);
          level++;
        }
      }

      setMaxLevel(function (prev) {
        return Math.max(prev, level - 1);
      });
    }; // BFS 获取每个节点的直接子节点汇总


    for (var i = 0; i < treeLen; i++) {
      _loop_1(i);
    } // console.log('partialFinalNodeStatistic: ', partialFinalNodeStatistic);


    console.timeEnd('bfs');
    console.time('generate struct'); // 根据直接子节点汇总 得出最后节点汇总

    var finalNodeStatistic = {};
    noLeafNodeIds.reverse().forEach(function (nodeId) {
      if (nodeId in filterNodesObj) {
        finalNodeStatistic[nodeId] = partialFinalNodeStatistic[nodeId];
        return;
      }

      var subNodesValObj = finalNodeStatistic[nodeId] || subNodesStatistic[nodeId] || {};
      finalNodeStatistic[nodeId] = Object.keys(subNodesValObj).reduce(function (acc, val) {
        var _a;

        if (!onProcessing) {
          return [{}, {}];
        }

        var res = {};
        var _b = subNodesValObj[val],
            id = _b.id,
            _id = _b._id;
        var tempObj = (_a = {}, _a[val] = {
          id: id,
          _id: _id
        }, _a);

        while (Object.keys(tempObj).length) {
          var key = Object.keys(tempObj)[0];
          var _c = tempObj[key],
              id_1 = _c.id,
              _id_1 = _c._id;
          delete tempObj[key];
          var subNodesObj = finalNodeStatistic[key];

          if (subNodesObj) {
            res = __assign(__assign({}, res), subNodesObj);
          } else {
            res[id_1] = _id_1 || id_1;

            if (_id_1) {
              tempLeafNodeRouteIds[id_1] = _id_1;
            }
          }
        }

        acc = __assign(__assign({}, acc), res);
        return acc;
      }, {});
    });
    console.timeEnd('generate struct');
    console.log('levelNodesStatistic: ', levelNodesStatistic);
    console.log('subNodesStatistic: ', finalNodeStatistic);
    return [levelNodesStatistic, finalNodeStatistic];
  }, []);
  react_1.useEffect(function () {
    if (data.length) {
      onProcessing = false;
      setTimeout(function () {
        var _a = traversalNode(data),
            lvSt = _a[0],
            subNodeSt = _a[1];

        setLeveNodesStatistic(lvSt);
        setSubNodesStatistic(subNodeSt);
      });
    }
  }, [data, traversalNode]);
  react_1.useEffect(function () {
    if (checkedIds) {
      var nodesIdsObj = checkedIds.reduce(function (acc, v) {
        acc[v] = tempLeafNodeRouteIds[v] || v;
        return acc;
      }, {});
      console.log('nodesIdsObj: ', nodesIdsObj);
      setCheckedNodesIdsObj(nodesIdsObj);
    }
  }, [checkedIds]);
  return jsx_runtime_1.jsx(CascadeCheckList_1.CascadeCheckListMemo, {
    rowWidth: rowWidth,
    rowMinWidth: rowMinWidth,
    rowMaxWidth: rowMaxWidth,
    control: !!checkedIds,
    renderer: renderer,
    customRendererLevel: customRendererLevel,
    level: 0,
    levelTitles: levelTitles,
    data: data,
    leveNodesStatistic: leveNodesStatistic,
    subNodesStatistic: subNodesStatistic,
    checkedNodesIdsObj: checkedNodesIdsObj,
    updateCheckedNodesIdsObj: setCheckedNodesIdsObj,
    showSearchLevel: showSearchLevel,
    levelSearchInputPlaceholder: levelSearchInputPlaceholder,
    levelShowCheckbox: levelShowCheckbox,
    onChange: onChange,
    initCheckedIds: initCheckedIds,
    levelSelectAll: levelSelectAll,
    levelSelectAllText: levelSelectAllText,
    maxLevel: maxLevel,
    triggerType: triggerType
  }, void 0);
};

exports.CascadeCheckListWrap = CascadeCheckListWrap;
CascadeCheckListWrap.displayName = 'CascadeCheckList';
var CascadeCheckListMemo = React.memo(CascadeCheckListWrap);
exports.CascadeCheckListMemo = CascadeCheckListMemo;
CascadeCheckListMemo.displayName = 'CascadeCheckListMemo';

var List_1 = require("./components/List");

Object.defineProperty(exports, "CascadeModifiedList", {
  enumerable: true,
  get: function get() {
    return __importDefault(List_1)["default"];
  }
});
exports["default"] = CascadeCheckListWrap;

