//==============================================================
//  版权所有：深圳杰文科技
//  文件名：PermissionRoleForm.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：Jay
//  修改时间：2018-3-5 11:03
//  修改说明： 增加数据权限分类。
//==============================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Nodes;
using Framework.BaseUI;
using Framework.Common;
using Framework.DomainBase;
using Framework.HandlerBase;
using Framework.RPC;
using Infrastructure.Components;
using Infrastructure.Utilities;

namespace Framework.SystemUI
{
	[Module(Name = "系统权限", RootModule = "系统管理", SystemModule = true)]
	public partial class PermissionRoleForm : ToolbarBaseForm
	{
		public PermissionRoleForm()
		{
			InitializeComponent();
			this.Load += PermissionRoleForm_Load;
		}

		void PermissionRoleForm_Load(object sender, EventArgs e)
		{
			this.SetStyle();
			gridControl2.EditOnly(colDeleteUser);

			this.Shown += PermissionRoleForm_Shown;
			bsRole.CurrentChanged += bsRole_CurrentChanged;
			bsRole.DataSource = Rpc.Create<PermissionHandler>().QueryRole();
			btnDeleteUser.ButtonClick += btnDeleteUser_ButtonClick;
			chkOnlySelf.CheckedChanged += chkOnlySelf_CheckedChanged;
			chkDepts.CheckedChanged += chkDepts_CheckedChanged;
			chkAll.CheckedChanged += chkAll_CheckedChanged;
		}

		void PermissionRoleForm_Shown(object sender, EventArgs e)
		{
			treeList1.BeginUpdate();

			InitActionTree();
			InitDataTree();

			if (CurrentRole != null)
			{
				PermissionRole role = Rpc.Create<PermissionHandler>().GetRoleWithItem(CurrentRole.RoleId, "部门");
				UpdateActionTree(role.Actions);
				//UpdateDataTree(role.Data);
			}

			treeList1.EndUpdate();
		}

		private PermissionRole CurrentRole
		{
			get
			{
				return bsRole.GetCurrent<PermissionRole>();
			}
		}

		void bsRole_CurrentChanged(object sender, EventArgs e)
		{
			if (CurrentRole == null)
			{
				return;
			}

			PermissionRole role = Rpc.Create<PermissionHandler>().GetRoleWithItem(CurrentRole.RoleId, "部门");
			UpdateActionTree(role.Actions);
			UpdateDataTree(role.Data);
			bsUser.DataSource = role.Users;
		}

		[Action(Name = "新增角色")]
		private void Add()
		{
			PermissionRoleEditForm form = new PermissionRoleEditForm();
			form.Shown += delegate
			{
				form.Add();
			};
			if (form.ShowDialog() == DialogResult.OK)
			{
				bsRole.Add(form.Current);
			}
		}

		[Action(Name = "修改角色")]
		private void Modify()
		{
			if (this.CurrentRole == null)
			{
				return;
			}

			PermissionRoleEditForm form = new PermissionRoleEditForm();
			form.Shown += delegate
			{
				form.Modify(CurrentRole);
			};
			if (form.ShowDialog() == DialogResult.OK)
			{
				bsRole.ReplaceCurrent(form.Current);
			}
		}

		//[Action(Name = "删除角色")]
		//private void Delete()
		//{
		//	if (this.CurrentRole == null)
		//	{
		//		return;
		//	}
		//	if (!MsgBox.Confirm("您确定要删除角色 {0} ？", this.CurrentRole.RoleName))
		//	{
		//		return;
		//	}
		//	Rpc.Create<PermissionHandler>().Delete(this.CurrentRole);
		//	bsRole.RemoveCurrent();
		//}

		[Action(Name = "选择用户", Image = Toolbar.usergroup, Permission = false)]
		private void SelectUser()
		{
			List<PermissionRoleUser> userList = bsUser.DataSource as List<PermissionRoleUser>;
			IEnumerable<Employee> users = SelectMultiEmployeeForm.GetUser();
			foreach (Employee emp in users)
			{
				if (userList.Exists(a => a.UserId == emp.EmpId))
				{
					continue;
				}

				PermissionRoleUser user = new PermissionRoleUser()
				{
					Id = Guid.NewGuid(),
					UserId = emp.EmpId,
					RoleId = CurrentRole.RoleId,
					EmpName = emp.EmpName,
					EmpNo = emp.EmpNo
				};
				userList.Add(user);
			}
			bsUser.DataSource = userList;
			bsUser.ResetBindings(false);
		}

