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.Controls
Imports UTS_Core.UTSModule.Test.StatusMonitor
Imports UTS_Core.UTSModule.Test.StatusMonitor.DatabaseStatusMonitor
Imports UTS_Core.UTSModule.Test.StatusMonitor.StationEditStatusMonitor


#Const BM_ITM53 = 0
#Const ZQ_Mars = 1

#If ZQ_Mars Then

#Const ZQ_Mars_P1 = 1
#Const ZQ_Mars_P2 = 1
#Const ZQ_Mars_P3 = 0
#Const ZQ_Phobos_T1 = 0
#Const ZQ_Phobos_T2 = 0
#Const ZQ_Mars_SELECT = ZQ_Mars_P1

#End If
#If BM_ITM53 Then
#Const BM_ITM53_P1 = 1
#Const BM_ITM53_P2 = 1
#Const BM_ITM53_P3 = 1
#Const BM_ITM53_SELECT = BM_ITM53_P1
#End If

Public Class FrmMain
    Implements IProcessStation
    Implements IProductionLine

    Private _utsApp As UtsAppForm
    Private _DefaultTestPage As Integer
    Private _DefaultPlanPage As Integer
    Public Event StationRelease(station As ProcessStation) '项目发布事件

#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 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


    Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        ApplicationLog.WriteInfoLog($"{Application.ProductName} {Application.ProductVersion} 运行程序加载中。")

        '初始化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() '填充程序可操作页面

        '加载上次关闭前页面
        ApplicationLog.WriteInfoLog($"PN:{My.Settings.Project} SN:{My.Settings.ProcessStation} 站位信息加载中。")
        _utsApp.LoadStation(My.Settings.Project, My.Settings.ProcessStation)
        ApplicationLog.WriteInfoLog("站位信息加载完成。")

        '初始化窗体页面
        InitializeForm()

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

#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="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

#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)
        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}"
    End Sub
