using AmtScanner.Api.Data; using AmtScanner.Api.Models; using Microsoft.EntityFrameworkCore; namespace AmtScanner.Api.Services; /// /// 菜单服务实现 /// public class MenuService : IMenuService { private readonly AppDbContext _context; private readonly IAuthService _authService; public MenuService(AppDbContext context, IAuthService authService) { _context = context; _authService = authService; } public async Task> GetUserMenusAsync(int userId) { // 获取用户角色 var userRoles = await _authService.GetUserRolesAsync(userId); // 如果是超级管理员,返回所有菜单 if (userRoles.Contains("R_SUPER")) { return await GetAllMenusAsync(); } // 获取用户角色对应的菜单 var roleIds = await _context.Roles .Where(r => userRoles.Contains(r.RoleCode) && r.Enabled) .Select(r => r.Id) .ToListAsync(); var menuIds = await _context.RoleMenus .Where(rm => roleIds.Contains(rm.RoleId)) .Select(rm => rm.MenuId) .Distinct() .ToListAsync(); var menus = await _context.Menus .Where(m => menuIds.Contains(m.Id)) .OrderBy(m => m.Sort) .ToListAsync(); return BuildMenuTree(menus, null); } public async Task> GetAllMenusAsync() { var menus = await _context.Menus .OrderBy(m => m.Sort) .ToListAsync(); return BuildMenuTree(menus, null); } private List BuildMenuTree(List menus, int? parentId) { return menus .Where(m => m.ParentId == parentId) .OrderBy(m => m.Sort) .Select(m => new MenuDto { Id = m.Id, Name = m.Name, Path = m.Path, Component = m.Component, Meta = new MenuMetaDto { Title = m.Title, Icon = m.Icon, IsHide = m.IsHide, KeepAlive = m.KeepAlive, Link = m.Link, IsIframe = m.IsIframe, Roles = string.IsNullOrEmpty(m.Roles) ? new List() : m.Roles.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList() }, Children = BuildMenuTree(menus, m.Id) }) .ToList(); } }