		[Action(Name = "保存", Permission = false)]
		private void Save()
		{
			this.EndEdit();

			CurrentRole.Actions = GetSelectedAction();
			CurrentRole.Data = GetSelectedData();
			CurrentRole.Users = bsUser.DataSource as List<PermissionRoleUser>;

			if (chkAll.Checked)
			{
				CurrentRole.DataPermissionType = DataPermissionTypes.全部;
			}
			else if (chkDepts.Checked)
			{
				CurrentRole.DataPermissionType = DataPermissionTypes.部门;
			}
			else
			{
				CurrentRole.DataPermissionType = DataPermissionTypes.自己;
			}

			Rpc.Create<PermissionHandler>().SaveWithItem(CurrentRole);

			MsgBox.Show("保存成功");
		}

		#region - Init Tree -

		private void InitActionTree()
		{
			List<PermissionActionNode> list = new List<PermissionActionNode>();
			foreach (RootModuleAttribute rootModule in ModuleParser.Instance.RootModuleList)
			{
				PermissionActionNode rootNode = new PermissionActionNode()
				{
					Id = rootModule.Name,
					ParentId = null,
					IsSelected = false,
					Name = rootModule.Name,
					NodeTypeId = PermissionActionNode.NodeType.Root
				};
				list.Add(rootNode);
			}

			foreach (ModuleInfo moduleInfo in ModuleParser.Instance.ModuleInfoList)
			{
				if (!moduleInfo.Attribute.Permission || moduleInfo.Attribute.Fix || !moduleInfo.Attribute.ShowInMenu)
				{
					continue;
				}

				string rootModuleName = moduleInfo.Attribute.RootModule;
				if (string.IsNullOrEmpty(rootModuleName))
				{
					string[] str = moduleInfo.Attribute.Name.SplitArray('.');
					rootModuleName = str[0];
				}

				PermissionActionNode moduleNode = new PermissionActionNode()
				{
					Id = moduleInfo.Attribute.Name,
					ParentId = rootModuleName,
					IsSelected = false,
					Name = moduleInfo.Attribute.Name.Replace(rootModuleName + ".", ""),
					NodeTypeId = PermissionActionNode.NodeType.Module
				};

				if (list.Exists(a => a.Id == moduleNode.Id))
				{
					throw new Exception(string.Format("模块名称重复：{0}", moduleNode.Id));
				}

				list.Add(moduleNode);

				PermissionActionNode runNode = new PermissionActionNode()
				{
					Id = moduleNode.Id + ".运行",
					IsSelected = false,
					Name = "运行",
					NodeTypeId = PermissionActionNode.NodeType.Action,
					ParentId = moduleNode.Id
				};
				list.Add(runNode);

				foreach (ActionAttribute actionAttribute in ModuleParser.Instance.GetActionList(moduleInfo))
				{
					if (!actionAttribute.Permission)
					{
						continue;
					}

					if (list.Exists(a => a.Id == moduleNode.Id + "." + actionAttribute.Name))
					{
						continue;
					}

					PermissionActionNode actionNode = new PermissionActionNode()
					{
						Id = moduleNode.Id + "." + actionAttribute.Name,
						ParentId = moduleNode.Id,
						NodeTypeId = PermissionActionNode.NodeType.Action,
						Name = actionAttribute.Name,
						IsSelected = false,
					};
					list.Add(actionNode);
				}
			}

			bsAction.DataSource = list;
		}

		private void InitDataTree()
		{
			var list = Rpc.Create<OrgHandler>().GetOrgTreeWithoutGroup();
			bsOrg.DataSource = list;
			treOrg.ExpandAll();
		}

		#endregion

		#region - Update Tree -

