//==============================================================
//  版权所有：深圳杰文科技
//  文件名：LoginForm.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2018-05-05 17:48
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using Framework.BaseUI;
using Framework.HandlerBase;
using Framework.RPC;
using Infrastructure.Components;
using Infrastructure.Utilities;

namespace Framework.MainUI
{
	public partial class LoginForm : BaseForm
	{
		public LoginForm()
		{
			InitializeComponent();
			this.Load += LoginForm_Load;
			this.Shown += new EventHandler(LoginForm_Shown);
		}

		void LoginForm_Load(object sender, EventArgs e)
		{
			LoadLogo();
		}

		void LoginForm_Shown(object sender, EventArgs e)
		{
			txtPassword.KeyDown += txtPassword_KeyDown;
			cmbServer.SelectedIndexChanged += cmbServer_SelectedIndexChanged;

			Init();

			if (string.IsNullOrEmpty(txtAccount.Text))
			{
				txtAccount.Focus();
			}
			else if (string.IsNullOrEmpty(txtPassword.Text))
			{
				txtPassword.Focus();
			}
			else
			{
				btnLogin.Focus();
			}
		}

		void cmbServer_SelectedIndexChanged(object sender, EventArgs e)
		{
			Rpc.Url = cmbServer.GetSelectedValue<string>();
		}

		private void Init()
		{
			//从升级配置文件（Upgrade.config）中读取版本信息。
			UpgradeConfig upgradeConfig = UpgradeConfig.Load();
			if (upgradeConfig.VersionNo > 0)
			{
				string versionNo = upgradeConfig.VersionNo.ToString();
				ClientContext.ApplicationVersion = string.Format("{0}.{1}.{2}", ClientContext.ApplicationVersion, versionNo.Substring(4, 4), versionNo.Substring(8, 4));
			}

			lblTitle.Text = ClientContext.ApplicationName;
			lblVersion.Text = ClientContext.ApplicationVersion;
			lblCompany.Text = ClientContext.CompanyName;

			foreach (KeyValuePair<string, string> kvp in ClientConfig.LoadServers())
			{
				cmbServer.Add(kvp.Key, kvp.Value);
			}

			ClientConfig clientConfig = ClientConfig.Load();
			if (clientConfig == null)
			{
				clientConfig = new ClientConfig();
			}

			if (string.IsNullOrEmpty(clientConfig.Server))
			{
				cmbServer.SelectedIndex = 0;
			}
			else
			{
				for (int i = 0; i < cmbServer.Properties.Items.Count; i++)
				{
					ImageComboBoxItem item = cmbServer.Properties.Items[i];
					if (item.Description == clientConfig.Server)
					{
						cmbServer.SelectedIndex = i;
						break;
					}
				}
			}

			string password = "";
			string url = "";

			if (!string.IsNullOrEmpty(ClientContext.UsbkeyAccount)) //如果是用U盾登录；
			{
				clientConfig.LoginAccount = ClientContext.UsbkeyAccount;
				password = ClientContext.UsbkeyPassword;
			}
			else
			{
				SysLocalConfig localConfig = SysLocalConfig.Load();
				if (localConfig != null) //如果有设置自动登录；
				{
					string[] cmd = Environment.GetCommandLineArgs();
					if (cmd.Length < 2 || cmd[1] != "noautologin") //如果没有强制指定不自动登录；
					{
						if (!string.IsNullOrEmpty(localConfig.LoginAccount))
						{
							clientConfig.LoginAccount = localConfig.LoginAccount;
						}
						if (!string.IsNullOrEmpty(localConfig.Password))
						{
							password = Encrypt.DesDecrype("12345678", "87654321", localConfig.Password);
						}
					}
				}

				if (string.IsNullOrEmpty(password))
				{
					string[] cmd = Environment.GetCommandLineArgs();
					if (cmd.Length >= 2)
					{
						clientConfig.LoginAccount = cmd[1] == "noautologin" ? "" : cmd[1];
					}
					if (cmd.Length >= 3)
					{
						password = cmd[2];
					}
					if (cmd.Length >= 4)
					{
						url = cmd[3];
					}
				}
			}

			Init(clientConfig.LoginAccount, password, url);
		}

