using Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Permission { public static class PermissionManager { public const PermissionLevel DefaultPermissionLevel = PermissionLevel.无权限; public static User CurrentUser { get => AppSession.CurrentUser; private set => AppSession.CurrentUser = value; }//当前的权限等级 public static event Action OnPermissionLevelChanged; // 定义一个事件,当权限级别改变时触发 public static void SignIn(User user) { CurrentUser = user; OnPermissionLevelChanged?.Invoke(user.PermissionLevel); } public static void SignOut() { CurrentUser.PermissionLevel = DefaultPermissionLevel; CurrentUser.Username = ""; // 触发事件:通知所有订阅者权限已变更 OnPermissionLevelChanged?.Invoke(DefaultPermissionLevel); } public static void LogOffAndSignInOperator() { //SignOut(); if (CurrentUser.PermissionLevel != PermissionLevel.操作工 && CurrentUser.PermissionLevel != PermissionLevel.开发者) { User user = new User(CurrentUser.Username + "_自动注销", "", PermissionLevel.操作工); SignIn(user); } } public static void ApplyPermissions(Form form) { foreach (Control control in GetAllControls(form)) { // 控件本身实现了接口 if (control is IPermissionControl pc) { pc.CurrentPermissionLevel = CurrentUser.PermissionLevel; } else { var hasPermission = CurrentUser.PermissionLevel >= control.GetPermissionLevel(); control.Enabled = hasPermission; //control.Visible = hasPermission; //if (control is Control c && !(c is Form)) // c.Enabled = hasPermission; } } } private static IEnumerable GetAllControls(Control parent) { var controls = new List(); foreach (Control ctrl in parent.Controls) { controls.Add(ctrl); if(!(ctrl is IPermissionControl pc) && ctrl.HasChildren) controls.AddRange(GetAllControls(ctrl)); // 递归 } return controls; } private static readonly object _lock = new object(); private static bool _initialized = false; private static readonly Dictionary roleProfiles = new Dictionary(); private static readonly string[] _roleFileNames = { "operator", "engineer", "technician", "admin" }; private const string roleDir = "Role"; /// /// 初始化权限管理器(建议在程序启动时调用一次) /// public static void Initialize() { if (_initialized) return; lock (_lock) { if (_initialized) return; for (int i = 0; i < _roleFileNames.Length; i++) { string filePath = GetPermissionFilePath(_roleFileNames[i]); if (File.Exists(filePath)) { try { string json = File.ReadAllText(filePath); var profile = JsonHelper.DeserializeFromString(json) ?? new PermissionProfile(); roleProfiles[(PermissionLevel)i] = profile; } catch (Exception) { roleProfiles[(PermissionLevel)i] = new PermissionProfile(); // 损坏则新建 } } else { roleProfiles[(PermissionLevel)i] = new PermissionProfile(); // 文件不存在,空权限 } } _initialized = true; } } public static void ResetPermissions() { lock (_lock) { roleProfiles.Clear(); _initialized = false; Initialize(); } } private static string GetPermissionFilePath(string roleName) { return Path.Combine(Application.StartupPath, roleDir, $"permissions_{roleName}.json"); } /// /// 获取指定角色被授权的控件列表 /// /// 0=操作工, 1=工程师, 2=技术员, 3=管理员 /// 授权控件列表(只读副本) public static IReadOnlyList GetAuthorizedControlsForRole(PermissionLevel roleLevel) { if (!_initialized) Initialize(); // 懒加载(也可强制要求提前初始化) lock (_lock) { if (roleProfiles.TryGetValue(roleLevel, out var profile)) { // 返回副本,防止外部修改缓存 return profile.AuthorizedControls.ToList().AsReadOnly(); } return new List(); } } public static PermissionProfile GetRoleProfile(PermissionLevel roleLevel) { if (!_initialized) Initialize(); lock (_lock) { if (roleProfiles.TryGetValue(roleLevel, out var profile)) { return profile; } return new PermissionProfile(); } } public static void SaveRoleProfile(PermissionLevel roleLevel, PermissionProfile profile) { roleProfiles[roleLevel] = profile; string filePath = GetPermissionFilePath(_roleFileNames[(int)roleLevel]); JsonHelper.SerializeObject(filePath, profile); } /// /// (可选)检查某个控件对当前角色是否授权 /// public static bool IsControlAuthorized(PermissionLevel roleLevel, string formType, string controlName) { var authorized = GetAuthorizedControlsForRole(roleLevel); return authorized.Any(c => c.FormType == formType && c.ControlName == controlName); } } }