//==============================================================
//  版权所有：深圳杰文科技
//  文件名：OrgForm.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraReports.UI;
using DevExpress.XtraTab;
using Framework.BaseUI;
using Framework.DomainBase;
using Framework.HandlerBase;
using Framework.RPC;
using Infrastructure.Components;
using Infrastructure.Utilities;

namespace Framework.SystemUI
{
	[Module(Name = "组织结构", RootModule = "基础资料", Order = 1)]
	public partial class OrgForm : ToolbarBaseForm
	{
		private ContainerController cc = new ContainerController();

		public OrgForm()
		{
			InitializeComponent();
			this.Load += DeptForm_Load;
		}

		void DeptForm_Load(object sender, EventArgs e)
		{
			if (this.DesignMode)
			{
				return;
			}

			InitToolbarButton();

			this.SetStyle();
			gridControl2.EditOnly(colDeleteGroupEmployee);

			cmbDeptType.AddEnum<Dept.DeptTypes>();

			cc.ReadOnlyChanged += r =>
			{
				chkOnJob.Properties.ReadOnly = false;
				chkOnJob.Enabled = true;

				chkAllowLogin.Properties.ReadOnly = false;
				chkAllowLogin.Enabled = true;
			};
			cc.Init(true, this);

			this.Shown += OrgForm_Shown;
			treeList1.FocusedNodeChanged += treeList1_FocusedNodeChanged;
			edtDept.ButtonClick += edtDept_ButtonClick;
			btnModifyEmployee.ButtonClick += btnModifyEmployee_ButtonClick;
			btnDeleteEmployee.ButtonClick += btnDeleteEmployee_ButtonClick;
			btnDeleteGroupEmployee.ButtonClick += btnDeleteGroupEmployee_ButtonClick;
			txtDeptParent.ButtonClick += txtDeptParent_ButtonClick;
			btnTopDept.Click += btnTopDept_Click;
		}

		void OrgForm_Shown(object sender, EventArgs e)
		{
			RefreshData();
			treeList1.ExpandAll();
			treeList1.FocusedNode = treeList1.Nodes[0];

			cc.ReadOnly = true;
		}

		public virtual IEmployeeEditForm CreateEmployeeEditForm()
		{
			if (OrgTypes.EmployeeEditFormType == null)
			{
				string typeName = ConfigurationManager.AppSettings["EmployeeEditForm"];
				if (!string.IsNullOrEmpty(typeName))
				{
					OrgTypes.EmployeeEditFormType = Type.GetType(typeName);
				}
			}

			if (OrgTypes.EmployeeEditFormType == null)
			{
				return new EmployeeEditForm();
			}
			else
			{
				return (IEmployeeEditForm)Activator.CreateInstance(OrgTypes.EmployeeEditFormType);
			}
		}

		private void InitToolbarButton()
		{
			Toolbar.ShowOnly(RefreshData, ModifyCompany, AddDept, ModifyDept, DeleteDept, AddGroup, ModifyGroup, DeleteGroup, ImportEmployee, PrintEmployeeCard);
		}