		public void Init(string account, string password, string serverName)
		{
			this.Account = account;
			this.Password = password;
			this.Server = serverName;

			if (!string.IsNullOrEmpty(this.Account) && !string.IsNullOrEmpty(this.Password) && !string.IsNullOrEmpty(this.Server))
			{
				btnLogin.PerformClick();
			}
		}

		public string Account
		{
			get
			{
				return txtAccount.Text;
			}
			set
			{
				txtAccount.Text = value;
			}
		}

		public string Password
		{
			get
			{
				return txtPassword.Text;
			}
			set
			{
				txtPassword.Text = value;
			}
		}

		public string Server
		{
			get
			{
				return cmbServer.Text;
			}
			set
			{
				foreach (ImageComboBoxItem item in cmbServer.Properties.Items)
				{
					if (item.Description == value)
					{
						cmbServer.SelectedItem = item;
						break;
					}
				}
			}
		}

		protected virtual bool Login(bool compulsory)
		{
			if (!ValidateData())
			{
				return false;
			}

			Thread.Sleep(300);

			string hostName = Dns.GetHostName();
			try
			{
				ClientContext.User = Rpc.Create<LoginHandler>().Login(this.Account, this.Password, hostName, compulsory);
			}
			catch (SocketException ex)
			{
				//if (ex.ErrorCode == 10061) //如果连接不上服务器，那么自动换一个服务器登录。
				//{
				//	foreach (KeyValuePair<string, string> kvp in ClientConfig.LoadServers())
				//	{
				//		if (kvp.Value != Rpc.Url)
				//		{
				//			Rpc.Url = kvp.Value;
				//			break;
				//		}
				//	}

				//	ClientContext.User = Rpc.Create<LoginHandler>().Login(this.Account, this.Password, hostName, compulsory);
				//}

				MsgBox.Show("登录失败：{0}", ex.Message);
				return false;
			}
			if (ClientContext.User == null)
			{
				MsgBox.Show("登录失败！\r\n请核对您的账号和密码是否正确！");
				return false;
			}
			else if (ClientContext.User.Name == "DuplicateId") //如果是重复登录；
			{
				if (!compulsory)
				{
					if (MsgBox.Confirm("{0} 已经在 {1} 登录，您是否强制登录？\r\n注意，强制登录之后，原在线用户将强制下线。", this.Account, ClientContext.User.IP))
					{
						return Login(true);
					}
					else
					{
						return false;
					}
				}
				else
				{
					MsgBox.Show("登录失败！用户已经在 {1} 登录！", ClientContext.User.IP);
				}
			}

			ClientContext.SessionId = ClientContext.User.SessionId;

			ClientConfig clientConfig = new ClientConfig()
			{
				LoginAccount = this.Account,
				Server = this.Server
			};
			clientConfig.Save();
			return true;
		}

		private void btnLogin_Click(object sender, EventArgs e)
		{
			if (this.Login(false))
			{
				ClientContext.Server = this.Server;
				this.DialogResult = DialogResult.OK;
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
		}

		public bool ValidateData()
		{
			return new DataVerifier()
				.Check(string.IsNullOrEmpty(Account), "请填写登录账号！")
				.Check(string.IsNullOrEmpty(Password), "请填写登录密码！")
				.Check(string.IsNullOrEmpty(Server), "请选择服务器！")
				.ShowMsgIfFailed()
				.Pass;
		}

		void txtPassword_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode != Keys.Enter)
			{
				return;
			}

			if (!string.IsNullOrEmpty(txtAccount.Text))
			{
				btnLogin.PerformClick();
			}
		}

		private void LoadLogo()
		{
			string logoBackground = ConfigurationManager.AppSettings["LogoBackground"];
			if (!string.IsNullOrEmpty(logoBackground) && logoBackground.ToLower() == "fill")
			{
				pictureEdit1.Dock = DockStyle.Fill;
			}

			string[] path = Directory.GetFiles(ClientContext.ApplicationPath, "logo.*");
			if (path.Length == 0)
			{
				return;
			}
			if (File.Exists(path[0]))
			{
				pictureEdit1.Image = Bitmap.FromFile(path[0]);
			}
		}
	}
}