		private void UpdateActionTree(IEnumerable<PermissionAction> actions)
		{
			treeList1.BeginUpdate();

			//更新权限子节点。
			treeList1.NodesIterator.DoOperation(node =>
			{
				PermissionActionNode actionNode = (PermissionActionNode)treeList1.GetDataRecordByNode(node);
				if (actions.Count(a => a.Action == actionNode.Id) > 0)
				{
					node.Checked = true;
				}
				else
				{
					node.Checked = false;
				}
			});

			//更新模块节点。
			treeList1.NodesIterator.DoOperation(node =>
			{
				PermissionActionNode actionNode = (PermissionActionNode)treeList1.GetDataRecordByNode(node);
				if (actionNode.NodeTypeId == PermissionActionNode.NodeType.Module)
				{
					UpdateNodeCheckState(node);
				}
			});

			//更新根菜单节点。
			treeList1.NodesIterator.DoOperation(node =>
			{
				PermissionActionNode actionNode = (PermissionActionNode)treeList1.GetDataRecordByNode(node);
				if (actionNode.NodeTypeId == PermissionActionNode.NodeType.Root)
				{
					UpdateNodeCheckState(node);
				}
			});

			treeList1.EndUpdate();
		}

		private void UpdateNodeCheckState(TreeListNode node)
		{
			int checkedCount = 0;
			int indeterminateCount = 0;
			int uncheckedCount = 0;
			foreach (TreeListNode childNode in node.Nodes)
			{
				switch (childNode.CheckState)
				{
					case CheckState.Checked:
						checkedCount++;
						break;
					case CheckState.Indeterminate:
						indeterminateCount++;
						break;
					case CheckState.Unchecked:
						uncheckedCount++;
						break;
				}
			}
			if (indeterminateCount > 0)
			{
				node.CheckState = CheckState.Indeterminate;
			}
			else if (checkedCount > 0 && uncheckedCount == 0 && indeterminateCount == 0)
			{
				node.Checked = true;
			}
			else if (checkedCount > 0 && uncheckedCount > 0)
			{
				node.CheckState = CheckState.Indeterminate;
			}
			else
			{
				node.Checked = false;
			}
		}

		private void UpdateDataTree(IEnumerable<PermissionData> list)
		{
			switch (CurrentRole.DataPermissionType)
			{
				case DataPermissionTypes.无:
				case DataPermissionTypes.全部:
					chkAll.Checked = true;
					treOrg.OptionsView.ShowCheckBoxes = false;
					break;
				
				case DataPermissionTypes.自己:
					chkOnlySelf.Checked = true;
					treOrg.OptionsView.ShowCheckBoxes = false;
					break;
				
				case DataPermissionTypes.部门:
					chkDepts.Checked = true;
					treOrg.OptionsView.ShowCheckBoxes = true;
					break;
			}

			treOrg.BeginUpdate();

			treOrg.NodesIterator.DoOperation(node =>
			{
				Org org = (Org)treOrg.GetDataRecordByNode(node);
				node.Checked = list.Any(a => a.Data == org.Id.ToString());
			});

			treOrg.EndUpdate();
		}

		#endregion

		#region - Get Selected Node -

		private List<PermissionAction> GetSelectedAction()
		{
			List<PermissionAction> list = new List<PermissionAction>();

			treeList1.NodesIterator.DoOperation(node =>
			{
				if (node.Checked)
				{
					PermissionActionNode actionNode = (PermissionActionNode)treeList1.GetDataRecordByNode(node);
					if (actionNode.NodeTypeId == PermissionActionNode.NodeType.Action)
					{
						PermissionAction action = new PermissionAction()
						{
							ActionId = Guid.NewGuid(),
							Action = actionNode.Id,
							RoleId = CurrentRole.RoleId
						};
						list.Add(action);
					}
				}
			});

			return list;
		}

		private List<PermissionData> GetSelectedData()
		{
			List<PermissionData> list = new List<PermissionData>();

			treOrg.NodesIterator.DoOperation(node =>
			{
				if (node.Checked)
				{
					Org org = (Org)treOrg.GetDataRecordByNode(node);
					PermissionData data = new PermissionData()
					{
						DataId = Guid.NewGuid(),
						Data = org.Id.ToString(),
						DataType = "部门",
						RoleId = CurrentRole.RoleId,
					};
					list.Add(data);
				}
			});

			return list;
		}

		#endregion

		void btnDeleteUser_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			bsUser.RemoveCurrent();
		}

		void chkOnlySelf_CheckedChanged(object sender, EventArgs e)
		{
			treOrg.OptionsView.ShowCheckBoxes = false;
		}

		void chkDepts_CheckedChanged(object sender, EventArgs e)
		{
			treOrg.OptionsView.ShowCheckBoxes = true;
		}

		void chkAll_CheckedChanged(object sender, EventArgs e)
		{
			treOrg.OptionsView.ShowCheckBoxes = false;
		}
	}
}
