using HslCommunication.WebSocket; using Microsoft.Extensions.Hosting; using SqlSugar; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using WIDESEA_Core.Helper; using WIDESEA_Core.Seed; using ICacheService = WIDESEA_Core.Caches.ICacheService; namespace WIDESEA_Core.HostedService { public class PermissionDataHostService : IHostedService { private readonly DBContext _dbContext; private readonly ICacheService _cacheService; private readonly WebSocketServer _server; public static List UserRoles; public PermissionDataHostService(DBContext dbContext, ICacheService cacheService, WebSocketServer server) { _dbContext = dbContext; _cacheService = cacheService; _server = server; } public Task StartAsync(CancellationToken cancellationToken) { List roles = _dbContext.Db.Queryable("Sys_Role", "x").Select(RoleSelectModes).ToList(); List roleDynamics = new List(); foreach (var item in roles) { roleDynamics.Add(item); } List roleDataDynamics = new List(); List roleDatas = _dbContext.Db.Queryable("Sys_RoleDataPermission", "x").Select(RoleDataSelectModes).ToList(); foreach (var item in roleDatas) { roleDataDynamics.Add(item); } List users = _dbContext.Db.Queryable("Sys_User", "x").Select(UserSelectModes).ToList(); List userRoles = new List(); foreach (var item in users) { dynamic user = item; dynamic? role = roleDynamics.FirstOrDefault(x => x.RoleId == user.RoleId); List warehouseIds = roleDataDynamics.Where(x => x.RoleId == user.RoleId).Select(x => x.WarehouseId).ToList(); List ids = new List(); for (int i = 0; i < warehouseIds.Count; i++) { ids.Add(Convert.ToInt32(warehouseIds[i])); } if (role != null) { userRoles.Add(new UserRole { RoleId = role.RoleId, RoleName = role.RoleName, ParentId = role.ParentId, UserId = user.UserId, UserName = user.UserName, WarehouseIds = ids }); } } UserRoles = userRoles; _cacheService.AddOrUpdate("UserRoles", userRoles.Serialize()); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } List RoleSelectModes = new List() { new SelectModel() { FieldName = "RoleId", }, new SelectModel() { FieldName = "ParentId", }, new SelectModel() { FieldName = "RoleName", }, }; List UserSelectModes = new List() { new SelectModel() { FieldName = "UserId", }, new SelectModel() { FieldName = "UserName", }, new SelectModel() { FieldName = "RoleId", }, new SelectModel() { FieldName = "RoleName", } }; List RoleDataSelectModes = new List() { new SelectModel() { FieldName = "RoleId", }, new SelectModel() { FieldName = "WarehouseId", } }; } public class UserRole { public int UserId { get; set; } public int RoleId { get; set; } public string RoleName { get; set; } public string UserName { get; set; } public int ParentId { get; set; } public int AuthorityScope { get; set; } public List WarehouseIds { get; set; } } }