/*
 * @Author: your name
 * @Date: 2024-05-17 16:09:03
 * @LastEditTime: 2024-05-18 18:40:13
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/utils/getAuth.js
 */
import { orgList } from "@/views/home/components/mockData";
//返回可动态添加的路由
export const getAuthRouterFn = (list) => {
  // 将list 转成一维数组，按钮级别权限拿到 返回为[]格式
  const { result, anthBtnList } = flattenTree(list);
  const arr = filterTreeByPermissions(result, orgList);
  return { authRouterList: arr, anthBtnList };
};

const flattenTree = (tree) => {
  let result = [];
  let anthBtnList = [];
  const flattenRecursive = (nodes) => {
    nodes.forEach((node) => {
      result.push(node);
      if (node.children && node.children.length > 0) {
        flattenRecursive(node.children);
      }
      if (node.permissionDepth === 2) {
        anthBtnList.push(node);
      }
    });
  };

  flattenRecursive(tree);
  return { result, anthBtnList };
};
const filterTreeByPermissions = (permissions, tree) => {
  const permissionSet = new Set(permissions.map((item) => item.permissionName));

  const filterTreeRecursive = (nodes) => {
    return nodes.reduce((filteredNodes, node) => {
      const newNode = { ...node };

      if (newNode.children && newNode.children.length > 0) {
        newNode.children = filterTreeRecursive(newNode.children);
      }
      if (
        permissionSet.has(newNode.name) ||
        (newNode.children && newNode.children.length > 0)
      ) {
        filteredNodes.push(newNode);
      }

      return filteredNodes;
    }, []);
  };

  return filterTreeRecursive(tree);
};
