Imports System.Windows.Forms
Imports UTS_Core.My
Imports UTS_Core.Security

Namespace UTSModule.Login
    Public Class LoginForm
        Inherits System.Windows.Forms.Form
#Region "初始化组件"


        Friend WithEvents Label4 As System.Windows.Forms.Label
        Friend WithEvents CboUserAccount As System.Windows.Forms.ComboBox
        Friend WithEvents BtnLogin As System.Windows.Forms.Button
        Friend WithEvents ChkAutoLogin As System.Windows.Forms.CheckBox
        Friend WithEvents ChkRememb As System.Windows.Forms.CheckBox
        Friend WithEvents TxtUserPassword As System.Windows.Forms.TextBox
        Friend WithEvents Label2 As System.Windows.Forms.Label
        Friend WithEvents Label1 As System.Windows.Forms.Label
        Friend WithEvents PicLogin As System.Windows.Forms.PictureBox
        Friend WithEvents TmrAutoLogin As System.Windows.Forms.Timer
        Friend WithEvents PictureBox1 As PictureBox
        Friend WithEvents PictureBox2 As PictureBox



        'Form 重写 Dispose，以清理组件列表。
        <System.Diagnostics.DebuggerNonUserCode()>
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            Try
                If disposing AndAlso components IsNot Nothing Then
                    components.Dispose()
                End If
            Finally
                MyBase.Dispose(disposing)
            End Try
        End Sub

        'Windows 窗体设计器所必需的
        Private components As System.ComponentModel.IContainer

        '注意:  以下过程是 Windows 窗体设计器所必需的
        '可以使用 Windows 窗体设计器修改它。  
        '不要使用代码编辑器修改它。
        <System.Diagnostics.DebuggerStepThrough()>
        Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(LoginForm))
        Me.Label4 = New System.Windows.Forms.Label()
        Me.CboUserAccount = New System.Windows.Forms.ComboBox()
        Me.BtnLogin = New System.Windows.Forms.Button()
        Me.ChkAutoLogin = New System.Windows.Forms.CheckBox()
        Me.ChkRememb = New System.Windows.Forms.CheckBox()
        Me.TxtUserPassword = New System.Windows.Forms.TextBox()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.PicLogin = New System.Windows.Forms.PictureBox()
        Me.TmrAutoLogin = New System.Windows.Forms.Timer(Me.components)
            Me.PictureBox1 = New System.Windows.Forms.PictureBox()
            Me.PictureBox2 = New System.Windows.Forms.PictureBox()
            CType(Me.PicLogin, System.ComponentModel.ISupportInitialize).BeginInit()
            CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit()
            CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.SuspendLayout()
            '
            'Label4
            '
            Me.Label4.Location = New System.Drawing.Point(518, 91)
            Me.Label4.Name = "Label4"
            Me.Label4.Size = New System.Drawing.Size(18, 21)
            Me.Label4.TabIndex = 32
            Me.Label4.Text = "*"
            Me.Label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
            '
            'CboUserAccount
            '
            Me.CboUserAccount.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.CboUserAccount.FormattingEnabled = True
            Me.CboUserAccount.ImeMode = System.Windows.Forms.ImeMode.Disable
            Me.CboUserAccount.Location = New System.Drawing.Point(338, 41)
            Me.CboUserAccount.MaxLength = 20
            Me.CboUserAccount.Name = "CboUserAccount"
            Me.CboUserAccount.Size = New System.Drawing.Size(174, 23)
            Me.CboUserAccount.TabIndex = 0
            Me.CboUserAccount.Text = "Qizengbiao"
            '
            'BtnLogin
            '
            Me.BtnLogin.FlatStyle = System.Windows.Forms.FlatStyle.Flat
            Me.BtnLogin.Font = New System.Drawing.Font("Microsoft Sans Serif", 18.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.BtnLogin.ForeColor = System.Drawing.Color.White
            Me.BtnLogin.Location = New System.Drawing.Point(304, 162)
            Me.BtnLogin.Name = "BtnLogin"
            Me.BtnLogin.Size = New System.Drawing.Size(208, 49)
            Me.BtnLogin.TabIndex = 2
            Me.BtnLogin.Text = "登    录"
            Me.BtnLogin.UseVisualStyleBackColor = True
            '
            'ChkAutoLogin
            '
            Me.ChkAutoLogin.AutoSize = True
            Me.ChkAutoLogin.FlatStyle = System.Windows.Forms.FlatStyle.Popup
            Me.ChkAutoLogin.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.ChkAutoLogin.ForeColor = System.Drawing.Color.White
            Me.ChkAutoLogin.Location = New System.Drawing.Point(314, 134)
            Me.ChkAutoLogin.Name = "ChkAutoLogin"
            Me.ChkAutoLogin.Size = New System.Drawing.Size(72, 19)
            Me.ChkAutoLogin.TabIndex = 28
            Me.ChkAutoLogin.TabStop = False
            Me.ChkAutoLogin.Text = "自动登录"
            Me.ChkAutoLogin.UseVisualStyleBackColor = True
            '
            'ChkRememb
            '
            Me.ChkRememb.AutoSize = True
            Me.ChkRememb.FlatStyle = System.Windows.Forms.FlatStyle.Popup
            Me.ChkRememb.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.ChkRememb.ForeColor = System.Drawing.Color.White
            Me.ChkRememb.Location = New System.Drawing.Point(440, 134)
            Me.ChkRememb.Name = "ChkRememb"
            Me.ChkRememb.Size = New System.Drawing.Size(72, 19)
            Me.ChkRememb.TabIndex = 27
            Me.ChkRememb.TabStop = False
            Me.ChkRememb.Text = "记住密码"
            Me.ChkRememb.UseVisualStyleBackColor = True
            '
            'TxtUserPassword
            '
            Me.TxtUserPassword.ImeMode = System.Windows.Forms.ImeMode.Disable
            Me.TxtUserPassword.Location = New System.Drawing.Point(338, 88)
            Me.TxtUserPassword.MaxLength = 20
            Me.TxtUserPassword.Name = "TxtUserPassword"
            Me.TxtUserPassword.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42)
            Me.TxtUserPassword.Size = New System.Drawing.Size(174, 21)
            Me.TxtUserPassword.TabIndex = 1
            Me.TxtUserPassword.Text = "Actop00803"
            '
            'Label2
            '
            Me.Label2.AutoSize = True
            Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.Label2.ForeColor = System.Drawing.Color.White
            Me.Label2.Location = New System.Drawing.Point(301, 94)
            Me.Label2.Name = "Label2"
            Me.Label2.Size = New System.Drawing.Size(31, 15)
            Me.Label2.TabIndex = 25
            Me.Label2.Text = "密码"
            '
            'Label1
            '
            Me.Label1.AutoSize = True
            Me.Label1.BackColor = System.Drawing.Color.Transparent
            Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            Me.Label1.ForeColor = System.Drawing.Color.White
            Me.Label1.Location = New System.Drawing.Point(301, 49)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(31, 15)
            Me.Label1.TabIndex = 24
            Me.Label1.Text = "账号"
            Me.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight
            '
            'PicLogin
            '
            Me.PicLogin.Image = CType(resources.GetObject("PicLogin.Image"), System.Drawing.Image)
            Me.PicLogin.Location = New System.Drawing.Point(3, 3)
            Me.PicLogin.Name = "PicLogin"
            Me.PicLogin.Size = New System.Drawing.Size(275, 242)
            Me.PicLogin.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
            Me.PicLogin.TabIndex = 23
            Me.PicLogin.TabStop = False
            '
            'TmrAutoLogin
            '
            Me.TmrAutoLogin.Interval = 3000
            '
            'PictureBox1
            '
            Me.PictureBox1.Image = CType(resources.GetObject("PictureBox1.Image"), System.Drawing.Image)
            Me.PictureBox1.Location = New System.Drawing.Point(304, 36)
            Me.PictureBox1.Name = "PictureBox1"
            Me.PictureBox1.Size = New System.Drawing.Size(28, 33)
            Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
            Me.PictureBox1.TabIndex = 35
            Me.PictureBox1.TabStop = False
            '
            'PictureBox2
            '
            Me.PictureBox2.Image = CType(resources.GetObject("PictureBox2.Image"), System.Drawing.Image)
            Me.PictureBox2.Location = New System.Drawing.Point(304, 79)
            Me.PictureBox2.Name = "PictureBox2"
            Me.PictureBox2.Size = New System.Drawing.Size(28, 33)
            Me.PictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
            Me.PictureBox2.TabIndex = 36
            Me.PictureBox2.TabStop = False
            '
            'LoginForm
            '
            Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!)
            Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
            Me.BackColor = System.Drawing.Color.DodgerBlue
            Me.ClientSize = New System.Drawing.Size(544, 249)
            Me.Controls.Add(Me.PictureBox2)
            Me.Controls.Add(Me.PictureBox1)
            Me.Controls.Add(Me.Label4)
            Me.Controls.Add(Me.CboUserAccount)
            Me.Controls.Add(Me.BtnLogin)
        Me.Controls.Add(Me.ChkAutoLogin)
        Me.Controls.Add(Me.ChkRememb)
        Me.Controls.Add(Me.TxtUserPassword)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.PicLogin)
        Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 9!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134,Byte))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
        Me.Icon = CType(resources.GetObject("$this.Icon"),System.Drawing.Icon)
        Me.MaximizeBox = false
        Me.MinimizeBox = false
        Me.Name = "LoginForm"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Form1"
        CType(Me.PicLogin,System.ComponentModel.ISupportInitialize).EndInit
        CType(Me.PictureBox1,System.ComponentModel.ISupportInitialize).EndInit
        CType(Me.PictureBox2,System.ComponentModel.ISupportInitialize).EndInit
        Me.ResumeLayout(false)
        Me.PerformLayout

