using Pms.Common.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PMSUI.Config;
using CasunCommon.SystemLog;
using System.Diagnostics;

namespace PMSUI
{
    public partial class CLoginForm : Form
    {
        private static CLoginForm m_Instance;           // 该类实例对象
        public static CLoginForm Instance
        {
            get
            {
                if (m_Instance == null)
                {
                    m_Instance = new CLoginForm();
                }
                else
                {
                    m_Instance.Activate();
                }
                return m_Instance;
            }
        }

        public bool IsBuiltUser = false;
        private void InitStatusStrip()
        {
            ToolStripStatusLabel Tss;
            Tss = new ToolStripStatusLabel();
            Tss.BackColor = CasunUILib.g_FormBackColor;
            Tss.Spring = true;
            statusStrip1.Items.Add(Tss);

            Tss = new ToolStripStatusLabel();
            Tss.BackColor = CasunUILib.g_FormBackColor;
            string strVersion = "Version：" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
            Tss.Text = strVersion;
            Tss.ForeColor = Color.DarkGray;
            Tss.ToolTipText = strVersion;
            //Tss.AutoToolTip = true;
            statusStrip1.Items.Add(Tss);
        }

        public CLoginForm()
        {
            InitializeComponent();
            InitConfig();
            CLanguageManager.SetLang(this);
            this.BackColor = CasunUILib.g_FormBackColor;
            InitStatusStrip();

            m_Instance = this;
        }

        private void InitConfig()
        {
            CConfigManager.Init();

            if(CConfigManager.gs_globalConfig.gs_IsSavePassword)
            {
                tbUserID.Text = CConfigManager.gs_globalConfig.gs_UserName;
                tbPassWd.Text = CConfigManager.gs_globalConfig.gs_Password;
                cbRememberPasswd.Checked = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="IsBuilt"> 是否内置用户</param>
        /// <param name="sUserInfo">用户信息，非内置用户才生效</param>
        private void LoadMainForm( bool IsBuilt, PmsCoreDB.Model.PMS_sys_UserInfo sUserInfo)
        {
            MainForm open;
            if (IsBuilt)
            {
                IsBuiltUser = true;
                string strOptLog = string.Format("【" + CLanguageManager.LanguageChange("用户登录") + "】={0}", "*******");
                COperateLog.Instance.InsertOperaterLogAsync("CasunAdmin", strOptLog, DateTime.Now);

                open = new MainForm("*****", "*****", "*****");

                if (CConfigManager.gs_globalConfig.gs_IsSavePassword)
                {
                    tbUserID.Text = CConfigManager.gs_globalConfig.gs_UserName;
                    tbPassWd.Text = CConfigManager.gs_globalConfig.gs_Password;
                    cbRememberPasswd.Checked = true;
                }

                string strLog = string.Format(" 超级用户登录：ID={0},权限={1}", "CasunAdmin", "*****");
                CLog.Instance.WriteLog("System", strLog);
            }
            else
            {
                IsBuiltUser = false;

                open = new MainForm(sUserInfo.UserID, sUserInfo.UserName, sUserInfo.Permission);

                string strOptLog = string.Format("【" + CLanguageManager.LanguageChange("用户登录") + "】={0}", open.UserID);
                COperateLog.Instance.InsertOperaterLogAsync(open.UserID, strOptLog, DateTime.Now);

                if (!cbRememberPasswd.Checked)
                {
                    this.tbPassWd.Text = "";
                    CConfigManager.gs_globalConfig.gs_IsSavePassword = false;
                    CConfigManager.gs_globalConfig.gs_UserName = "";
                    CConfigManager.gs_globalConfig.gs_Password = "";
                    CConfigManager.SaveGlobalData();
                }
                else
                {
                    CConfigManager.gs_globalConfig.gs_IsSavePassword = true;
                    CConfigManager.gs_globalConfig.gs_UserName = tbUserID.Text;
                    CConfigManager.gs_globalConfig.gs_Password = tbPassWd.Text;
                    CConfigManager.SaveGlobalData();
                }
                string strLog = string.Format(CLanguageManager.LanguageChange("用户登录") + "：ID={0},Permission={1}", sUserInfo.UserID, sUserInfo.Permission);
                CLog.Instance.WriteLog("System", strLog);
            }

            this.Hide();
            open.ShowDialog();
            this.Show();
            //this.Close();
        }
        private void btOk_Click(object sender, EventArgs e)
        {
            if (!EntryCheck())
            {
                return;
            }
            string strSql = " UserID ='" + tbUserID.Text.Trim() + "'";

            // 内置账号
            if (tbUserID.Text.Trim() == "CasunAdmin" && tbPassWd.Text.ToString() == "Admin1470968")
            {
                LoadMainForm(true, null);
            }
            else
            {
                PmsCoreDB.Model.PMS_sys_UserInfo sUserInfo = PmsCoreDB.DBHost.Instance.UserInfo.GetModel(tbUserID.Text.Trim());

                if (sUserInfo != null)
                {
                    if (sUserInfo.Passwd != tbPassWd.Text.Trim())
                    {
                        MessageBox.Show(CLanguageManager.LanguageChange("密码错误") + "！");
                        return;
                    }
                    else
                    {
                        DateTime DTDBTime = PmsCoreDB.DBHost.Instance.GetDBTime();

                        if (sUserInfo.AuditPassword != CasunUILib.AuditUserPwd(
                            sUserInfo.UserID,
                            sUserInfo.Passwd,
                            sUserInfo.Permission,
                            sUserInfo.StartTime,
                            sUserInfo.EndTime
                            ))
                        {
                            string strMsg = CLanguageManager.LanguageChange("离线时间") + "," + CLanguageManager.LanguageChange("不能使用") + "！";
                            MessageBox.Show(strMsg);
                            return;
                        }

                        if (DTDBTime.CompareTo(Convert.ToDateTime(sUserInfo.StartTime.ToString())) < 0)
                        {
                            string strMsg = CLanguageManager.LanguageChange("授权还未开始") + "！";
                            MessageBox.Show(strMsg);
                            return;
                        }

                        if (DTDBTime.CompareTo(Convert.ToDateTime(sUserInfo.EndTime.ToString())) > 0)
                        {
                            string strMsg = CLanguageManager.LanguageChange("授权超期") + "！";
                            MessageBox.Show(strMsg);
                            return;
                        }
                        LoadMainForm(false, sUserInfo);
                    }
                }
                else
                {
                    string strMsg = CLanguageManager.LanguageChange("用户不存在") + "！";
                    MessageBox.Show(strMsg);
                    return;
                }
            }
        }


        /// <summary>
        /// 输入内容验证
        /// </summary>
        /// <returns></returns>
        private bool EntryCheck()
        {
            bool bResult = true;
            string strMsg = "";

            if (tbUserID.Text == "")
            {
                strMsg += "【" + CLanguageManager.LanguageChange("账号不能为空") + "】\r\n";
                bResult = false;
            }
            if (tbPassWd.Text == "")
            {
                strMsg += "【" + CLanguageManager.LanguageChange("密码不能为空") + "】\r\n";
                bResult = false;
            }
            if (!bResult)
            {
                MessageBox.Show(CLanguageManager.LanguageChange("以下项目输入有误") + "：\r\n" + strMsg, CLanguageManager.LanguageChange("提示"));
            }
            return bResult;
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tbPassWd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btOk_Click(sender, e);
            }
        }

        public void Dispose()
        {
            Process currentProcess = Process.GetCurrentProcess();
            currentProcess.Kill();
        }

    }
}