		void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
		{
			if (e.Node == null)
			{
				return;
			}

			xtraTabControl1.BeginUpdate();
			bool focusEmployee = xtraTabControl1.SelectedTabPage == tabEmployee;
			foreach (XtraTabPage page in xtraTabControl1.TabPages)
			{
				page.PageVisible = false;
			}
			tabEmployee.PageVisible = true;

			Org org = (Org)treeList1.GetDataRecordByNode(e.Node);
			switch ((Org.NodeTypes)org.NodeType)
			{
				case Org.NodeTypes.Company:
					{
						bsCompany.DataSource = Rpc.Create<OrgHandler>().GetCompany();

						List<Employee> empList = Rpc.Create<OrgHandler>().QueryEmployee();
						if (chkOnJob.Checked)
						{
							empList = empList.Where(a => a.OnJob).ToList();
						}
						if (chkAllowLogin.Checked)
						{
							empList = empList.Where(a => a.AllowLogin).ToList();
						}
						bsEmployee.DataSource = empList;

						gridControl1.RefreshDataSource();
						tabCompany.PageVisible = true;
						xtraTabControl1.SelectedTabPage = tabCompany;
						Toolbar.ShowOnly(RefreshData, ModifyCompany, AddDept, BrowseEmployee, ModifyEmployee, ImportEmployee, PrintEmployeeCard);
						break;
					}

				case Org.NodeTypes.Dept:
					{
						Dept dept = Rpc.Create<OrgHandler>().GetDept(org.Id);
						bsDept.DataSource = dept;

						List<Employee> empList = Rpc.Create<OrgHandler>().QueryEmployeeByDept(dept.DeptId);
						if (chkOnJob.Checked)
						{
							empList = empList.Where(a => a.OnJob).ToList();
						}
						if (chkAllowLogin.Checked)
						{
							empList = empList.Where(a => a.AllowLogin).ToList();
						}
						bsEmployee.DataSource = empList;

						gridControl1.RefreshDataSource();
						tabDept.PageVisible = true;
						xtraTabControl1.SelectedTabPage = tabDept;
						Toolbar.ShowOnly(RefreshData, AddDept, ModifyDept, DeleteDept, AddGroup, BrowseEmployee, AddEmployee, ModifyEmployee, PrintEmployeeCard);
						break;
					}

				case Org.NodeTypes.Group:
					{
						DeptGroup group = Rpc.Create<OrgHandler>().GetGroupWithEmployee(org.Id);
						bsGroup.DataSource = group;
						bsGroupEmployee.DataSource = group.Employees;
						gridControl2.RefreshDataSource();

						List<Employee> empList = Rpc.Create<OrgHandler>().QueryEmployeeByGroup(group.GroupId);
						if (chkOnJob.Checked)
						{
							empList = empList.Where(a => a.OnJob).ToList();
						}
						if (chkAllowLogin.Checked)
						{
							empList = empList.Where(a => a.AllowLogin).ToList();
						}
						bsEmployee.DataSource = empList;

						gridControl1.RefreshDataSource();
						tabGroup.PageVisible = true;
						xtraTabControl1.SelectedTabPage = tabGroup;
						Toolbar.ShowOnly(RefreshData, AddGroup, ModifyGroup, DeleteGroup, BrowseEmployee, AddEmployee, ModifyEmployee, PrintEmployeeCard);
						break;
					}
			}

			if (focusEmployee)
			{
				xtraTabControl1.SelectedTabPage = tabEmployee;
			}
			xtraTabControl1.EndUpdate();

			cc.ReadOnly = true;
		}

		private void LocalTab(Org.NodeTypes nodeType)
		{
			foreach (XtraTabPage page in xtraTabControl1.TabPages)
			{
				page.PageVisible = false;
			}

			switch (nodeType)
			{
				case Org.NodeTypes.Company:
					tabCompany.PageVisible = true;
					break;

				case Org.NodeTypes.Dept:
					tabDept.PageVisible = true;
					break;

				case Org.NodeTypes.Group:
					tabGroup.PageVisible = true;
					break;

				case Org.NodeTypes.Employee:
					break;
			}
		}

		[Action(Name = "刷新", Permission = false)]
		private void RefreshData()
		{
			var list = Rpc.Create<OrgHandler>().GetOrgTree();
			bsOrg.DataSource = list;
			treeList1.ExpandAll();
		}

		[Action(Name = "修改单位", Image = "Modify")]
		private void ModifyCompany()
		{
			Org orgCompany = (Org)treeList1.GetDataRecordByNode(treeList1.Nodes[0]);
			Company company = Rpc.Create<OrgHandler>().GetCompany();
			bsCompany.DataSource = company;
			LocalTab(Org.NodeTypes.Company);
			cc.ReadOnly = false;
			Toolbar.ShowOnly(SaveCompany, Cancel);
		}

		[Action(Name = "保存", Image = "Save", Permission = false)]
		private void SaveCompany()
		{
			this.EndEdit();
			Company company = bsCompany.GetCurrent<Company>();
			Rpc.Create<OrgHandler>().Save(company);
			InitToolbarButton();
			MsgBox.Show("保存成功");
		}