End Sub

        Sub New()
            InitializeComponent()
        End Sub
#End Region

        ''' <summary>是否记住密码</summary>
        Private _isRecordPassWord As Boolean

        ''' <summary>是否自动登录</summary>
        Private _isAutoLogin As Boolean

        ''' <summary>是否正在登录中</summary>
        Private _isLogging As Boolean


        ''' <summary>校验文件信息</summary>
        Public Property UserLicense As License.License

        ''' <summary>用户登录信息</summary>
        Public Property UserLoginInfo As UserInfo




        ''' <summary>修改窗体标题</summary>
        Private Sub ShowFormTitle()
            Text = $"{My.Application.Info.ProductName} Login"
        End Sub

        ''' <summary>读取Setting中的缓存量</summary>
        Private Sub LoadSettings()
            My.Settings.Reload() '读取Setting中的内容
            _isAutoLogin = My.Settings.IsAutoLogin
            _isRecordPassWord = My.Settings.IsRecordPassWord
        End Sub

        ''' <summary>保存Setting中的缓存量</summary>
        Private Sub SaveSettings()
            My.Settings.IsAutoLogin = _isAutoLogin
            My.Settings.IsRecordPassWord = _isRecordPassWord

            If _isRecordPassWord Then
                Settings.UserAccount = Aes128.EncryptStr(CboUserAccount.Text, Aes128.ServerAesKey)
                Settings.UserPassword = Aes128.EncryptStr(TxtUserPassword.Text, Aes128.ServerAesKey)
            Else
                Settings.UserAccount = String.Empty
                Settings.UserPassword = String.Empty
            End If
            Settings.Save()
        End Sub

        Private Sub InitChkAutoLogin()
            ChkAutoLogin.Checked = _isAutoLogin
        End Sub

        Private Sub InitChkRememb()
            ChkRememb.Checked = _isRecordPassWord
        End Sub

        ''' <summary>
        ''' 初始化账号控件显示
        ''' </summary>
        Private Sub InitCboUserAccount()
            Try
                CboUserAccount.Text = Aes128.DecryptStr(Settings.UserAccount, Aes128.ServerAesKey)
            Catch ex As Exception
                CboUserAccount.Text = String.Empty
            End Try
        End Sub

        ''' <summary>
        ''' 密码获取与保存机制以后会修改,或加密
        ''' </summary>
        Private Sub InitTxtUserPassword()
            Try
                TxtUserPassword.Text = Aes128.DecryptStr(Settings.UserPassword, Aes128.ServerAesKey)
            Catch ex As Exception
                TxtUserPassword.Text = String.Empty
            End Try
        End Sub

        Private Sub InitForm()
            ShowFormTitle()

            InitChkAutoLogin()
            InitChkRememb()
            InitCboUserAccount()
            InitTxtUserPassword()
        End Sub


        Private Sub CloseTipMessage(tipString As String)
            MessageBox.Show(tipString, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            DialogResult = DialogResult.Abort
            Close()
        End Sub


        Private Sub CheckLicense()
            Try
                UserLicense = New License.License(UtsRegistry.LicenseFilePath)
                UserLicense.CheckLicense()

            Catch ex As Exception
                CloseTipMessage($"Open And Check License Error:{ex.Message}")
            End Try
        End Sub


        Private Sub InitConnectParams()
            If UserLicense Is Nothing Then
                Throw New Exception($"License Error:Uninitialized License!")
            End If

            UtsPath.VendorName = UserLicense.VendorName
            UtsFtp.InitConnectParams(CInt(UserLicense.FtpPort), UserLicense.FtpUser, UserLicense.FtpPwd)
            UtsDb.InitConnectParams(UserLicense) '根据License信息,初始化数据库连接信息
        End Sub

        Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles Me.Load
            LoadSettings()
            InitForm()

            CheckLicense()
            InitConnectParams()
        End Sub

        ''' <summary>记住密码复选框状态修改触发事件</summary>
        Private Sub ChkKeepPwd_CheckedChanged(sender As Object, e As EventArgs) Handles ChkRememb.CheckedChanged
            _isRecordPassWord = ChkRememb.Checked
        End Sub

        ''' <summary>自动登录复选框状态修改触发事件</summary>
        Private Sub Chk_AutoLogin_CheckedChanged(sender As Object, e As EventArgs) Handles ChkAutoLogin.CheckedChanged
            _isAutoLogin = ChkAutoLogin.Checked
        End Sub

        Private Sub LoginForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            SaveSettings()
        End Sub


        Private Sub CheckUserAccount(userAccount As String)
            If String.IsNullOrWhiteSpace(userAccount) Then
                Throw New Exception($"请输入用户账号!")
            End If
        End Sub

        Private Sub CheckUserPassword(userPassword As String)
            If String.IsNullOrWhiteSpace(userPassword) Then
                Throw New Exception($"请输入密码!")
            End If
        End Sub


        Private Function AdminLogin(userAccount As String, userPassword As String) As Boolean
            Return userAccount = UserLicense.DefaultUser AndAlso userPassword = UserLicense.DefaultPassword
        End Function

        ''' <summary>
        ''' 使用账号密码登录
        ''' </summary>
        Private Sub AccountLogin()
            Dim userAccount As String = CboUserAccount.Text
            Dim userPassword As String = TxtUserPassword.Text
            CheckUserAccount(userAccount)
            CheckUserPassword(userPassword)

            Dim dtUser As DataTable = DbConnect.DbConnector.UtsGetUserInfo(userAccount, userPassword)
            UserLoginInfo = New UserInfo(dtUser)
        End Sub


        Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click
            CloseAutoLogin()
            If _isLogging Then Return
            _isLogging = True

            Text = $"{My.Application.Info.ProductName} Login [Logining]"
            Try
                AccountLogin() '从云端获取用户信息

                DialogResult = DialogResult.OK
                Close() '登录完成关闭登录页面
            Catch ex As Exception
                Text = $"{My.Application.Info.ProductName} Login [Login failed]"
                MsgBox(ex.Message, MsgBoxStyle.OkOnly, "登录失败")
            End Try

            _isLogging = False
        End Sub

        Private Sub TmrAutoLogin_Tick(sender As Object, e As EventArgs) Handles TmrAutoLogin.Tick
            BtnLogin.PerformClick()
        End Sub

        Private Sub LoginForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            If _isAutoLogin Then
                TmrAutoLogin.Start()
            End If
        End Sub

        Private Sub LoginForm_Activated(sender As Object, e As EventArgs) Handles Me.Activated
            '设置默认焦点控件
            BtnLogin.Focus()
        End Sub

        Private Sub TxtUserPassword_TextChanged(sender As Object, e As EventArgs) Handles TxtUserPassword.TextChanged
            CloseAutoLogin()
        End Sub

        Private Sub CboUserAccount_TextChanged(sender As Object, e As EventArgs) Handles CboUserAccount.TextChanged
            CloseAutoLogin()
        End Sub

        Private Sub CloseAutoLogin()
            If TmrAutoLogin.Enabled Then
                TmrAutoLogin.Stop()
                Text = $"{My.Application.Info.ProductName} Login [Auto Login Cancelled...]"
            End If
        End Sub
    End Class
End Namespace