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

using System;
using DevExpress.XtraGrid.Views.Grid;
using Framework.BaseUI;
using Framework.DomainBase;
using Framework.HandlerBase;
using Framework.RPC;
using Infrastructure.Components;
using Infrastructure.Utilities;

namespace Framework.BaseDataUI
{
	[Module(Name = "公共代码", RootModule = "基础资料", Order = 2)]
	public partial class PubCodeForm : ToolbarBaseForm
	{
		public PubCodeForm()
		{
			InitializeComponent();
			this.Load += SystemCodeForm_Load;
		}

		void SystemCodeForm_Load(object sender, EventArgs e)
		{
			gridView1.OptionsBehavior.ReadOnly = false;
			gridView1.OptionsBehavior.Editable = true;

			gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
			gridView1.ValidateRow += gridView1_ValidateRow;
			treeList1.FocusedNodeChanged += treeList1_FocusedNodeChanged;
			btnDelete.ButtonClick += btnDelete_ButtonClick;

			InitCodeType();
		}

		private void InitCodeType()
		{
			foreach (string s in Rpc.Create<PubCodeHandler>().GetNames())
			{
				if (!string.IsNullOrWhiteSpace(s))
				{
					treeList1.AppendNode(new object[] { s }, -1);
				}
			}
		}

		public string CurrentCodeType
		{
			get
			{
				return treeList1.FocusedNode == null ? "" : treeList1.FocusedNode[0].ToString();
			}
		}

		void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
		{
			string codeType = e.Node[0].ToString();
			bindingSource1.DataSource = Rpc.Create<PubCodeHandler>().QueryByType(codeType);
		}

		void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
		{
			PubCode code = (PubCode)gridView1.GetRow(e.RowHandle);
			if (gridView1.IsNewItemRow(e.RowHandle))
			{
				code.CodeId = Guid.NewGuid();
				code.CodeType = CurrentCodeType;
				code.SeqNo = gridView1.RowCount + 1;
			}

			DataValidator dv = new DataValidator()
			   .Check(string.IsNullOrWhiteSpace(code.CodeName), "请填写代码内容");

			if (!dv.Pass)
			{
				e.ErrorText = dv.Content;
				e.Valid = false;
			}
			else
			{
				Rpc.Create<PubCodeHandler>().Save(code);
			}
		}

		void btnDelete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
		{
			PubCode systemCode = (PubCode)gridView1.GetFocusedRow();
			Rpc.Create<PubCodeHandler>().Delete(systemCode);
			gridView1.RemoveCurrentRow();
		}

	}
}
