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

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.Utils;
using DevExpress.XtraBars;
using Framework.BaseUI;
using Framework.DomainBase;
using Framework.HandlerBase;
using Framework.RPC;
using Framework.ViewPortal;
using Infrastructure.Components;
using Infrastructure.Utilities;

namespace Framework.MainUI
{
	//[DebuggerStepThrough]
	public partial class MainForm : BaseForm, IMainForm
	{
		private MainMenu _MainMenu;

		#region Public Property

		public Type InstanceType
		{
			get
			{
				return typeof(MainForm);
			}
		}

		public IList<IBaseForm> FormList
		{
			get;
			private set;
		}

		public int OpenFormsCount
		{
			get
			{
				int count = 0;

				foreach (IBaseForm view in FormList)
				{
					if (object.ReferenceEquals(view, this))
					{
						continue;
					}
					count++;
				}

				return count;
			}
		}

		#endregion

		public MainForm()
		{
			InitializeComponent();

			LoadIcon();

			InitUI();

			this.Load += MainForm_Load;
			this.Shown += new EventHandler(MainForm_Shown);
			this.FormClosing += MainForm_FormClosing;
		}

		//菜单必须在构造函数中创建，否则不显示，或者有延迟。
		private void InitUI()
		{
			List<PermissionAction> actionList = null;
			if (PermissionManager.Instance.RoleType.IsNullOrEmpty())
			{
				actionList = Rpc.Create<PermissionHandler>().QueryActionByUser(ClientContext.User.Id);
			}
			else
			{
				actionList = Rpc.Create<PermissionHandler>().QueryActionByUser(ClientContext.User.Id, PermissionManager.Instance.RoleType);
			}

			PermissionManager.Instance.Add(actionList.Select(a => a.Action));

			SkinStyle skinStyle = Rpc.Create<SkinStyleHandler>().Get();
			ClientContext.SkinName = skinStyle.StyleName;
			ClientContext.FontName = skinStyle.FontName;
			ClientContext.FontSize = skinStyle.FontSize.GetValueOrDefault();

			UserLookAndFeel.Default.Style = LookAndFeelStyle.Skin;
			UserLookAndFeel.Default.SkinName = ClientContext.SkinName;
			Font font = new Font(ClientContext.FontName, (float)skinStyle.FontSize);
			AppearanceObject.DefaultFont = font;
			new BarAndDockingController().AppearancesBar.ItemsFont = font;

			InitMenu();
			InitShortcutButton();
		}

		void MainForm_Load(object sender, EventArgs e)
		{
			//初始化导航栏。
			ModuleProxy.Instance.TabNavManager.TabNav = tabNav;
			ModuleProxy.Instance.TabNavManager.InitTabNav(null);
			ClientContext.SystemMessageHint = new SystemMessageHint();

			this.Text = string.Format("{0} {1}", ClientContext.ApplicationName, ClientContext.ApplicationVersion);

			lblComp.Caption = ClientContext.CompanyName;
			lblDept.Caption = ClientContext.User.DeptName;
			lblUser.Caption = ClientContext.User.Account;
			btnNotify.Caption = "";
			txtServer.Caption = ClientContext.Server;

			btnNotify.ItemClick += btnNotify_ItemClick;
		}

		private void MainForm_Shown(object sender, EventArgs e)
		{
			if (ClientContext.NavigationForm != null)
			{
				if (ClientContext.NavigationForm.IsPop)
				{
					ClientContext.NavigationForm.ShowDialog();
				}
				else
				{
					ClientContext.NavigationForm.MdiParent = this;
					ClientContext.NavigationForm.WindowState = FormWindowState.Maximized;
					ClientContext.NavigationForm.Show();
					ModuleProxy.Instance.TabNavManager.Add(ClientContext.NavigationForm);
					AnalyseNavigationButton();
				}
			}

			AutoRunModule();
			ApplicationLoader.RaiseMainFormShown();

			string backgroundImage = "";
			if (File.Exists(Path.Combine(ClientContext.ApplicationPath, "BackgroundImage.jpg")))
			{
				backgroundImage = Path.Combine(ClientContext.ApplicationPath, "BackgroundImage.jpg");
			}
			else if (File.Exists(Path.Combine(ClientContext.ApplicationPath, "BackgroundImage.png")))
			{
				backgroundImage = Path.Combine(ClientContext.ApplicationPath, "BackgroundImage.png");
			}

			if (!backgroundImage.IsNullOrEmpty())
			{
				this.BackgroundImage = Image.FromFile(backgroundImage);
				this.BackgroundImageLayout = ImageLayout.Stretch;
			}

			UpgradeLogForm.Open();

			//ClientContext.TimedTask += () => ClientContext.SystemMessageHint.Open(ClientContext.Now +  "\r\ntest test test !!!");

			timer2.Tick += timer2_Tick;
			timer2.Interval = 1000 * 60;
			timer2.Start();
			timer2_Tick(null, null);
		}

