// import type { AppRouteRecordRaw } from '/@/router/types';

export interface TreeNode {
  id: number;
  parentId: number;
  name: string;
  key?: string;
  level?: string;
  children?: TreeNode[];
}
export interface TreeMenuNode {
  menuId: number;
  parentId: number;
  name: string;
  type?: number;
  children?: TreeMenuNode[];
}

// function traverse(tree: TreeMenuNode[], rootId: number) {
//   tree.forEach((item) => {
//     if (item.parentId == rootId) {
//       console.log('name', item.name);
//       console.log('menuId', item.menuId);
//       console.log('rootId', rootId);
//       // temp.push(item.parentId);
//       // item.key = temp;
//     }
//     if (item.children?.length) {
//       traverse(item.children, item.menuId);
//     }
//   });
// }

export function makeTree(treeNodes: TreeNode[]): TreeNode[] {
  // 提前生成节点查找表。
  // 如果明确节点是顺序可以保证先父后子，可以省去这次遍历，在后面边遍历过程中填充查找表
  const nodesMap = new Map<number, TreeNode>(treeNodes.map((node) => [node.id, node]));

  // 引入虚拟根节点来统一实现 parent 始终有效，避免空判断
  const virtualRoot = {} as Partial<TreeNode>;
  treeNodes.forEach((node) => {
    const parent = nodesMap.get(node.parentId) ?? virtualRoot;
    (parent.children ??= []).push(node);
  });
  // if (virtualRoot.children?.length) {
  //   traverse(virtualRoot.children, virtualRoot.children[0].id);
  // }

  return virtualRoot.children ?? [];
}

export function makeMenuTree(treeNodes: TreeMenuNode[]): TreeMenuNode[] {
  const nodesMap = new Map<number, TreeMenuNode>(treeNodes.map((node) => [node.menuId, node]));

  // 引入虚拟根节点来统一实现 parent 始终有效，避免空判断
  const virtualRoot = {} as Partial<TreeMenuNode>;
  treeNodes.forEach((node) => {
    const parent = nodesMap.get(node.parentId) ?? virtualRoot;
    (parent.children ??= []).push(node);
  });
  return virtualRoot.children ?? [];
}
