using System;
using System.IO;
using System.Net;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;

using Core.Mes.IBaseInterface;
using Core.Mes.ClientFrameWork;

namespace Core.Mes.ClientManager
{
    /// <summary>
    /// 登录窗口
    /// </summary>
    public class FrmCover : System.Windows.Forms.Form
    {

        #region "	定义变量	"

        public MainForm _mainForm;

        public static int pot;
        public static string url;
        public static string messageFlag;


        public bool _loginFlag = false;

        //重新登录标志
        public bool ReLoginFlag = false;
        private int index = 1;

        #endregion //

        #region "	窗体自动生成代码	"


        public FrmCover()
        {
            //
            // Windows 窗体设计器支持所必需的
            //
            InitializeComponent();

            //
            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            //

        }

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }


        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button btnLoad;
        private System.Windows.Forms.ToolTip toolTip1;
        private System.Windows.Forms.Button btnExit;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.ComponentModel.IContainer components;
        private Infragistics.Win.UltraWinProgressBar.UltraProgressBar ultraProgressBar1;
        private System.Windows.Forms.Timer timerAutoRun;
        #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            Infragistics.Win.Appearance appearance1 = new Infragistics.Win.Appearance();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmCover));
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.btnLoad = new System.Windows.Forms.Button();
            this.btnExit = new System.Windows.Forms.Button();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.ultraProgressBar1 = new Infragistics.Win.UltraWinProgressBar.UltraProgressBar();
            this.timerAutoRun = new System.Windows.Forms.Timer(this.components);
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
            this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
            this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.textBox1.Location = new System.Drawing.Point(150, 133);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(120, 21);
            this.textBox1.TabIndex = 0;
            this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
            this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
            // 
            // textBox2
            // 
            this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.textBox2.Location = new System.Drawing.Point(150, 161);
            this.textBox2.Name = "textBox2";
            this.textBox2.PasswordChar = '*';
            this.textBox2.Size = new System.Drawing.Size(120, 21);
            this.textBox2.TabIndex = 1;
            this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox2_KeyPress);
            // 
            // btnLoad
            // 
            this.btnLoad.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.btnLoad.ImageIndex = 0;
            this.btnLoad.Location = new System.Drawing.Point(282, 132);
            this.btnLoad.Name = "btnLoad";
            this.btnLoad.Size = new System.Drawing.Size(56, 23);
            this.btnLoad.TabIndex = 2;
            this.btnLoad.Text = "登录";
            this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
            // 
            // btnExit
            // 
            this.btnExit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.btnExit.ImageIndex = 3;
            this.btnExit.Location = new System.Drawing.Point(282, 160);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(55, 23);
            this.btnExit.TabIndex = 3;
            this.btnExit.Text = "退出";
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            // 
            // pictureBox1
            // 
            this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(450, 104);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 6;
            this.pictureBox1.TabStop = false;
            // 
            // ultraProgressBar1
            // 
            this.ultraProgressBar1.BorderStyle = Infragistics.Win.UIElementBorderStyle.None;
            this.ultraProgressBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
            appearance1.ForeColor = System.Drawing.Color.Yellow;
            this.ultraProgressBar1.FillAppearance = appearance1;
            this.ultraProgressBar1.Location = new System.Drawing.Point(0, 213);
            this.ultraProgressBar1.Maximum = 300;
            this.ultraProgressBar1.Name = "ultraProgressBar1";
            this.ultraProgressBar1.Size = new System.Drawing.Size(450, 14);
            this.ultraProgressBar1.Step = 1;
            this.ultraProgressBar1.SupportThemes = false;
            this.ultraProgressBar1.TabIndex = 8;
            this.ultraProgressBar1.Text = "新余钢铁有限责任公司技术中心 & 湖南视拓科技发展有限责任公司 联合研发";
            // 
            // timerAutoRun
            // 
            this.timerAutoRun.Tick += new System.EventHandler(this.timerAutoRun_Tick);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(105, 137);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(41, 12);
            this.label4.TabIndex = 12;
            this.label4.Text = "用户名";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(117, 165);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(29, 12);
            this.label5.TabIndex = 13;
            this.label5.Text = "密码";
            // 
            // FrmCover
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(450, 227);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.ultraProgressBar1);
            this.Controls.Add(this.btnExit);
            this.Controls.Add(this.btnLoad);
            this.Controls.Add(this.pictureBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FrmCover";
            this.ShowInTaskbar = false;
            this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "系统用户登录";
            this.Load += new System.EventHandler(this.FrmCover_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion



        #endregion

        #region "	Init Form "

        DataSet dsetLoginUrl = new DataSet();

        /// <summary>
        /// 窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmCover_Load(object sender, System.EventArgs e)
        {

            try
            {
                if (ConfigurationSettings.AppSettings["Corporation"] != null)
                    this.ultraProgressBar1.Text = System.Configuration.ConfigurationSettings.AppSettings["Corporation"] + @" & 湖南视拓科技发展有限责任公司 联合研发";
                this.pictureBox1.Image = System.Drawing.Image.FromFile(@"LoginPic.jpg");
                url = ConfigurationSettings.AppSettings["RemoteServerUrl"];

                if (File.Exists("LoginUrl.txt"))
                {
                    dsetLoginUrl.ReadXml("LoginUrl.txt");
                    dsetLoginUrl.Tables[0].PrimaryKey = new DataColumn[] { dsetLoginUrl.Tables[0].Columns[0] };
                    foreach (DataRow arow in dsetLoginUrl.Tables[0].Rows)
                    {
                        textBox1.AutoCompleteCustomSource.Add(arow[0].ToString());
                    }
                }
                else
                {
                    DataTable dtab = new DataTable();
                    dtab.Columns.Add("LogID", typeof(string));
                    dtab.PrimaryKey = new DataColumn[] { dtab.Columns[0] };
                    dsetLoginUrl.Tables.Add(dtab);
                    dsetLoginUrl.WriteXml("LoginUrl.txt", XmlWriteMode.IgnoreSchema);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            this.textBox1.Focus();
        }

        #endregion

        #region "	Button Event	"

        private bool IsLoginThreadFlag = false;
        private string loginID = "";
        private string passwd = "";
        private bool IsException = false;

        private Thread ThLogin;

        /// <summary>
        /// 登录按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoad_Click(object sender, System.EventArgs e)
        {
            loginID = this.textBox1.Text.Trim();
            passwd = this.textBox2.Text.Trim();
            this.timerAutoRun.Interval = 100;
            index = 1;
            IsException = false;
            this.ultraProgressBar1.Value = this.ultraProgressBar1.Minimum;

            this.btnLoad.Enabled = false;


            if (!ReLoginFlag)
            {

                //this.ultraProgressBar1.Visible = true

               
                this.timerAutoRun.Start();

                ThreadStart ts = new ThreadStart(LoginHandler);
                ThLogin = new Thread(ts);
                ThLogin.Name = "LoginThread";
                ThLogin.Start();
                
            }
            else
            {
                try
                {
                    string ipaddress = "";

                    System.Net.IPAddress[] ips = Dns.GetHostByName(Dns.GetHostName()).AddressList;
                    if (ips.Length > 0) ipaddress = ips[0].ToString();

                    string strOut = "";
                    ClientCommon._RemotingHelp.InitServerUrlList("ServerCommon", url);

                    object obj = ClientCommon._RemotingHelp.ExecuteMethod("ServerCommon", "Core.Mes.ServerCommon.UserInfoManager", "GetPurviewInfo",
                        new object[] { this.loginID, this.passwd, Dns.GetHostName(), ipaddress }, out strOut);

                    if (strOut != "") throw new Exception(strOut);

                    ClientCommon._UserInfo = (UserInfo)obj;

                    //===

                    //==
                    AfterLogin();

                    //调用服务器与客户端时间同步函数
                    SetTime.SetClientTime();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接服务器失败！\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
                this.btnLoad.Enabled = true;
            }
        }
        private void AfterLogin()
        {
            try
            {



                _loginFlag = true;

                try
                {
                    if (dsetLoginUrl.Tables[0].Rows.Find(textBox1.Text.Trim()) == null)
                    {
                        if (dsetLoginUrl.Tables[0].Rows.Count == 10)
                            dsetLoginUrl.Tables[0].Rows[0].Delete();

                        dsetLoginUrl.Tables[0].Rows.Add(new object[] { textBox1.Text.Trim() });
                        dsetLoginUrl.Tables[0].AcceptChanges();
                        dsetLoginUrl.WriteXml("LoginUrl.txt", XmlWriteMode.IgnoreSchema);
                    }
                }
                catch
                { }
                this.Close();
            }
            catch (Exception ex)
            {
                this.btnLoad.Enabled = true;
                _loginFlag = false;
                MessageBox.Show("连接服务器失败！\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void LoginHandler()
        {
            string ipaddress = "";

            System.Net.IPAddress[] ips = Dns.GetHostByName(Dns.GetHostName()).AddressList;
            if (ips.Length > 0) ipaddress = ips[0].ToString();


            try
            {
                IsLoginThreadFlag = false;
                string strOut = "";
                ClientCommon._RemotingHelp.InitServerUrlList("ServerCommon", url);
                object obj = ClientCommon._RemotingHelp.ExecuteMethod("ServerCommon", "Core.Mes.ServerCommon.UserInfoManager", "GetPurviewInfo",
                    new object[] { this.loginID, this.passwd, Dns.GetHostName(), ipaddress }, out strOut);


                if (strOut != "") throw new Exception(strOut);

                ClientCommon._UserInfo = (UserInfo)obj;
                ClientCommon._RemotingHelp.ServerUrlList = (DataSet)ClientCommon._RemotingHelp.ExecuteMethod("ServerCommon", "Core.Mes.ServerCommon.UserInfoManager", "GetServerList",
                    null, out strOut);

                _loginFlag = true;
                IsLoginThreadFlag = true;
            }

            catch (Exception ex)
            {
                //this.btnLoad.Enabled =true;
                IsException = true;
                _loginFlag = false;
                IsLoginThreadFlag = true;
                if (ex.Message == "线程正被中止。") return;
                MessageBox.Show("连接服务器失败！\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            _loginFlag = false;
            try
            {
                this.timerAutoRun.Stop();

                if (ThLogin != null)
                {
                    ThLogin.Abort();
                }

            }
            catch { }
            this.Close();
        }

        private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {

            }
            if (e.KeyChar == (char)27)
            {
                this.btnExit_Click(sender, new EventArgs());
            }
        }

        private void textBox2_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.btnLoad_Click(sender, new EventArgs());
            }
            if (e.KeyChar == (char)27)
            {
                this.btnExit_Click(sender, new EventArgs());
            }
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            FrmPasswd frm = new FrmPasswd();
            frm.strUserID = this.textBox1.Text.Trim();
            frm.ShowDialog();
        }
        #endregion

        #region "	Monuse	Events	"

        #endregion


        private void timerAutoRun_Tick(object sender, System.EventArgs e)
        {
            int current = this.ultraProgressBar1.Value;
            int max = this.ultraProgressBar1.Maximum;
            int min = this.ultraProgressBar1.Minimum;
            int step = this.ultraProgressBar1.Step;

            if (index++ > 300)
            {
                string strInfo = "";
                try
                {
                    this.timerAutoRun.Stop();

                    if (ThLogin != null)
                    {
                        ThLogin.Abort();
                    }
                }
                catch (Exception ex)
                {
                    strInfo = ex.Message;
                }

                MessageBox.Show("连接超时！\n" + strInfo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (current == max && step > 0)
                this.ultraProgressBar1.Value = min;

            this.ultraProgressBar1.PerformStep();


            if (IsLoginThreadFlag)
            {
                if (IsException)
                {
                    this.timerAutoRun.Stop();
                    //this.ultraProgressBar1.Visible = false;
                }
                if (this.ultraProgressBar1.Value != max)
                {
                    this.timerAutoRun.Interval = 10;
                    this.ultraProgressBar1.Step = 5;
                }
                else
                {
                    this.timerAutoRun.Stop();
                    this.AfterLogin();
                }
            }
            else
            {

            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == System.Windows.Forms.Keys.Return)
            {
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }
    }
}