		[Action(Name = "新增部门", Image = "Add", BeginGroup = true)]
		private void AddDept()
		{
			Org orgParent = treeList1.GetFocusedNode<Org>();

			Dept dept = new Dept()
			{
				DeptId = Guid.NewGuid(),
				DeptNo = "",
				DeptName = "",
				//CompanyId = orgParent.com,
				ParentId = orgParent.Id,
				ParentName = orgParent.Name,
				DeptTypeId = (int)Dept.DeptTypes.无
			};

			if (orgParent.NodeType == Org.NodeTypes.Dept)
			{
				Dept parentDept = Rpc.Create<OrgHandler>().GetDept(orgParent.Id);
				dept.CompanyId = parentDept.CompanyId;
			}
			else
			{
				dept.CompanyId = orgParent.Id;
			}

			bsDept.DataSource = dept;
			LocalTab(Org.NodeTypes.Dept);
			Toolbar.ShowOnly(SaveDept, Cancel);
			cc.ReadOnly = false;
		}

		[Action(Name = "修改部门", Image = "Modify")]
		private void ModifyDept()
		{
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);
			if (org == null || org.NodeType != Org.NodeTypes.Dept)
			{
				MsgBox.Show("请选择要修改的部门");
				return;
			}

			Dept dept = Rpc.Create<OrgHandler>().GetDept(org.Id);
			bsDept.DataSource = dept;
			Toolbar.ShowOnly(SaveDept, Cancel);
			LocalTab(Org.NodeTypes.Dept);
			cc.ReadOnly = false;
		}

		[Action(Name = "删除部门", Image = "Delete")]
		private void DeleteDept()
		{
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);
			if (org == null || org.NodeType != Org.NodeTypes.Dept)
			{
				MsgBox.Show("请选择要删除的部门");
				return;
			}

			if (!MsgBox.Confirm("您确定要删除部门 {0}？", org.Name))
			{
				return;
			}

