Imports System.Text
Imports System.Threading
Imports Microsoft.VisualBasic.Devices
Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Test
Imports UTS_Core.UTSModule.Test.Controls
Imports UTS_Core.UTSModule.Test.StatusMonitor
Imports UTS_Core.UTSModule.Test.StatusMonitor.ComportStatusMonitor
Imports UTS_Core.UTSModule.Test.StatusMonitor.DatabaseStatusMonitor
Imports UTS_Core.UTSModule.Test.StatusMonitor.StationEditStatusMonitor
Imports UTS_Core.UTSModule.Test.StatusMonitor.TestStatusMonitor


Public Class FrmMain
    Implements IProcessStation
    Implements IProductionLine

    Private _utsApp As UtsAppForm


#Region "网络检测模块"
    Enum NetWorkStatusEnum
        Connected
        UnConnected
    End Enum
    Private _networkStatus As NetWorkStatusEnum = NetWorkStatusEnum.Connected

    ''' <summary>
    ''' 根据网络状态修改页面提示
    ''' </summary>
    ''' <param name="netStatus"></param>
    Private Sub UpdateNetWorkStatus(netStatus As NetWorkStatusEnum)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of NetWorkStatusEnum)(AddressOf UpdateNetWorkStatus), New Object() {netStatus})
            Return
        End If

        If netStatus = NetWorkStatusEnum.Connected Then
            TssLblNetWorkStatus.Image = ImgMainStatus.Images("网络-绿色64x64.png")
            TssLblNetWorkStatus.ToolTipText = $"网络已连接"

            ApplicationLog.WriteInfoLog("网络连接状态变更,网络已连接。")
        Else
            TssLblNetWorkStatus.Image = ImgMainStatus.Images("网络-红色64x64.png")
            TssLblNetWorkStatus.ToolTipText = $"网络未连接"

            ApplicationLog.WriteWarningLog("网络连接状态变更,网络未连接。")
        End If
    End Sub

    ''' <summary>
    ''' 网络状态变化修改处理事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub NetworkAvailabilityChanged(sender As Object, e As NetworkAvailableEventArgs)
        If e.IsNetworkAvailable Then
            _networkStatus = NetWorkStatusEnum.Connected
        Else
            _networkStatus = NetWorkStatusEnum.UnConnected
        End If
        UpdateNetWorkStatus(_networkStatus)
    End Sub

    ''' <summary>
    ''' 开始监听网络状态
    ''' </summary>
    Private Sub StartMonitorNetworkStatus()
        '网络监控
        Dim netStatus As New Network

        If netStatus.IsAvailable Then
            _networkStatus = NetWorkStatusEnum.Connected
        Else
            _networkStatus = NetWorkStatusEnum.UnConnected
        End If

        UpdateNetWorkStatus(_networkStatus) '刷新界面网络状态提示

        AddHandler netStatus.NetworkAvailabilityChanged, AddressOf NetworkAvailabilityChanged
    End Sub

#End Region

#Region "数据库同步状态检测模块"
    Private Sub UpdateDatabaseStatus(dbStatus As DatabaseSyncStatusEnum)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of DatabaseSyncStatusEnum)(AddressOf UpdateDatabaseStatus), New Object() {dbStatus})
            Return
        End If
        Select Case dbStatus
            Case DatabaseSyncStatusEnum.Unknown
                TssLblDatabaseStatus.Image = ImgMainStatus.Images("数据同步-灰色64x64.png")
                TssLblDatabaseStatus.ToolTipText = $"数据库同步信息未知"

                ApplicationLog.WriteWarningLog("数据库同步状态变更,未知。")
            Case DatabaseSyncStatusEnum.Completed
                TssLblDatabaseStatus.Image = ImgMainStatus.Images("数据同步-绿色64x64.png")
                TssLblDatabaseStatus.ToolTipText = $"数据库已同步"

                ApplicationLog.WriteInfoLog("数据库同步状态变更,已同步。")
            Case DatabaseSyncStatusEnum.UnCompleted
                TssLblDatabaseStatus.Image = ImgMainStatus.Images("数据同步-红色64x64.png")
                TssLblDatabaseStatus.ToolTipText = $"数据库未同步"

                ApplicationLog.WriteWarningLog("数据库同步状态变更,未同步。")
            Case Else
                Console.WriteLine($"数据库同步状态变更,未知类型：{dbStatus}")
                ApplicationLog.WriteErrorLog($"数据库同步状态变更,未知类型：{dbStatus}。")
        End Select
    End Sub

    ''' <summary>
    ''' 数据库同步状态修改处理事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub DatabaseStatusChanged(sender As Object, e As DatabaseStatusChangedEventArgs)
        UpdateDatabaseStatus(e.Status)
    End Sub

    ''' <summary>
    ''' 开始监控数据库状态
    ''' </summary>
    Private Sub StartMonitorDatabaseStatus()
        UpdateDatabaseStatus(DatabaseSyncStatus)

        AddHandler DatabaseStatusMonitor.DatabaseSyncStatusChanged, AddressOf DatabaseStatusChanged
    End Sub