		void timer2_Tick(object sender, EventArgs e)
		{
			if (ClientContext.TimedTask != null)
			{
				ClientContext.TimedTask();
			}
		}

		void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			try
			{
				if (Logout != null)
				{
					Logout();
				}

				Rpc.Create<LoginHandler>().Logout(ClientContext.SessionId);
			}
			catch (Exception ex)
			{
				Debug.Print(ex.Message);
			}
		}

		private void InitMenu()
		{
			this.BarManager.AllowCustomization = false;
			this.BarManager.AllowQuickCustomization = false;
			this.BarManager.AllowShowToolbarsPopup = false;
			this.BarManager.MdiMenuMergeStyle = BarMdiMenuMergeStyle.Never;
			ModuleProxy.Instance.MainForm = this;

			ModuleParser.Instance.AssignRunPermission(); //分配每个模块是否有运行权限
			this._MainMenu = new Framework.MainUI.MainMenu(this.bar1, MenuItemClick); //注意，生成菜单一定要在构造函数中调用，否则不会显示出来
			this._MainMenu.BuildMenuTree(ModuleParser.Instance.RootModuleList, ModuleParser.Instance.ModuleInfoList);
		}

		//菜单点击
		public void MenuItemClick(BarButtonMenu menu)
		{
			this.Cursor = Cursors.WaitCursor;
			ModuleInfo moduleInfo = ModuleParser.Instance.GetModuleInfo(menu.ClassName);
			ModuleProxy.Instance.Execute(false, moduleInfo, "", new object[] { });
			this.Cursor = Cursors.Default;
		}

		private int GetWorkingFormsCount()
		{
			int count = 0;
			foreach (Form form in System.Windows.Forms.Application.OpenForms)
			{
				if (object.ReferenceEquals(form, this))
				{
					continue;
				}
				count++;
			}

			return count;
		}

		private void AutoRunModule()
		{
			SysLocalConfig config = SysLocalConfig.Load();
			if (config == null) //如果本机定义了自动启动的模块，
			{
				return;
			}

			if (!string.IsNullOrEmpty(config.StartupModule))
			{
				ModuleProxy.Instance.Execute(config.StartupModule, "运行", null);
			}
			if (!string.IsNullOrEmpty(config.StartupModule2))
			{
				ModuleProxy.Instance.Execute(config.StartupModule2, "运行", null);
			}
			if (!string.IsNullOrEmpty(config.StartupModule3))
			{
				ModuleProxy.Instance.Execute(config.StartupModule3, "运行", null);
			}
		}

		#region 供ModuleProxy调用的函数

		public void ShowPopForm(Form form)
		{
			if (form != null && !form.Disposing && !form.IsDisposed)
			{
				if (form.FormBorderStyle.ToString().StartsWith("Sizable"))
				{
					form.MaximizeBox = true;
					form.MinimizeBox = true;
				}

				try
				{
					form.ShowDialog(this);
				}
				catch (Exception e)
				{
					MsgBox.Warning(e.Message);
				}
				finally
				{
					//如果不手动关闭，会在ModuleLoader中缓存，再次调用DestForm时，不会调用构造函数
					form.Close();
				}
			}
		}

		public void MinimizeForm()
		{
			this.WindowState = FormWindowState.Minimized;
		}

		#endregion

		private void btnClose_ItemClick(object sender, ItemClickEventArgs e)
		{
			string msg = string.Format("系统关闭后，您正在进行的工作将被终止，未保存的数据将会取消。{0}{0}您确定要关闭系统吗？", Environment.NewLine);
			if (GetWorkingFormsCount() > 0 && !MsgBox.Confirm(msg))
			{
				return;
			}
			this.Close();
		}

