using AutoUpdaterDotNET;
using DevExpress.XtraEditors;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Common;
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization
{
    public partial class frmLogin : XtraForm
    {
        private string m_UserCode
        {
            get
            {
                return bTxtUserCode.Text.Trim();
            }
        }
        private string m_UserPwd
        {
            get
            {
                return bTxtPassword.Text.Trim();
            }
        }

        public frmLogin()
        {
            InitializeComponent();
            Load += FrmLogin_Load;
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            AutoUpdate();
            lblVersion.Text = $"Ver {GetAppVersion()}";
        }

        #region 窗口拖动
        private const int WM_SysCommand = 0x0112;
        private const int OneMsgNum = 0xf017;
        [DllImport("user32")]
        private static extern bool ReleaseCapture();
        [DllImport("user32")]
        private static extern bool PostMessage(int hWnd, int Mwg, int wParam, int lParam);

        private void pnl_Top_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                PostMessage((int)this.Handle, WM_SysCommand, OneMsgNum, 0);
            }
        }
        #endregion

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnLogin_Click(object sender, EventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            try
            {
                if (string.IsNullOrEmpty(m_UserCode))
                {
                    throw new Exception("您输入的账户错误，请重试。");
                }

                if (string.IsNullOrEmpty(m_UserPwd))
                {
                    throw new Exception("您输入的密码错误，请重试。");
                }

                var responseData = Biz.UserManager.Instance.GetDataByCodeAndPwd(new UserInfoModel
                {
                    LoginCode = m_UserCode,
                    PassWord = DeviceRepair.Utils.Security.EncryptionHelper.EncryptByMD5(m_UserPwd)
                });

                if (responseData.Code != 1)
                    throw new Exception(responseData.Message);

                UserInfoModel us = responseData.ToDeserializeObject<UserInfoModel>();
                if (us != null)
                {
                    if (!us.Status)
                        throw new Exception($"用户被锁定,无法登录！");

                    if (!string.IsNullOrEmpty(responseData.Token))
                    {
                        splashScreenManager1.TryCloseWait();
                        GlobalInfo.CurrentUser = us;
                        GlobalInfo.token = responseData.Token;

                        this.DialogResult = DialogResult.OK;
                        this.Close();
                        return;
                    }
                }

                //EnableOrDisableControl(true);
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(responseData.Message);
            }
            catch (Exception ex)
            {
                //EnableOrDisableControl(true);
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void picConfig_Click(object sender, EventArgs e)
        {
            //using (frmClientConfig mFrm = new Sys.frmClientConfig())
            //{
            //    mFrm.ShowDialog();
            //}

            //ueEnv.RefreshEditValue();
        }

        private void bTxtPassword_Enter(object sender, EventArgs e)
        {
        }

        private void bTxtPassword_Leave(object sender, EventArgs e)
        {
            bTxtPassword.Properties.UseSystemPasswordChar = true;
            bTxtPassword.Properties.Buttons[1].ImageOptions.Image = Properties.Resources.icoshow;
            bTxtPassword.Properties.Buttons[1].Caption = "密码可见";
            bTxtPassword.Properties.Buttons[1].ToolTip = "密码可见";
        }

        /// <summary>
        /// 密码校验
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bTxtUserCode_TextChanged(object sender, EventArgs e)
        {
            if (((ButtonEdit)sender).Name != "bTxtPassword")
            {
                bTxtPassword.Text = string.Empty;
                this.dxValidationProvider1.Validate((ButtonEdit)sender);
            }
            else
            {
                if (!string.IsNullOrEmpty(bTxtPassword.Text.Trim()))
                {
                    dxValidationProvider1.RemoveControlError((ButtonEdit)sender);
                }
            }
        }

        /// <summary>
        /// 回车登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bTxtPassword_Properties_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(m_UserCode) && !string.IsNullOrEmpty(m_UserPwd))
                {
                    if (e.KeyChar == (char)Keys.Enter)
                    {
                        bBtnLogin.PerformClick();
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 密码可视/隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bTxtPassword_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "密码可见")
            {
                bTxtPassword.Properties.UseSystemPasswordChar = false;
                bTxtPassword.Properties.Buttons[1].ImageOptions.Image = Properties.Resources.icohide;
                bTxtPassword.Properties.Buttons[1].Caption = "密码隐藏";
                bTxtPassword.Properties.Buttons[1].ToolTip = "密码隐藏";
            }
            else if (e.Button.Caption == "密码隐藏")
            {
                bTxtPassword.Properties.UseSystemPasswordChar = true;
                bTxtPassword.Properties.Buttons[1].ImageOptions.Image = Properties.Resources.icoshow;
                bTxtPassword.Properties.Buttons[1].Caption = "密码可见";
                bTxtPassword.Properties.Buttons[1].ToolTip = "密码可见";
            }
        }

        /// <summary>
        /// 程序退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bBtnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        public void AutoUpdate()
        {
            AutoUpdater.AppTitle = "Device Repair And Optimization";
            var vUpdateDir = Path.Combine(Application.StartupPath, "Update");
            if (!Directory.Exists(vUpdateDir))
            {
                Directory.CreateDirectory(vUpdateDir);
            }

            // 指定下载文件的存储目录
            AutoUpdater.DownloadPath = vUpdateDir;
            AutoUpdater.UpdateFormSize = new Size(800, 600);

            AutoUpdater.ApplicationExitEvent += AutoUpdater_ApplicationExitEvent;
            AutoUpdater.Synchronous = true;
            AutoUpdater.ShowSkipButton = false;
            AutoUpdater.ShowRemindLaterButton = false;
            AutoUpdater.Start($"http://{DeviceRepair.Utils.Config.Configurations.Properties.ServiceIP}/{DeviceRepair.Utils.Config.Configurations.Properties.ServiceName}/Update/DOAutoUpdater.xml");
        }

        private void AutoUpdater_ApplicationExitEvent()
        {
            Text = @"Closing application...";
            Thread.Sleep(3000);
            Application.Exit();
        }

        /// <summary>
        /// 获取当前程序版本
        /// </summary>
        /// <returns></returns>
        private static string GetAppVersion()
        {
            try
            {
                char vSplitChar = '.';
                string[] vVersion = Application.ProductVersion.Split(vSplitChar);
                return $"{vVersion[0]}{vSplitChar}{vVersion[1]}";
            }
            catch
            {
                return Application.ProductVersion;
            }
        }
    }
}
