PermissionConfigForm.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using Model;
  2. using Newtonsoft.Json;
  3. using Permission;
  4. using PlcUiForm;
  5. using Sunny.UI;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Data;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. namespace YangjieTester.用户管理
  18. {
  19. [FormDescriptionAttribute("权限管理")]
  20. public partial class PermissionConfigForm : PlcBaseForm
  21. {
  22. private string ROOT_NAMESPACE = "YangjieTester"; // ← 你要扫描的根命名空间
  23. private PermissionLevel currentRoleLevel = PermissionLevel.操作工; // 默认操作工
  24. private Dictionary<PermissionLevel, PermissionProfile> roleProfiles = new Dictionary<PermissionLevel, PermissionProfile>();
  25. List<PermissionLevel> permissionLevels=new List<PermissionLevel>()
  26. {
  27. PermissionLevel.操作工,
  28. PermissionLevel.工程师,
  29. PermissionLevel.技术员,
  30. PermissionLevel.管理员,
  31. };
  32. private readonly string[] roleNames;
  33. public PermissionConfigForm()
  34. {
  35. ROOT_NAMESPACE = this.GetType().Namespace.Split('.')[0];
  36. InitializeComponent();
  37. treeView1.CheckBoxes = true; // 启用复选框
  38. treeView1.AfterCheck += treeView1_AfterCheck; // ← 添加这一行
  39. roleNames= permissionLevels.Select(level => Enum.GetName(typeof(PermissionLevel), level)).ToArray();
  40. // 👇 添加这一行
  41. InitializeRoleComboBox();
  42. LoadAllProfiles(); // 加载4个角色的权限
  43. LoadPermissionControlsIntoTreeView(); // 构建树结构(不带勾选)
  44. RefreshTreeViewCheckState(currentRoleLevel); // 应用当前角色的勾选状态
  45. }
  46. private void InitializeRoleComboBox()
  47. {
  48. //comboBoxRole.Items.Clear();
  49. //for (int i = 0; i < roleNames.Length; i++)
  50. //{
  51. // comboBoxRole.Items.Add($"{roleNames[i]} ({i})");
  52. //}
  53. comboBoxRole.DataSource = permissionLevels;
  54. comboBoxRole.SelectedItem = comboBoxRole.Items[0];
  55. comboBoxRole.SelectedIndexChanged += (s, e) =>
  56. {
  57. SaveCurrentProfile(); // 先保存当前角色的勾选
  58. currentRoleLevel = (PermissionLevel)comboBoxRole.SelectedItem;
  59. RefreshTreeViewCheckState(currentRoleLevel); // 根据新权限重设 CheckBox
  60. };
  61. }
  62. private void LoadAllProfiles()
  63. {
  64. foreach (var item in permissionLevels)
  65. {
  66. roleProfiles[item] = PermissionManager.GetRoleProfile(item);
  67. }
  68. }
  69. private void SaveCurrentProfile()
  70. {
  71. var profile = new PermissionProfile();
  72. // 遍历 TreeView 所有叶子节点(控件节点)
  73. CollectCheckedControls(treeView1.Nodes, profile.AuthorizedControls);
  74. roleProfiles[currentRoleLevel] = profile;
  75. }
  76. private void CollectCheckedControls(TreeNodeCollection nodes, List<AuthorizedControl> list)
  77. {
  78. foreach (TreeNode node in nodes)
  79. {
  80. if (node.Tag is ControlInfo info && node.Checked)
  81. {
  82. list.Add(new AuthorizedControl
  83. {
  84. Namespace = info.NameSpace,
  85. FormType = info.FormType,
  86. ControlName = info.ControlName
  87. });
  88. }
  89. CollectCheckedControls(node.Nodes, list);
  90. }
  91. }
  92. private bool isRestoringCheckState = false;
  93. private void RefreshTreeViewCheckState(PermissionLevel roleLevel)
  94. {
  95. var currentProfile = roleProfiles.TryGetValue(roleLevel, out var profile)
  96. ? profile
  97. : new PermissionProfile();
  98. // 构建快速查找字典:(FormType + "." + ControlName) -> bool
  99. var authorizedSet = new HashSet<string>(
  100. currentProfile.AuthorizedControls.Select(c => $"{c.Namespace}.{c.FormType}.{c.ControlName}")
  101. );
  102. //isRestoringCheckState = true;
  103. foreach (TreeNode node in treeView1.Nodes)
  104. {
  105. node.Checked = false;
  106. }
  107. SetCheckStateRecursive(treeView1.Nodes, authorizedSet);
  108. //isRestoringCheckState = false;
  109. }
  110. private void SetCheckStateRecursive(TreeNodeCollection nodes, HashSet<string> authorizedSet)
  111. {
  112. foreach (TreeNode node in nodes)
  113. {
  114. if (node.Tag is ControlInfo info)
  115. {
  116. bool isChecked = authorizedSet.Contains($"{info.NameSpace}.{info.FormType}.{info.ControlName}");
  117. node.Checked = isChecked;
  118. }
  119. SetCheckStateRecursive(node.Nodes, authorizedSet);
  120. }
  121. // 注意:此时不要触发 AfterCheck(避免级联),所以暂时关闭事件?
  122. // 或者我们重构:AfterCheck 只处理用户点击,程序设置不触发逻辑
  123. }
  124. private void LoadPermissionControlsIntoTreeView()
  125. {
  126. treeView1.Nodes.Clear();
  127. var assembly = Assembly.GetExecutingAssembly();
  128. var currentType = typeof(PermissionConfigForm);
  129. // 1. 获取所有在 ROOT_NAMESPACE 及其子命名空间下的非抽象 Form 类型(排除自己)
  130. var formTypes = assembly.GetTypes()
  131. .Where(t => t.IsSubclassOf(typeof(Form))
  132. && !t.IsAbstract
  133. && t != currentType
  134. && !string.IsNullOrEmpty(t.Namespace)
  135. && (t.Namespace == ROOT_NAMESPACE || t.Namespace.StartsWith(ROOT_NAMESPACE + ".")))
  136. .ToList();
  137. // 2. 按命名空间分组
  138. var formsByNamespace = formTypes
  139. .GroupBy(f => f.Namespace)
  140. .OrderBy(g => g.Key)
  141. .ToList();
  142. foreach (var nsGroup in formsByNamespace)
  143. {
  144. TreeNode nsNode = new TreeNode(nsGroup.Key);
  145. treeView1.Nodes.Add(nsNode);
  146. foreach (var formType in nsGroup.OrderBy(f => f.Name))
  147. {
  148. // TreeNode formNode = new TreeNode(formType.Name);
  149. TreeNode formNode = new TreeNode(FormEx.GetFormDescription(formType));
  150. nsNode.Nodes.Add(formNode);
  151. // 3. 扫描该窗体中所有实现了 IPermissionControl 的控件
  152. try
  153. {
  154. var permissionControls = GetPermissionControlFields(formType);
  155. //using (Form instance = (Form)Activator.CreateInstance(formType))
  156. {
  157. //var permissionControls = FindPermissionControls(instance.Controls, "");
  158. foreach (var item in permissionControls.OrderBy(x => x.ControlName))
  159. {
  160. TreeNode ctrlNode = new TreeNode($"{item.ControlName}");
  161. ctrlNode.Tag = new ControlInfo
  162. {
  163. NameSpace = nsGroup.Key,
  164. FormType = formType.Name,
  165. ControlName= item.ControlName,
  166. ControlType = item.ControlType
  167. };
  168. formNode.Nodes.Add(ctrlNode);
  169. }
  170. }
  171. }
  172. catch (Exception ex)
  173. {
  174. TreeNode errorNode = new TreeNode($"[加载失败: {ex.Message}]")
  175. {
  176. ForeColor = Color.Red
  177. };
  178. formNode.Nodes.Add(errorNode);
  179. }
  180. }
  181. }
  182. }
  183. private List<ControlInfo> GetPermissionControlFields(Type formType)
  184. {
  185. var list = new List<ControlInfo>();
  186. // 遍历窗体类中所有字段(包括私有、继承的)
  187. var fields = formType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
  188. foreach (var field in fields)
  189. {
  190. Type fieldType = field.FieldType;
  191. // 1. 必须是 Control 或其子类
  192. if (!typeof(Control).IsAssignableFrom(fieldType))
  193. continue;
  194. // 2. 必须实现 IPermissionControl 接口
  195. if (!typeof(IPermissionControl).IsAssignableFrom(fieldType))
  196. continue;
  197. //// 3. 必须具有名为 "WriteNode" 的公共实例属性(可读或可写均可)
  198. //var writeNodeProperty = fieldType.GetProperty(
  199. // "WriteNode",
  200. // BindingFlags.Public | BindingFlags.Instance);
  201. //if (writeNodeProperty == null)
  202. // continue; // 没有 WriteNode 属性,跳过
  203. if (typeof(MyUiButton).IsAssignableFrom(fieldType) || typeof(MyUiInput).IsAssignableFrom(fieldType) || typeof(MyUIComboBox).IsAssignableFrom(fieldType))
  204. {
  205. // ✅ 全部条件满足,加入列表
  206. list.Add(new ControlInfo
  207. {
  208. ControlName = field.Name,
  209. ControlType = fieldType.Name,
  210. });
  211. }
  212. }
  213. return list;
  214. }
  215. private bool isUpdating = false; // 防止 AfterCheck 递归调用
  216. private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
  217. {
  218. // 防止递归触发
  219. if (isUpdating || isRestoringCheckState) return;
  220. isUpdating = true;
  221. try
  222. {
  223. // 1. 子节点跟随父节点
  224. SetChildNodesChecked(e.Node, e.Node.Checked);
  225. // 👇 关键修复:如果当前节点被设为 Checked(全选),立即恢复其默认颜色
  226. if (e.Node.Checked)
  227. {
  228. e.Node.ForeColor = treeView1.ForeColor; // 恢复默认文字颜色
  229. }
  230. // 2. 更新所有祖先节点的状态(部分选中 or 全选/全不选)
  231. UpdateParentCheckState(e.Node.Parent);
  232. }
  233. finally
  234. {
  235. isUpdating = false;
  236. }
  237. }
  238. // 递归设置所有子节点状态
  239. private void SetChildNodesChecked(TreeNode node, bool isChecked)
  240. {
  241. foreach (TreeNode child in node.Nodes)
  242. {
  243. child.Checked = isChecked;
  244. SetChildNodesChecked(child, isChecked);
  245. }
  246. }
  247. // 递归更新父节点状态
  248. private void UpdateParentCheckState(TreeNode parentNode)
  249. {
  250. if (parentNode == null) return;
  251. bool allChecked = true;
  252. bool allUnchecked = true;
  253. foreach (TreeNode child in parentNode.Nodes)
  254. {
  255. if (child.Checked)
  256. allUnchecked = false;
  257. else
  258. allChecked = false;
  259. }
  260. if (allChecked)
  261. parentNode.Checked = true;
  262. else if (allUnchecked)
  263. parentNode.Checked = false;
  264. else
  265. parentNode.Checked = false; // 逻辑上是“部分选中”,但 CheckBox 只能显示 false
  266. // 👇 修复:明确根据状态设置颜色
  267. if (allChecked || allUnchecked)
  268. {
  269. parentNode.ForeColor = treeView1.ForeColor; // 全选或全不选 → 正常颜色
  270. }
  271. else
  272. {
  273. parentNode.ForeColor = Color.LightGray; // 部分选中 → 灰色
  274. }
  275. // 继续向上更新祖父节点
  276. UpdateParentCheckState(parentNode.Parent);
  277. }
  278. private void btnSave_Click(object sender, EventArgs e)
  279. {
  280. SaveCurrentProfile();
  281. foreach (var item in roleProfiles)
  282. {
  283. PermissionManager.SaveRoleProfile(item.Key, item.Value);
  284. }
  285. PermissionManager.ResetPermissions();
  286. MessageBox.Show("保存完成");
  287. }
  288. }
  289. public class ControlInfo
  290. {
  291. public string NameSpace { get; set; } = "";
  292. public string FormType { get; set; } = "";
  293. public string ControlName { get; set; } = "";
  294. public string ControlType { get; set; } = "";
  295. }
  296. }