#End Region

    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.Package) '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 InitializeForm()
        lblServiceID.Text = _utsApp.Register.ServiceIndex.ToString
        LblServiceAlias.Text = _utsApp.ServiceAlias.ToString
        TsLblService.Text = $"[{IIf(_utsApp.ServiceRoles = 0, "C", "S")}]{_utsApp.License.VendorName}-{_utsApp.ServiceGroup}"

        StartMonitorNetworkStatus()

        StartMonitorStationEditStatus()

        StartMonitorDatabaseStatus()

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

    ''' <summary>修改窗体标题</summary>
    Private Sub ShowFormTitle(Optional station As ProcessStation = Nothing)
        Dim myTitle As String = "AUTS_FunctionTest  ( 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
        End If

        myTitle = myTitle & " )"

        Text = myTitle
    End Sub

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


        '根据枚举顺序添加所需页面
        '  AddProjectFormToTabControl(TabControlEnum.TpProject.ToString(), "Project")

        ApplicationLog.WriteInfoLog($"运行程序装载发布页面中。")
        AddStationDesignFormToTabControl(TabControlEnum.TpStationDesign.ToString(), "StationDesign")
        ApplicationLog.WriteInfoLog($"运行程序装载发布页面完成。")
#If BM_ITM53_P1 Then
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        AddStationPlanFormToTabControl(TabControlEnum.BM_ITM53_P1_TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

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


#If ZQ_Mars_SELECT = BM_ITM53_SELECT Then
        TabMain.SelectedIndex = TabControlEnum.TpStationTest
       _DefaultTestPage = TabControlEnum.BM_ITM53_P1_TpStationTest
        _DefaultPlanPage = TabControlEnum.BM_ITM53_P1_TpStationPlan
#End If

#End If

#If ZQ_Mars_P1 Then
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        ZQ_Mars_Plan_FormToTabControl(TabControlEnum.ZQ_MARS_P1_TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载测试页面中。")
        ZQ_Mars_Test_FormToTabControl(TabControlEnum.ZQ_MARS_P1_TpStationTest.ToString(), "StationTest")
        ApplicationLog.WriteInfoLog($"运行程序装载测试页面完成。")
        _DefaultTestPage = TabControlEnum.ZQ_MARS_P1_TpStationTest
        _DefaultPlanPage = TabControlEnum.ZQ_MARS_P1_TpStationPlan

#End If
#If ZQ_Mars_P2 Then
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        ZQ_Mars_Plan_FormToTabControl(TabControlEnum.ZQ_MARS_P2_TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载测试页面中。")
        ZQ_Mars_Test_FormToTabControl(TabControlEnum.ZQ_MARS_P2_TpStationTest.ToString(), "StationTest")
        ApplicationLog.WriteInfoLog($"运行程序装载测试页面完成。")
       
     
                _DefaultTestPage = TabControlEnum.ZQ_MARS_P2_TpStationTest
                _DefaultPlanPage = TabControlEnum.ZQ_MARS_P2_TpStationPlan
     
#End If
#If ZQ_Mars_P3 Then
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        ZQ_Mars_Plan_FormToTabControl(TabControlEnum.ZQ_MARS_P3_TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载测试页面中。")
        ZQ_Mars_Test_FormToTabControl(TabControlEnum.ZQ_MARS_P3_TpStationTest.ToString(), "StationTest")
        ApplicationLog.WriteInfoLog($"运行程序装载测试页面完成。")
       
                _DefaultTestPage = TabControlEnum.ZQ_MARS_P3_TpStationTest
                _DefaultPlanPage = TabControlEnum.ZQ_MARS_P3_TpStationPlan
       
#End If

#If ZQ_Phobos_T1 Then
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        ZQ_Phobos_Plan_FormToTabControl(TabControlEnum.ZQ_Phobos_T1_TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载测试页面中。")
        ZQ_Phobos_Test_FormToTabControl(TabControlEnum.ZQ_Phobos_T1_TpStationTest.ToString(), "StationTest")
        ApplicationLog.WriteInfoLog($"运行程序装载测试页面完成。")
#End If
#If ZQ_Phobos_T2 Then
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面中。")
        ZQ_Phobos_Plan_FormToTabControl(TabControlEnum.ZQ_Phobos_T2_TpStationPlan.ToString(), "StationPlan")
        ApplicationLog.WriteInfoLog($"运行程序装载编辑页面完成。")

        ApplicationLog.WriteInfoLog($"运行程序装载测试页面中。")
        ZQ_Phobos_Test_FormToTabControl(TabControlEnum.ZQ_Phobos_T2_TpStationTest.ToString(), "StationTest")
        ApplicationLog.WriteInfoLog($"运行程序装载测试页面完成。")
#End If


        TabMain.SelectedIndex = _DefaultTestPage

        '设置初始页面

    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 FrmStationRelease

        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 BM_ITM53_P1_FrmStationPlan

        frm.ShowForm(page)

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


        If pageName.ToLower.Contains("p1") Then
            Dim frm As New ZQ_Mars_P1_FrmStationPlan
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("p2") Then
            Dim frm As New ZQ_Mars_T2_FrmStationPlan
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("p3") Then
            Dim frm As New ZQ_Mars_P3_FrmStationPlan

            frm.ShowForm(page)
        End If

        TabMain.TabPages.Add(page)
    End Sub

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


        If pageName.ToLower.Contains("t1") Then
            Dim frm As New ZQ_Phobos_T1_FrmStationPlan
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("t2") Then
            Dim frm As New ZQ_Phobos_T2_FrmStationPlan
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("t3") Then
            'Dim frm As New ZQ_Phobos_T3_FrmStationPlan

            'frm.ShowForm(page)
        End If

        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 BM_ITM53_P1_FrmStationTest

        frm.ShowForm(page)

        TabMain.TabPages.Add(page)
    End Sub

    Private Sub ZQ_Mars_Test_FormToTabControl(pageName As String, pageText As String)
        If TabMain.TabPages.ContainsKey(pageName) Then Return
        Dim page As New TabPage With {.Name = pageName, .Text = pageText}
        If pageName.ToLower.Contains("p1") Then
            Dim frm As New ZQ_Mars_P1_FrmStationTest
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("p2") Then
            Dim frm As New ZQ_Mars_T2_FrmStationTest
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("p3") Then
            Dim frm As New ZQ_Mars_P3_FrmStationTest
            frm.ShowForm(page)
        End If
        TabMain.TabPages.Add(page)
    End Sub
    Private Sub ZQ_Phobos_Test_FormToTabControl(pageName As String, pageText As String)
        If TabMain.TabPages.ContainsKey(pageName) Then Return
        Dim page As New TabPage With {.Name = pageName, .Text = pageText}
        If pageName.ToLower.Contains("t1") Then
            Dim frm As New ZQ_Phobos_T1_FrmStationTest
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("t2") Then
            Dim frm As New ZQ_Phobos_T2_FrmStationTest
            frm.ShowForm(page)
        ElseIf pageName.ToLower.Contains("t3") Then
            Dim frm As New ZQ_Mars_P3_FrmStationTest
            frm.ShowForm(page)
        End If

        TabMain.TabPages.Add(page)
    End Sub

    Private Sub TsBtnStationTest_Click(sender As Object, e As EventArgs) Handles TsBtnStationTest.Click
        TabMain.SelectedIndex = _DefaultTestPage
    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 = _DefaultPlanPage
    End Sub

    Private Sub TabMain_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabMain.SelectedIndexChanged
        Select Case TabMain.SelectedIndex
            Case _DefaultTestPage
                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 _DefaultPlanPage
                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 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("请输入编辑密码", $"第{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 = _DefaultPlanPage
            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 = _DefaultTestPage
            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("请输入发布密码", $"第{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 = _DefaultTestPage
            End If
        End If

    End Sub

    Private Sub TsBtnOpenStation_Click(sender As Object, e As EventArgs) Handles TsBtnOpenStation.Click
        Try
            _utsApp.ChangeStation()

        Catch ex As Exception
            MsgBox($"ChangeStation Error:{ex.Message}")
        End Try
    End Sub


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

        ShowFormTitle(station)

        RaiseEvent StationRelease(station)

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

    Public Sub Station_Changed() Implements IProcessStation.StationChanged
        ApplicationLog.WriteInfoLog($"主页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}。")

        My.Settings.Project = _utsApp.ProcessStation.ParentProject.Name
        My.Settings.ProcessStation = _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 = "发布解锁"
#If ZQ_Mars Then
        If _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p1") Then
#If ZQ_Mars_P1 Then
            'TabMain.SelectedIndex = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultTestPage = TabControlEnum.ZQ_MARS_P1_TpStationTest
            _DefaultPlanPage = TabControlEnum.ZQ_MARS_P1_TpStationPlan
#End If
        ElseIf _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p2") Then

#If ZQ_Mars_P2 Then
            'TabMain.SelectedIndex = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultTestPage = TabControlEnum.ZQ_MARS_P2_TpStationTest
            _DefaultPlanPage = TabControlEnum.ZQ_MARS_P2_TpStationPlan
#End If
        ElseIf _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p3") Then
            _DefaultTestPage = TabControlEnum.TpStationDesign
#If ZQ_Mars_P3 Then
            'TabMain.SelectedIndex = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultTestPage = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultPlanPage = TabControlEnum.ZQ_MARS_P3_TpStationPlan
#End If
        ElseIf _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p3") Then

#If ZQ_Phobos_T1 Then
            'TabMain.SelectedIndex = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultTestPage = TabControlEnum.ZQ_Phobos_T1_TpStationTest
            _DefaultPlanPage = TabControlEnum.ZQ_Phobos_T1_TpStationPlan
#End If
        ElseIf _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p3") Then

#If ZQ_Phobos_T2 Then
            'TabMain.SelectedIndex = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultTestPage = TabControlEnum.ZQ_Phobos_T2_TpStationTest
            _DefaultPlanPage = TabControlEnum.ZQ_Phobos_T2_TpStationPlan
#End If
        End If
#End If

#If BM_ITM53 Then
                If _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p1") Then
#If  BM_ITM53_P1 Then
            'TabMain.SelectedIndex = TabControlEnum.BM_ITM53_P1_TpStationTest
            _DefaultTestPage = TabControlEnum.BM_ITM53_P1_TpStationTest
            _DefaultPlanPage = TabControlEnum.BM_ITM53_P1_TpStationPlan
#End If
        ElseIf _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p2") Then

#If  BM_ITM53_P2 Then
            'TabMain.SelectedIndex = TabControlEnum.BM_ITM53_P2_TpStationTest
            _DefaultTestPage = TabControlEnum.BM_ITM53_P2_TpStationTest
            _DefaultPlanPage = TabControlEnum.BM_ITM53_P2_TpStationPlan
#End If
        ElseIf _utsApp.ProcessStation.Name.ToLower.Trim.Equals("p3") Then

#If BM_ITM53_P3 Then
            'TabMain.SelectedIndex = TabControlEnum.ZQ_MARS_P3_TpStationTest
            _DefaultTestPage = TabControlEnum.BM_ITM53_P3_TpStationTest
            _DefaultPlanPage = TabControlEnum.BM_ITM53_P3_TpStationPlan
#End If
        End If
#End If



        TabMain.SelectedIndex = _DefaultTestPage



        ShowFormTitle(_utsApp.ProcessStation)

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

    Public Sub ProductionLineChanged() Implements IProductionLine.ProductionLineChanged
        ApplicationLog.WriteInfoLog($"主页面生产线变更中。")

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

    ''' <summary>
    ''' 分页控件包含的页面
    ''' </summary>
    Enum TabControlEnum
        ''' <summary>发布页面</summary>
        TpStationDesign

#If BM_ITM53 Then
          ''' <summary>编辑页面</summary>
        BM_ITM53_P1_TpStationPlan 
        ''' <summary>测试页面</summary>
        BM_ITM53_P1_TpStationTest
#End If


#If ZQ_Mars Then
#If ZQ_Mars_P1 Then

        ''' <summary>ZQ编辑页面</summary>
        ZQ_MARS_P1_TpStationPlan
        ''' <summary>ZQ测试页面</summary>
        ZQ_MARS_P1_TpStationTest

#End If
#If ZQ_Mars_P2 Then
        ''' <summary>ZQ编辑页面</summary>
        ZQ_MARS_P2_TpStationPlan
        ''' <summary>ZQ测试页面</summary>
        ZQ_MARS_P2_TpStationTest

#End If
#If ZQ_Mars_P3 Then
  ''' <summary>ZQ编辑页面</summary>
        ZQ_MARS_P3_TpStationPlan
        ''' <summary>ZQ测试页面</summary>
        ZQ_MARS_P3_TpStationTest
#End If
#If ZQ_Phobos_T1 Then
        ''' <summary>ZQ编辑页面</summary>
        ZQ_Phobos_T1_TpStationPlan
        ''' <summary>ZQ测试页面</summary>
        ZQ_Phobos_T1_TpStationTest
#End If
#If ZQ_Phobos_T2 Then
        ''' <summary>ZQ编辑页面</summary>
        ZQ_Phobos_T2_TpStationPlan
        ''' <summary>ZQ测试页面</summary>
        ZQ_Phobos_T2_TpStationTest
#End If


#End If

        ''' <summary>设置页面(未填充)</summary>
        TpSettings
        ''' <summary>帮助页面(未填充)</summary>
        TpHelp
        ''' <summary>关于页面(未填充)</summary>
        TpAbout
    End Enum

    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} 运行程序关闭中。")

        tim_UpdateTime.Stop()

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

    Private Sub tim_UpdateTime_Tick(sender As Object, e As EventArgs) Handles tim_UpdateTime.Tick
        UpdateTime(Now)
    End Sub
End Class