#End Region

#Region "测试状态检测模块"

    ''' <summary>
    ''' 测试状态改变处理事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TestStatusChanged(sender As Object, e As TestStatusChangedEventArgs)
        UtsComportTask.TestStatusChanged = True
        UpdateTestStatus(e.Status)
    End Sub

    ''' <summary>
    ''' 根据测试状态,更新界面UI显示
    ''' </summary>
    ''' <param name="status"></param>
    Private Sub UpdateTestStatus(status As TestStatusEnum)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of TestStatusEnum)(AddressOf UpdateTestStatus), New Object() {status})
            Return
        End If

        'Select Case status
        '    Case TestStatusEnum.WaitForTest
        '        TssLblTestStatus.Image = ImgMainStatus.Images("server_green_25x25.png")
        '        TssLblTestStatus.ForeColor = Color.Gray
        '        TssLblTestStatus.Text = $"未测试"
        '    Case TestStatusEnum.Testing
        '        TssLblTestStatus.Image = ImgMainStatus.Images("server_yellow_27x27.png")
        '        TssLblTestStatus.ForeColor = Color.Blue
        '        TssLblTestStatus.Text = $"测试中"
        '    Case TestStatusEnum.TestPass
        '        TssLblTestStatus.Image = ImgMainStatus.Images("server_green_25x25.png")
        '        TssLblTestStatus.ForeColor = Color.Green
        '        TssLblTestStatus.Text = $"测试成功"
        '    Case TestStatusEnum.TestFail
        '        TssLblTestStatus.Image = ImgMainStatus.Images("server_red_27x27.png")
        '        TssLblTestStatus.ForeColor = Color.Red
        '        TssLblTestStatus.Text = $"测试失败"
        '    Case TestStatusEnum.DeviceError
        '        TssLblTestStatus.Image = ImgMainStatus.Images("server_red_27x27.png")
        '        TssLblTestStatus.ForeColor = Color.DarkRed
        '        TssLblTestStatus.Text = $"设备错误"
        '    Case Else
        '        Console.WriteLine($"UpdateTestStatus Unknown:{status}")
        'End Select
        '
    End Sub

    ''' <summary>
    ''' 开始监听测试状态
    ''' </summary>
    Public Sub StartMonitorTestStatus()
        UpdateTestStatus(TestStatus) '刷新项目站测试状态提示
        AddHandler TestStatusMonitor.TestStatusChanged, AddressOf TestStatusChanged
    End Sub
#End Region

#Region "项目站信息修改监测模块"
    Private Sub UpdateStationEditStatus(status As StationEditStatusEnum)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of StationEditStatusEnum)(AddressOf UpdateStationEditStatus), New Object() {status})
            Return
        End If

        Select Case status
            Case StationEditStatusEnum.None
                TssLblEditStatus.Image = ImgMainStatus.Images("编辑保存-绿色64x64.png")
                TssLblEditStatus.ToolTipText = $"测试流程未修改"

                ApplicationLog.WriteInfoLog("测试流程编辑状态变更,未修改。")
            Case StationEditStatusEnum.Changed
                TssLblEditStatus.Image = ImgMainStatus.Images("编辑保存-红色64x64.png")
                TssLblEditStatus.ToolTipText = $"测试流程已修改"

                ApplicationLog.WriteInfoLog("测试流程编辑状态变更,已修改。")
            Case StationEditStatusEnum.Saved
                TssLblEditStatus.Image = ImgMainStatus.Images("编辑保存-绿色64x64.png")
                TssLblEditStatus.ToolTipText = $"测试流程已保存"

                ApplicationLog.WriteInfoLog("测试流程编辑状态变更,已保存。")
            Case Else
                Console.WriteLine($"测试流程编辑状态变更,未知状态：{status}。")
                ApplicationLog.WriteErrorLog($"测试流程编辑状态变更,未知状态：{status}。")
        End Select
    End Sub


    Private Sub StationEditStatusChanged(sender As Object, e As StationEditStatusChangedEventArgs)
        UpdateStationEditStatus(e.Status)
    End Sub

    Private Sub StartMonitorStationEditStatus()
        UpdateStationEditStatus(StationEditStatus)
        AddHandler StationEditStatusMonitor.StationEditStatusChanged, AddressOf StationEditStatusChanged
    End Sub
#End Region

#Region "测试串口连接状态检测模块"

    Private Sub UpdateComPortStatus(comPortStatus As ComPortConnectStatusEnum)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of ComPortConnectStatusEnum)(AddressOf UpdateComPortStatus), New Object() {comPortStatus})
            Return
        End If

        Select Case comPortStatus
            Case ComPortConnectStatusEnum.Connected
                TssLblComPortStatus.Image = ImgMainStatus.Images($"测试设备-绿色64x64.png")
                TssLblComPortStatus.ToolTipText = $"测试设备已连接"

                ApplicationLog.WriteInfoLog("测试设备连接状态变更,已连接。")
            Case ComPortConnectStatusEnum.Connecting
                TssLblComPortStatus.Image = ImgMainStatus.Images($"测试设备-灰色64x64.png")
                TssLblComPortStatus.ToolTipText = $"测试设备连接中"

                ApplicationLog.WriteInfoLog("测试设备连接状态变更,连接中。")
            Case ComPortConnectStatusEnum.UnConnected
                TssLblComPortStatus.Image = ImgMainStatus.Images($"测试设备-红色64x64.png")
                TssLblComPortStatus.ToolTipText = $"测试设备已断接"

                ApplicationLog.WriteWarningLog("测试设备连接状态变更,已断接。")
            Case Else
                Console.WriteLine($"测试设备连接状态变更,未知的状态:{comPortStatus}")
                ApplicationLog.WriteErrorLog($"测试设备连接状态变更,未知的状态:{comPortStatus}")
        End Select
    End Sub


    Private Sub ComPortStatusChanged(sender As Object, e As ComportStatusChangedEventArgs)
        UpdateComPortStatus(e.Status) '刷新串口状态提示
    End Sub

    Private Sub ComportThreadCallback()
        UtsComportTask.StartTask()
    End Sub


    Private Sub StartMonitorComPortStatus()
        UpdateComPortStatus(ComportStatus) '刷新串口状态提示

        AddHandler ComportStatusMonitor.ComportStatusChanged, AddressOf ComPortStatusChanged

        '自动检测串口
        _threadComport = New Thread(AddressOf ComportThreadCallback)
        _threadComport.IsBackground = True
        _threadComport.Start()
    End Sub
#End Region

#Region "控制串口连接状态检测模块"

    Private Sub UpdateControlPortStatus(comPortStatus As ComPortConnectStatusEnum)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of ComPortConnectStatusEnum)(AddressOf UpdateControlPortStatus), New Object() {comPortStatus})
            Return
        End If

        Select Case comPortStatus
            Case ComPortConnectStatusEnum.Connected
                TssLblControllerStatus.Image = ImgMainStatus.Images($"控制器-绿色64x64.png")
                TssLblControllerStatus.ToolTipText = $"控制器已连接"
                ApplicationLog.WriteInfoLog("控制设备连接状态变更,已连接。")
            Case ComPortConnectStatusEnum.Connecting
                TssLblControllerStatus.Image = ImgMainStatus.Images($"控制器-灰色64x64.png")
                TssLblControllerStatus.ToolTipText = $"控制器连接中"
                ApplicationLog.WriteInfoLog("控制设备连接状态变更,连接中。")
            Case ComPortConnectStatusEnum.UnConnected
                TssLblControllerStatus.Image = ImgMainStatus.Images($"控制器-红色64x64.png")
                TssLblControllerStatus.ToolTipText = $"控制器已断接"
                ApplicationLog.WriteWarningLog("控制设备连接状态变更,已断接。")
            Case Else
                Console.WriteLine($"控制设备连接状态变更,未知的状态：{comPortStatus}。")
                ApplicationLog.WriteErrorLog($"控制设备连接状态变更,未知的状态：{comPortStatus}。")
        End Select
    End Sub


    Private Sub ControlPortStatusChanged(sender As Object, e As ComportStatusChangedEventArgs)
        UpdateControlPortStatus(e.Status) '刷新串口状态提示
    End Sub

    Private Sub ControlPortThreadCallback()
        Static controllerTask As ControllerComPortTask = ControllerComPortTask.CreateControllerPortTask()

        controllerTask.StartTask()
    End Sub


    Private Sub StartMonitorControlPortStatus()
        UpdateControlPortStatus(ControllerComPortStatusMonitor.ComportStatus) '刷新串口状态提示

        AddHandler ControllerComPortStatusMonitor.ComportStatusChanged, AddressOf ControlPortStatusChanged

        '自动检测串口
        _threadComport = New Thread(AddressOf ControlPortThreadCallback)
        _threadComport.IsBackground = True
        _threadComport.Start()
    End Sub

#End Region

#Region "更新时间显示模块"
    Private Sub StartMonitorTimeStatus(state As Object)
        While True
            UpdateTime(Now)
            Thread.Sleep(500)
        End While
    End Sub

    ''' <summary>
    ''' 更新时间
    ''' </summary>
    ''' <param name="time"></param>
    Private Sub UpdateTime(time As DateTime)
        Try
            If StuMain.InvokeRequired Then '判断是否需要开委托
                StuMain.Invoke(New Action(Of DateTime)(AddressOf UpdateTime), New Object() {time})
                Return
            End If

            TsLblTime.Text = $"{time:yyyy-MM-dd HH:mm:ss}"
        Catch ex As Exception

        End Try

    End Sub
#End Region

#Region "更新数据库链接状态模块"

    ''' <summary>
    ''' 更新数据库状态
    ''' </summary>
    ''' <param name="dbStatus"></param>
    Private Sub UpdateDBStatus(dbStatus As Integer)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of Integer)(AddressOf UpdateDBStatus), New Object() {dbStatus})
            Return
        End If

        Select Case dbStatus
            Case 0
                TslblDbStatus.Image = ImgMainStatus.Images("数据库-红色64x64.png")
                TslblDbStatus.ToolTipText = $"数据库连接异常"

                ApplicationLog.WriteWarningLog($"数据库状态变更,数据库连接异常。")
            Case 1
                TslblDbStatus.Image = ImgMainStatus.Images("数据库-绿色64x64.png")
                TslblDbStatus.ToolTipText = $"数据库连接正常"

                ApplicationLog.WriteInfoLog($"数据库状态变更,数据库连接正常。")
            Case Else
                TslblDbStatus.Image = ImgMainStatus.Images("数据库-灰色64x64.png")
                TslblDbStatus.ToolTipText = $"数据库连接未知"

                ApplicationLog.WriteErrorLog($"数据库状态变更,数据库连接未知。")
        End Select

    End Sub


    ''' <summary>
    ''' 更新Ftp连接状态
    ''' </summary>
    ''' <param name="ftpStatus"></param>
    Private Sub UpdateFtpStatus(ftpStatus As Integer)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of Integer)(AddressOf UpdateFtpStatus), New Object() {ftpStatus})
            Return
        End If

        Select Case ftpStatus
            Case 0
                TslblFtpStatus.Image = ImgMainStatus.Images("FTP-红色64x64.png")
                TslblFtpStatus.ToolTipText = "Ftp连接异常"

                ApplicationLog.WriteWarningLog($"Ftp状态变更,Ftp连接异常。")
            Case 1
                TslblFtpStatus.Image = ImgMainStatus.Images("FTP-绿色64x64.png")
                TslblFtpStatus.ToolTipText = $"Ftp连接正常"

                ApplicationLog.WriteInfoLog($"Ftp状态变更,Ftp连接正常。")
            Case Else
                TslblFtpStatus.Image = ImgMainStatus.Images("FTP-灰色64x64.png")
                TslblFtpStatus.ToolTipText = "Ftp连接未知"

                ApplicationLog.WriteErrorLog($"Ftp状态变更,Ftp连接未知。")
        End Select
    End Sub



    ''' <summary>
    ''' 更新同步时间
    ''' </summary>
    ''' <param name="txt"></param>
    Private Sub UpdateSyncTime(txt As String)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of String)(AddressOf UpdateSyncTime), New Object() {txt})
            Return
        End If

        If String.IsNullOrEmpty(txt) Then
            TssLblDatabaseStatus.Text = "未知"

            ApplicationLog.WriteWarningLog($"数据库同步时间变更,未知的同步时间。")
        Else
            TssLblDatabaseStatus.Text = txt

            ApplicationLog.WriteInfoLog($"数据库同步时间变更,最新时间：{txt}。")
        End If

    End Sub

    ''' <summary>
    ''' 更新网上邻居
    ''' </summary>
    ''' <param name="txt"></param>
    Private Sub UpdateNetworkNeiborhood(txt As String)
        If StuMain.InvokeRequired Then '判断是否需要开委托
            StuMain.Invoke(New Action(Of String)(AddressOf UpdateNetworkNeiborhood), New Object() {txt})
            Return
        End If

        If String.IsNullOrEmpty(txt) Then
            TsLblGroupServices.Text = "无"

            ApplicationLog.WriteWarningLog($"网上邻居变更,无网上邻居。")
        Else
            TsLblGroupServices.Text = txt

            ApplicationLog.WriteInfoLog($"网上邻居变更,当前组网上邻居：{txt}。")
        End If
    End Sub
#End Region



    ''' <summary>
    ''' 分页控件包含的页面
    ''' </summary>
    Enum TabControlEnum
        TpStationDesign
        TpStationPlan
        TpStationTest
        TpSettings
        TpHelp
        TpAbout
    End Enum

    Public Event StationChanged(station As ProcessStation) '项目变更事件

    Public Event StationRelease(station As ProcessStation) '项目发布事件

    Private _threadMonitorStatus As Thread '状态检测线程

    Private _threadComport As Thread '串口相关线程

    Private _staionType As ProcessStation.StationTypeEnum = ProcessStation.StationTypeEnum.Test


    ''' <summary>修改窗体标题</summary>
    Private Sub ShowFormTitle(Optional station As ProcessStation = Nothing)
        'Dim str As New StringBuilder
        'str.Append(Application.ProductName)
        'str.Append(String.Empty.PadRight(8, " "c))
        'str.Append(Application.ProductVersion)
        'If _utsApp.Account IsNot Nothing Then
        '    str.Append(String.Empty.PadRight(8, " "c))
        '    str.Append(_utsApp.Account.UserName)
        'End If

        'If station IsNot Nothing AndAlso station.Packet IsNot Nothing Then
        '    str.Append(String.Empty.PadRight(8, " "c))
        '    str.Append($"{station.ParentProject.Name}  -  {station.Name}")
        '    str.Append(String.Empty.PadRight(8, " "c))
        '    str.Append(station.Packet.Name)
        'End If

        'Text = Str.ToString()

        'Momo 2022-0919 修改窗口标题文字
        Dim myTitle As String = "AUTS_Win( Build:" & Application.ProductVersion
        If _utsApp.Account IsNot Nothing Then
            myTitle = myTitle & ",用户: " & _utsApp.Account.UserName
        End If

        If station IsNot Nothing AndAlso station.Packet IsNot Nothing Then
            'myTitle = myTitle & " , 项目 : " & station.ParentProject.Name
            'myTitle = myTitle & " , 站序 : " & station.ArtworkOrder
            'myTitle = myTitle & " , 站位 : " & station.Name
            'myTitle = myTitle & " , 站名 : " & station.Description
            'myTitle = myTitle & " , 配置文件 : " & station.Packet.FileName

            myTitle = myTitle & "-" & station.Packet.FileName

            ' myTitle = myTitle & " ,项目: " & station.ParentProject.Name
            myTitle = myTitle & "-[" & station.ArtworkOrder
            myTitle = myTitle & "]"
            ' myTitle = myTitle & ",站位:" & station.Name
            'myTitle = myTitle & ",站名:" & station.Description

        End If

        myTitle = myTitle & ")"

        Text = myTitle
    End Sub


    ''' <summary>
    ''' 添加项目设计窗体到分页控件中
    ''' </summary>
    Private Sub AddStationDesignFormToTabControl(pageName As String, pageText As String)
        If TabMain.TabPages.ContainsKey(pageName) Then Return
        Dim page As New TabPage With {.Name = pageName, .Text = pageText}
        Dim frm As New FrmStationDesign

        AddHandler frm.StationRelease, AddressOf Station_Released
        frm.ShowForm(page)

        TabMain.TabPages.Add(page)
    End Sub

    Private Sub AddStationPlanFormToTabControl(pageName As String, pageText As String)
        If TabMain.TabPages.ContainsKey(pageName) Then Return
        Dim page As New TabPage With {.Name = pageName, .Text = pageText}
        Dim frm As New FrmStationPlan

        frm.ShowForm(page)

        TabMain.TabPages.Add(page)
    End Sub

    Private Sub AddStationTestFormToTabControl(pageName As String, pageText As String)
        If TabMain.TabPages.ContainsKey(pageName) Then Return
        Dim page As New TabPage With {.Name = pageName, .Text = pageText}
        Dim frm As New FrmStationTest

        frm.ShowForm(page)


        TabMain.TabPages.Add(page)

    End Sub


    Private Sub AddSettingsFormToTabControl(pageName As String, pageText As String)
        Dim frm As New FrmSettings

        If TabMain.TabPages.ContainsKey(pageName) Then Return
        Dim page As New TabPage With {.Name = pageName, .Text = pageText}

        frm.ShowForm(page)

        TabMain.TabPages.Add(page)

    End Sub


    Private Sub InitTabMain()
        TabMain.SizeMode = TabSizeMode.Fixed '隐藏TabControl的表头
        TabMain.ItemSize = New Size(0, 1)


        '根据枚举顺序添加所需页面
        ApplicationLog.WriteInfoLog($"运行程序装载发布页面中。")
        AddStationDesignFormToTabControl(TabControlEnum.TpStationDesign.ToString(), "StationDesign")
        ApplicationLog.WriteInfoLog($"运行程序装载发布页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        AddStationPlanFormToTabControl(TabControlEnum.TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载测试页面中。")
        AddStationTestFormToTabControl(TabControlEnum.TpStationTest.ToString(), "StationTest")
        ApplicationLog.WriteInfoLog($"运行程序装载测试页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载设置页面中。")
        AddSettingsFormToTabControl(TabControlEnum.TpSettings.ToString(), "Settings")
        ApplicationLog.WriteInfoLog($"运行程序装载设置页面完成。")

        

        '设置初始页面
        TabMain.SelectedIndex = TabControlEnum.TpStationTest
    End Sub


    Private Sub Station_Released(station As ProcessStation)
        ApplicationLog.WriteInfoLog($"主页面站位发布中,TP:{station.Packet.Name}")

        ShowFormTitle(station)

        RaiseEvent StationRelease(station)

        ApplicationLog.WriteInfoLog($"主页面站位发布完成。")
    End Sub


    Private Sub InitializingForm()
        lblServiceID.Text = _utsApp.ServiceIndex.ToString
        LblServiceAlias.Text = _utsApp.ServiceAlias.ToString
        TsLblService.Text = $"[{IIf(_utsApp.ServiceRoles = 0, "C", "S")}]{_utsApp.License.VendorName}-{_utsApp.ServiceGroup}"
    End Sub

    ''' <summary>
    ''' 校验文件夹,若文件夹不存在则创建
    ''' </summary>
    Private Sub CheckDirectory()
        UtsPath.CheckDirectory()
    End Sub

    Private Sub LoadSettings()
        My.Settings.Reload() '读取Setting中的内容

        WinSettings.LastProjectName = My.Settings.LastProjectName
        WinSettings.LastStationName = My.Settings.LastProcessStationName
    End Sub


    Private Sub SaveSettings()
        ApplicationLog.WriteInfoLog($"运行程序设置保存中。")

        My.Settings.LastProjectName = WinSettings.LastProjectName
        My.Settings.LastProcessStationName = WinSettings.LastStationName

        My.Settings.Save()
        ApplicationLog.WriteInfoLog($"运行程序设置保存完成。")
    End Sub

    ''' <summary>
    ''' 开启所有状态监听线程
    ''' </summary>
    Private Sub StartStatusMonitorThread()

        StartMonitorNetworkStatus() '开始监听网络状态

        'StartMonitorTestStatus() '开始监听测试状态

        StartMonitorStationEditStatus() '开始监听测试站编辑状态

        StartMonitorDatabaseStatus() '开始监听数据库同步状态

        StartMonitorComPortStatus() '开始监听测试串口连接状态

        StartMonitorControlPortStatus() '开始监听控制串口连接状态

        '定期更新时间
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf StartMonitorTimeStatus))
    End Sub


    Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        AddHandler AppDomain.CurrentDomain.UnhandledException, Sub(s As Object, ea As UnhandledExceptionEventArgs)
                                                                   Dim ex As Exception = CType(ea.ExceptionObject, Exception)
                                                                   MsgBox($"UTS未处理异常，{ex}")
                                                               End Sub

        AddHandler Application.ThreadException, Sub(s As Object, ea As System.Threading.ThreadExceptionEventArgs)
                                                    MsgBox($"UTS线程异常，{ea.Exception}")
                                                End Sub

        ApplicationLog.WriteInfoLog($"{Application.ProductName} {Application.ProductVersion} 运行程序加载中。")

        '更新一切路径信息与连接信息
        CheckDirectory()

        '读取系统缓存设置
        LoadSettings()

        '初始化UTS窗体信息,失败则关闭窗体
        If InitializeUtsApp() = False Then Return

        ApplicationLog.WriteInfoLog($"服务基础信息：{_utsApp.License.VendorName}-{_utsApp.ServiceGroup}({IIf(_utsApp.ServiceRoles = 0, "C", "S")})-{_utsApp.ServiceAlias}({_utsApp.Register.ServiceIndex})")

        '填充程序可操作页面
        InitTabMain()

        '获取上一次可操作页面
        LoadLastStation()

        '初始化窗体页面
        InitializingForm()

        '开始状态检测线程
        StartStatusMonitorThread()

        ApplicationLog.WriteInfoLog("运行程序加载完成。")
    End Sub

    Private Sub LoadLastStation()
        '获取上一次打开信息
        ApplicationLog.WriteInfoLog($"PN:{WinSettings.LastProjectName} SN:{WinSettings.LastStationName} 站位信息加载中。")

        _utsApp.LoadStation(WinSettings.LastProjectName, WinSettings.LastStationName)

        ApplicationLog.WriteInfoLog("站位信息加载完成。")
    End Sub

    Private Function InitializeUtsApp() As Boolean
        _utsApp = UtsAppForm.CreateSingleton()
        _utsApp.AddStatisticsObserver(Me)

        AddHandler _utsApp.DbStatusChanged, AddressOf UpdateDBStatus
        AddHandler _utsApp.FtpStatusChanged, AddressOf UpdateFtpStatus
        AddHandler _utsApp.SyncTimeChanged, AddressOf UpdateSyncTime
        AddHandler _utsApp.ServicesChanged, AddressOf UpdateNetworkNeiborhood

        Try
            If _utsApp.IsInitialized = False Then
                _utsApp.Initialize(ProcessStation.StationTypeEnum.Test) 'Todo:可根据需要限定可选站位           
            End If
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"初始化窗体失败,原因：{ex.Message}。")

            MsgBox($"初始化窗体失败,原因：{ex.Message}")
            Close()
            Return False
        End Try

        Return True
    End Function


    Private Sub UtsKeyDownCallback(sender As Object, e As UtsKeyDownEventArgs)
        If StuMain.InvokeRequired Then
            StuMain.Invoke(New Action(Of UtsKeyValueMonitor.UtsKeyValueEnum)(AddressOf UpdateKey), New Object() {e.KeyValue})
        Else
            UpdateKey(e.KeyValue)
        End If
    End Sub


    Private Sub UpdateKey(key As UtsKeyValueMonitor.UtsKeyValueEnum)
        TssLblKeyDown.Text = $"{key}"

        ApplicationLog.WriteInfoLog($"控制器按键按下，键值：{key}。")
    End Sub


    Private Sub FrmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown

        AddHandler UtsKeyValueMonitor.UtsKeyDown, AddressOf UtsKeyDownCallback
    End Sub

    Private Sub TsmStation_Click(sender As Object, e As EventArgs) Handles MsiStationDesign.Click
        'TabMain.SelectedIndex = TabControlEnum.TpStationDesign
    End Sub

    Private Sub MsiStationPlan_Click(sender As Object, e As EventArgs) Handles MsiStationPlan.Click
        'TabMain.SelectedIndex = TabControlEnum.TpStationPlan
    End Sub

    ''' <summary>
    ''' 打开或切换项目 Momo 2023-12-15：打开或切换项目前先进行权限验证
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnOpenStation_Click(sender As Object, e As EventArgs) Handles TsBtnOpenStation.Click
        Dim failCount As Integer = 0
        Dim tmpPwd As String = "123456"

        If _utsApp.ProcessStation Is Nothing Then
            tmpPwd = "123456"
        Else
            tmpPwd = _utsApp.ProcessStation.Packet.EditPwd
        End If

        Dim pwd As String = UtsInputBox.ShowDialog("请输入编辑密码（新项目第一次密码 123456）", $"第{failCount}次解锁", "", True)

        If pwd Is Nothing Then Return
        If String.Compare(pwd, tmpPwd, True) = 0 Then
            ApplicationLog.WriteInfoLog($"解锁打开项目。")
            failCount = 0
            _utsApp.ChangeStation()
        Else
            failCount += 1

            ApplicationLog.WriteWarningLog($"打开项目第[{failCount}]次解锁失败。")
            If failCount > 3 Then
                ApplicationLog.WriteFatalLog($"打开项目第[{failCount}]次解锁失败，程序关闭。")
                Application.Exit()
                Return
            End If
        End If

    End Sub

    Private Sub MsiSettings_Click(sender As Object, e As EventArgs) Handles MsiSettings.Click
        'TabMain.SelectedIndex = TabControlEnum.TpSettings
    End Sub

    Private Sub TsBtnStationTest_Click(sender As Object, e As EventArgs) Handles TsBtnStationTest.Click
        TabMain.SelectedIndex = TabControlEnum.TpStationTest
    End Sub

    Private Sub TsBtnStationDesign_Click(sender As Object, e As EventArgs) Handles TsBtnStationDesign.Click
        TabMain.SelectedIndex = TabControlEnum.TpStationDesign
    End Sub

    Private Sub TsBtnStationPlan_Click(sender As Object, e As EventArgs) Handles TsBtnStationPlan.Click
        TabMain.SelectedIndex = TabControlEnum.TpStationPlan
    End Sub

    Private Sub TabMain_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabMain.SelectedIndexChanged
        Select Case TabMain.SelectedIndex
            Case TabControlEnum.TpStationTest
                TsBtnStationTest.BackColor = Color.ForestGreen
                TsBtnStationDesign.BackColor = Color.Transparent
                TsBtnStationPlan.BackColor = Color.Transparent

                TsBtnStationTest.ForeColor = Color.White
                TsBtnStationDesign.ForeColor = Color.Black
                TsBtnStationPlan.ForeColor = Color.Black

                ApplicationLog.WriteInfoLog($"当前页面：测试页面。")
            Case TabControlEnum.TpStationDesign
                TsBtnStationTest.BackColor = Color.Transparent
                TsBtnStationDesign.BackColor = Color.ForestGreen
                TsBtnStationPlan.BackColor = Color.Transparent

                TsBtnStationTest.ForeColor = Color.Black
                TsBtnStationDesign.ForeColor = Color.White
                TsBtnStationPlan.ForeColor = Color.Black

                ApplicationLog.WriteInfoLog($"当前页面：发布页面。")
            Case TabControlEnum.TpStationPlan
                TsBtnStationTest.BackColor = Color.Transparent
                TsBtnStationDesign.BackColor = Color.Transparent
                TsBtnStationPlan.BackColor = Color.ForestGreen

                TsBtnStationTest.ForeColor = Color.Black
                TsBtnStationDesign.ForeColor = Color.Black
                TsBtnStationPlan.ForeColor = Color.White

                ApplicationLog.WriteInfoLog($"当前页面：编辑页面。")
        End Select
    End Sub

    Private Sub MsiAbout_Click(sender As Object, e As EventArgs) Handles MsiAbout.Click

    End Sub

    Private Sub FrmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        ApplicationLog.WriteInfoLog($"{Application.ProductName} {Application.ProductVersion} 运行程序关闭中。")
        If StationEditStatus = StationEditStatusEnum.Changed Then
            If MessageBox.Show($"检测到未保存的测试流程,是否继续退出？", $"Tip", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) = DialogResult.Cancel Then
                e.Cancel = True

                ApplicationLog.WriteInfoLog($"运行程序已取消关闭。")
            End If
        End If

        SaveSettings()
        ApplicationLog.WriteInfoLog($"运行程序已关闭。")
    End Sub



    Private Sub TsBtnEditLock_Click(sender As Object, e As EventArgs) Handles TsBtnEditLock.Click
        Static failCount As Integer = 1

        If TsBtnStationPlan.Visible = False Then
            If _utsApp.ProcessStation Is Nothing Then
                UtsMsgBox.ShowDialog("请选择项目后再解锁编辑功能！")
                Return
            End If

            Dim pwd As String = UtsInputBox.ShowDialog("请输入编辑密码（新项目第一次编辑密码 123456）", $"第{failCount}次编辑解锁", "", True)

            If pwd Is Nothing Then Return
            If String.Compare(pwd, _utsApp.ProcessStation.Packet.EditPwd, True) = 0 Then
                ApplicationLog.WriteInfoLog($"编辑页面已解锁。")

                failCount = 0
                TsBtnEditLock.Text = "编辑加锁"
                TsBtnStationPlan.Visible = True
                TabMain.SelectedIndex = TabControlEnum.TpStationPlan
            Else
                failCount += 1

                ApplicationLog.WriteWarningLog($"编辑页面第[{failCount}]次解锁失败。")
                If failCount > 3 Then
                    ApplicationLog.WriteFatalLog($"编辑页面第[{failCount}]次解锁失败，程序关闭。")

                    Application.Exit()
                End If
            End If
        Else
            If UtsMsgBox.ShowDialog("为防止误操作，请确定关闭编辑功能！", UtsMsgBox.UtsMsgBoxTypeEnum.YesNo) = DialogResult.OK Then
                ApplicationLog.WriteInfoLog($"编辑页面已加锁。")

                TsBtnEditLock.Text = "编辑解锁"
                TsBtnStationPlan.Visible = False
                TabMain.SelectedIndex = TabControlEnum.TpStationTest
            End If
        End If
    End Sub

    Private Sub TsBtnReleaseLock_Click(sender As Object, e As EventArgs) Handles TsBtnReleaseLock.Click
        Static failCount As Integer = 1
        Static isLock As Boolean = True

        If TsBtnStationDesign.Visible = False Then
            If _utsApp.ProcessStation Is Nothing Then
                UtsMsgBox.ShowDialog("请选择项目后再发布编辑功能！")
                Return
            End If

            Dim pwd As String = UtsInputBox.ShowDialog("请输入发布密码（新项目第一次发布密码 00803）", $"第{failCount}次发布解锁", "", True)

            If pwd Is Nothing Then Return
            If String.Compare(pwd, _utsApp.ProcessStation.Packet.ReleasePwd, True) = 0 Then
                ApplicationLog.WriteInfoLog($"发布页面已解锁。")

                failCount = 0
                isLock = False
                TsBtnReleaseLock.Text = "发布加锁"
                TsBtnStationDesign.Visible = True
                TabMain.SelectedIndex = TabControlEnum.TpStationDesign
            Else
                failCount += 1

                ApplicationLog.WriteWarningLog($"发布页面第[{failCount}]次解锁失败。")
                If failCount > 3 Then
                    ApplicationLog.WriteFatalLog($"发布页面第[{failCount}]次解锁失败，程序关闭。")

                    Application.Exit()
                End If
            End If
        Else
            If UtsMsgBox.ShowDialog("为防止误操作，请确定关闭发布功能！", UtsMsgBox.UtsMsgBoxTypeEnum.YesNo) = DialogResult.OK Then
                ApplicationLog.WriteInfoLog($"发布页面已加锁。")

                isLock = True
                TsBtnReleaseLock.Text = "发布解锁"
                TsBtnStationDesign.Visible = False
                TabMain.SelectedIndex = TabControlEnum.TpStationTest

            End If
        End If
    End Sub

    ''' <summary>
    ''' 站位修改处理函数
    ''' </summary>
    Private Sub IProcessStation_StationChanged() Implements IProcessStation.StationChanged
        ApplicationLog.WriteInfoLog($"主页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}。")

        WinSettings.LastProjectName = _utsApp.ProcessStation.ParentProject.Name
        WinSettings.LastStationName = _utsApp.ProcessStation.Name

        '项目站包路径
        Dim packetName As String = _utsApp.ProcessStation.Packet.Name
        UtsPath.StationPacketDirPath = UtsPath.GetStationPacketDirPath(packetName)
        UtsPath.StationPacketInfoPath = UtsPath.GetStationPacketInfoPath(packetName)
        UtsPath.StationPacketResourceDirPath = UtsPath.GetStationPacketResourceDirPath(packetName)
        UtsPath.StationPacketTestPlanDirPath = UtsPath.GetStationPacketTestPlanDirPath(packetName)

        TsBtnStationPlan.Visible = False
        TsBtnEditLock.Text = "编辑解锁"

        TsBtnStationDesign.Visible = False
        TsBtnReleaseLock.Text = "发布解锁"

        TabMain.SelectedIndex = TabControlEnum.TpStationTest

        ShowFormTitle(_utsApp.ProcessStation)

        ApplicationLog.WriteInfoLog($"主页面站位变更完成。")
    End Sub

    ''' <summary>
    ''' 产线修改后处理函数
    ''' </summary>
    Public Sub ProductionLineChanged() Implements IProductionLine.ProductionLineChanged
        ApplicationLog.WriteInfoLog($"主页面生产线变更中。")


        ApplicationLog.WriteInfoLog($"主页面生产线变更完成。")
    End Sub

    Private Sub MsiUser_Click(sender As Object, e As EventArgs) Handles MsiUser.Click
        'ThreadPool.QueueUserWorkItem(Sub()
        '                                 Throw New Exception("自定义线程错误")
        '                             End Sub)

    End Sub

    Private Sub MsiHelp_Click(sender As Object, e As EventArgs) Handles MsiHelp.Click
        'Throw New Exception("自定义UI线程错误")
    End Sub

End Class