			Rpc.Create<OrgHandler>().DeleteDept(org.Id);
			treeList1.Nodes.Remove(treeList1.FocusedNode);
		}

		[Action(Name = "保存", Image = "Save", Permission = false)]
		private void SaveDept()
		{
			this.EndEdit();
			Dept dept = bsDept.GetCurrent<Dept>();

			if (!new DataValidator()
				.Check(string.IsNullOrEmpty(dept.DeptNo), "请填写部门编号")
				.Check(string.IsNullOrEmpty(dept.DeptName), "请填写部门名称")
				.ShowMsgIfFailed()
				.Pass)
			{
				return;
			}

			Rpc.Create<OrgHandler>().Save(dept);

			InitToolbarButton();
			RefreshData();
			LocalNode(dept.DeptId);
			MsgBox.Show("保存成功");
		}

		[Action(Name = "新增小组", Image = "Add", BeginGroup = true)]
		private void AddGroup()
		{
			Org orgDept = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);
			if (orgDept.NodeType != Org.NodeTypes.Dept)
			{
				orgDept = null;
			}

			DeptGroup group = new DeptGroup()
			{
				DeptId = orgDept == null ? Guid.Empty : orgDept.Id,
				DeptName = orgDept == null ? "" : orgDept.Name,
				GroupId = Guid.NewGuid(),
			};
			bsGroup.DataSource = group;
			bsGroupEmployee.DataSource = group.Employees;

			LocalTab(Org.NodeTypes.Group);
			Toolbar.ShowOnly(SaveGroup);
			cc.ReadOnly = false;
		}

		[Action(Name = "修改小组", Image = "Modify")]
		private void ModifyGroup()
		{
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);
			if (org == null || org.NodeType != Org.NodeTypes.Group)
			{
				MsgBox.Show("请选择要修改的小组");
				return;
			}

			DeptGroup group = Rpc.Create<OrgHandler>().GetGroup(org.Id);
			bsGroup.DataSource = group;
			Toolbar.ShowOnly(SaveGroup, SelectEmployee, Cancel);
			LocalTab(Org.NodeTypes.Group);
			cc.ReadOnly = false;
		}

		[Action(Name = "取消", Permission = false)]
		private void Cancel()
		{
			cc.ReadOnly = true;
			InitToolbarButton();
			RefreshData();
		}

		[Action(Name = "选择小组成员", Image = "UserGroup", Permission = false)]
		private void SelectEmployee()
		{
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);

			var list = bsGroupEmployee.DataSource as List<DeptGroupEmployee>;
			foreach (Employee emp in SelectMultiEmployeeForm.Get())
			{
				if (list.Exists(a => a.EmpId == emp.EmpId))
				{
					continue;
				}

				DeptGroupEmployee groupEmp = new DeptGroupEmployee()
				{
					Id = Guid.NewGuid(),
					EmpId = emp.EmpId,
					EmpName = emp.EmpName,
					EmpNo = emp.EmpNo,
					GroupId = org.Id,
					GroupName = org.Name
				};
				bsGroupEmployee.Add(groupEmp);
			}
		}

		[Action(Name = "删除小组", Image = "Delete")]
		private void DeleteGroup()
		{
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);
			if (org == null || org.NodeType != Org.NodeTypes.Group)
			{
				MsgBox.Show("请选择要删除的小组");
				return;
			}

			if (!MsgBox.Confirm("您确定要删除小组 {0}？", org.Name))
			{
				return;
			}

			Rpc.Create<OrgHandler>().DeleteGroup(org.Id);
			treeList1.Nodes.Remove(treeList1.FocusedNode);
		}

		[Action(Name = "保存", Image = "Save", Permission = false)]
		private void SaveGroup()
		{
			this.EndEdit();
			DeptGroup group = bsGroup.GetCurrent<DeptGroup>();

			if (!new DataValidator()
				.Check(group.DeptId == Guid.Empty, "请选择小组所属部门")
				.Check(string.IsNullOrEmpty(group.GroupName), "请填写小组名称")
				.ShowMsgIfFailed()
				.Pass)
			{
				return;
			}

			List<DeptGroupEmployee> empList = bsGroupEmployee.DataSource as List<DeptGroupEmployee>;
			Rpc.Create<OrgHandler>().Save(group, empList);

			InitToolbarButton();
			RefreshData();
			LocalNode(group.GroupId);
			MsgBox.Show("保存成功");
		}

		[Action(Name = "浏览员工", Image = "Browse", BeginGroup = true)]
		private void BrowseEmployee()
		{
			Employee emp = (Employee)gvEmployee.GetFocusedRow();
			if (emp == null)
			{
				MsgBox.Show("请选择员工");
				return;
			}

			IEmployeeEditForm form = CreateEmployeeEditForm();
			form.Shown += delegate
			{
				form.Browse(emp);
			};
			if (form.ShowDialog() == DialogResult.OK)
			{
				bsEmployee.Insert(0, form.Employee);
			}
		}

		[Action(Name = "新增员工", Image = "Add")]
		private void AddEmployee()
		{
			Dept dept = null;
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.FocusedNode);
			if (org.NodeType == Org.NodeTypes.Dept)
			{
				dept = Rpc.Create<OrgHandler>().GetDept(org.Id);
			}

			IEmployeeEditForm form = CreateEmployeeEditForm();
			form.Shown += delegate
			{
				form.Add(dept);
			};
			if (form.ShowDialog() == DialogResult.OK)
			{
				bsEmployee.Insert(0, form.Employee);
			}
		}

		[Action(Name = "修改员工", Image = "Modify")]
		private void ModifyEmployee()
		{
			Employee emp = (Employee)gvEmployee.GetFocusedRow();
			if (emp == null)
			{
				MsgBox.Show("请选择员工");
				return;
			}

			IEmployeeEditForm form = CreateEmployeeEditForm();
			form.Shown += delegate
			{
				form.Modify(emp);
			};
			if (form.ShowDialog() == DialogResult.OK)
			{
				bsEmployee.ReplaceCurrent(form.Employee);
			}
		}

		[Action(Name = "导入员工", Image = "import")]
		private void ImportEmployee()
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.Filter = "Excel文档|*.xls;*.xlsx|所有文档|*.*";
			if (dialog.ShowDialog() != DialogResult.OK)
			{
				return;
			}

			DataTable table = ExcelHelper.ReadTable(dialog.FileName);

			List<Employee> list = new List<Employee>();
			foreach (DataRow row in table.Rows)
			{
				if (string.IsNullOrEmpty(row["工号"].ToString()) && string.IsNullOrEmpty(row["姓名"].ToString()) && string.IsNullOrEmpty(row["部门"].ToString()))
				{
					continue;
				}

				list.Add(new Employee()
				{
					EmpNo = row["工号"].ToString(),
					EmpName = row["姓名"].ToString(),
					DeptName = row["部门"].ToString(),
				});
			}

			Rpc.Create<OrgHandler>().ImportEmployee(list);
			MsgBox.Show("导入完毕");
		}

		private void LocalNode(Guid id)
		{
			treeList1.NodesIterator.DoOperation(node =>
			{
				Org org = (Org)treeList1.GetDataRecordByNode(node);
				if (org.Id == id)
				{
					treeList1.FocusedNode = node;
					return;
				}
			});
		}

		void edtDept_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			Dept dept = SelectDeptForm.Get();
			if (dept != null)
			{
				DeptGroup group = bsGroup.GetCurrent<DeptGroup>();
				group.DeptId = dept.DeptId;
				group.DeptName = dept.DeptName;
				bsGroup.ResetCurrentItem();
			}
		}

		void btnDeleteEmployee_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			Employee emp = bsEmployee.GetCurrent<Employee>();
			if (!MsgBox.Confirm("您确定要删除员工 {0} ？", emp.EmpName))
			{
				return;
			}

			Rpc.Create<OrgHandler>().DeleteEmployee(emp);
		}

		void btnModifyEmployee_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			Employee emp = bsEmployee.GetCurrent<Employee>();
			EmployeeEditForm form = new EmployeeEditForm();
			form.Shown += delegate
			{
				form.Modify(emp);
			};
			if (form.ShowDialog() == DialogResult.OK)
			{
				bsEmployee.ReplaceCurrent(form.Employee);
			}
		}

		void btnDeleteGroupEmployee_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			gridView2.DeleteRow(gridView2.FocusedRowHandle);
		}

		void txtDeptParent_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			Dept dept = SelectDeptForm.Get();
			if (dept == null)
			{
				return;
			}

			Dept currentDept = bsDept.GetCurrent<Dept>();
			currentDept.ParentId = dept.DeptId;
			currentDept.ParentName = dept.DeptName;
			currentDept.CompanyId = dept.CompanyId;
			bsDept.ResetCurrentItem();
		}

		void btnTopDept_Click(object sender, EventArgs e)
		{
			Org org = (Org)treeList1.GetDataRecordByNode(treeList1.Nodes[0]);
			if (org.NodeType == Org.NodeTypes.Company)
			{
				Dept dept = bsDept.GetCurrent<Dept>();
				dept.ParentId = org.Id;
				dept.CompanyId = org.Id;
				dept.ParentName = org.Name;
				bsDept.ResetCurrentItem();
			}
		}

		[Action(Name = "打印员工卡", Image = Toolbar.print)]
		private void PrintEmployeeCard()
		{
			if (OrgTypes.EmployeeCardReportType == null)
			{
				MsgBox.Show("未发现员工卡报表");
				return;
			}

			Employee emp = gvEmployee.GetCurrent<Employee>();
			if (emp == null)
			{
				MsgBox.Show("请选择员工");
				return;
			}

			XtraReport report = (XtraReport)Activator.CreateInstance(OrgTypes.EmployeeCardReportType);
			((IEmployeeCardReport)report).InitData(emp);
			//report.Show();
			ReportExt.Show(report);
		}
	}
}