		public event Action Logout;

		#region - System Message -

		private void timer1_Tick(object sender, EventArgs e)
		{
			lblTime.Caption = ClientContext.Now.ToString("yyyy年MM月dd日 HH:mm:ss dddd");
		}

		void btnNotify_ItemClick(object sender, ItemClickEventArgs e)
		{
		}

		#endregion

		#region - Shortcut Button -

		private void InitShortcutButton()
		{
			//List<ShortcutToolbar> list = Rpc.Create<ShortcutToolbarHandler>().QueryByUser(ClientContext.User.Id);
			//if (!list.Any())
			//{
			//	bar2.Visible = false;
			//	return;
			//}

			//foreach (ShortcutToolbar button in list)
			//{
			//	ModuleInfo module = ModuleParser.Instance.GetModuleInfoByModuleName(button.Module);
			//	CreateShortcutToolbarButton(module);
			//}
		}

		public void AddShortcutButton(ModuleInfo module)
		{
			Rpc.Create<ShortcutToolbarHandler>().Add(module.Attribute.Name);
			CreateShortcutToolbarButton(module);
		}

		public void RemoveShortcutButton(ModuleInfo module)
		{
			//Rpc.Create<ShortcutToolbarHandler>().Remove(module.Attribute.Name);

			//BarButtonItem foundButton = null;
			//foreach (LinkPersistInfo button in bar2.LinksPersistInfo)
			//{
			//	if (button.Item.Tag.ToString() == module.Attribute.Name)
			//	{
			//		foundButton = (BarButtonItem)button.Item;
			//		break;
			//	}
			//}

			//if (foundButton != null)
			//{
			//	BarManager.Items.Remove(foundButton);
			//}
		}

		private void CreateShortcutToolbarButton(ModuleInfo module)
		{
			//if (module == null)
			//{
			//	return;
			//}

			//string[] names = module.Attribute.Name.SplitArray('.');

			//((System.ComponentModel.ISupportInitialize)(this.BarManager)).BeginInit();
			//BarButtonItem button = new BarButtonItem();
			//button.Caption = names[names.Length - 1];
			//button.ImageIndex = 1;
			//button.PaintStyle = BarItemPaintStyle.CaptionGlyph;
			//button.Tag = module.Attribute.Name;
			//button.ItemClick += button_ItemClick;
			//BarManager.Items.Add(button);
			//bar2.AddItem(button);
			//((System.ComponentModel.ISupportInitialize)(this.BarManager)).EndInit();
		}

		void button_ItemClick(object sender, ItemClickEventArgs e)
		{
			if (PermissionManager.Instance.HasPermission(e.Item.Tag.ToString(), "运行"))
			{
				ModuleProxy.Instance.Execute(e.Item.Tag.ToString(), "运行", null);
			}
			else
			{
				MsgBox.Show("您没有运行 {0} 的权限", e.Item.Tag.ToString());
			}
		}

		#endregion

		private void LoadIcon()
		{
			string path = Path.Combine(ClientContext.ApplicationPath, "client.ico");
			if (File.Exists(path))
			{
				this.Icon = new Icon(path);
			}
		}

		void AnalyseNavigationButton()
		{
			List<Control> btnList = new List<Control>();
			ControlUtil.FindChildren((Control)ClientContext.NavigationForm, btnList);

			foreach (Control c in btnList)
			{
				if (c is INavigationButton)
				{
					c.Click += NavigationButton_Click;
				}
			}
		}

		void NavigationButton_Click(object sender, EventArgs e)
		{
			INavigationButton btn = sender as INavigationButton;
			if (!string.IsNullOrEmpty(btn.Module))
			{
				ModuleInfo module = ModuleParser.Instance.GetModuleInfoByModuleName(btn.Module);
				if (module != null)
				{
					string action = string.IsNullOrEmpty(btn.Action) ? "运行" : btn.Action;
					ModuleProxy.Instance.ShowForm(true, module, action, null);
				}
			}
			else if (!string.IsNullOrEmpty(btn.Class))
			{
				Type type = Type.GetType(btn.Class);
				if (type != null)
				{
					ModuleProxy.Instance.ShowForm(type);
				}
			}
		}

	}
}