Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Service

Public Class FrmMain

#Region "窗体初始化"
    ''' <summary>
    ''' 窗体加载时启动项
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        InitSerName()

        InitTabMain()

        InitGrid()

        Text = $"{Application.ProductName} {Application.ProductVersion}"
    End Sub


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

    End Sub


    ''' <summary> 初始化本地IP </summary>
    Private Sub InitSerName()
        TsCboServiceName.Items.Clear()

        InitUtsServices()

        For Each service As UtsService In _services
            TsCboServiceName.Items.Add(service.Name)
        Next

        If TsCboServiceName.Items.Count > 0 Then TsCboServiceName.SelectedIndex = 0
    End Sub


#End Region


#Region "服务控制信息"
    ''' <summary>
    ''' 所有服务的信息
    ''' </summary>
    Private _services As List(Of UtsService)

    Private _service As UtsService


    Private Sub InitUtsServices()
        _services = New List(Of UtsService)()

        Try
            _services.Add(New UtsService(UtsRegistry.UpdateServiceName, UtsRegistry.UpdateServiceVersion))
        Catch ex As Exception
            Console.WriteLine($"Init UpdateService Error:{ex.Message}")
        End Try


        Try
            _services.Add(New UtsService(UtsRegistry.DataServiceName, UtsRegistry.DataServiceVersion))
        Catch ex As Exception
            Console.WriteLine($"Init DataService Error:{ex.Message}")
        End Try
    End Sub


    ''' <summary>
    ''' 选择下拉框改变值
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsCboServiceName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TsCboServiceName.SelectedIndexChanged
        _service = _services(TsCboServiceName.SelectedIndex)

        TssLblServiceName.Text = $"{_service.Name} {_service.Version} :"
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub

    Private Sub TsBtnReflushServices_Click(sender As Object, e As EventArgs) Handles TsBtnReflushServices.Click
        InitSerName()
    End Sub

    ''' <summary>
    ''' 更新服务状态
    ''' </summary>
    ''' <param name="status"></param>
    Private Sub UpdateServiceStatusTip(status As UtsService.ServiceStatusEnum)
        Static tipColor() As Color = {Color.Gray, Color.Red, Color.Aquamarine, Color.Blue, Color.Orange, Color.Blue, Color.Green}

        TssLblServiceStatus.ForeColor = tipColor(status)
        TssLblServiceStatus.Text = $"{ UtsService.GetEnumDescription(status)}"

        UpdateServiceEnabled(status)
    End Sub



    Private Sub UpdateServiceEnabled(status As UtsService.ServiceStatusEnum)
        If status <= UtsService.ServiceStatusEnum.Nonentity Then '服务不存在状态
            TsBtnStartService.Enabled = False
            TsBtnCloseService.Enabled = False
            TsBtnRestartService.Enabled = False
            TsBtnConnService.Enabled = False
            TsBtnServiceInstall.Enabled = False
            TsBtnServiceUninstall.Enabled = False

            If _tcpClient IsNot Nothing Then
                _tcpClient.Close()
                UpdateTcpTip(_tcpClient.IsOpen) '更新连接提示
                UpdateConnectionEnabled(_tcpClient.IsOpen) '根据连接,设置控件可操作性
            End If
        ElseIf status <= UtsService.ServiceStatusEnum.StartPending Then '服务存在未启用状态
            TsBtnStartService.Enabled = True
            TsBtnCloseService.Enabled = True
            TsBtnRestartService.Enabled = True
            TsBtnConnService.Enabled = False

            TsBtnServiceInstall.Enabled = True
            TsBtnServiceUninstall.Enabled = True

            If _tcpClient IsNot Nothing Then
                _tcpClient.Close()
                UpdateTcpTip(_tcpClient.IsOpen) '更新连接提示
                UpdateConnectionEnabled(_tcpClient.IsOpen) '根据连接,设置控件可操作性
            End If
        Else '服务存在且启用状态
            TsBtnStartService.Enabled = True
            TsBtnCloseService.Enabled = True
            TsBtnRestartService.Enabled = True
            TsBtnConnService.Enabled = True
            TsBtnServiceInstall.Enabled = True
            TsBtnServiceUninstall.Enabled = True

            Try
                If _tcpClient Is Nothing Then
                    InitTcpClient()
                    _tcpClient.Open()

                ElseIf _tcpClient.IsOpen = False Then
                    _tcpClient.Open()

                End If

                UpdateTcpTip(_tcpClient.IsOpen) '更新连接提示
                UpdateConnectionEnabled(_tcpClient.IsOpen) '根据连接,设置控件可操作性
            Catch ex As Exception
                Console.WriteLine($"Tcp Client Open Error:{ex.Message}")
            End Try
        End If
    End Sub


    ''' <summary>
    ''' 工具栏检测服务按键
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnTestingServices_Click(sender As Object, e As EventArgs) Handles TsBtnTestingServices.Click
        If _service Is Nothing Then Return
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub


    ''' <summary>
    ''' 工具栏点击一键安装
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnServiceInstall_Click(sender As Object, e As EventArgs) Handles TsBtnServiceInstall.Click
        Try
            _service.InstallService()
            MsgBox($"{_service.Name}服务安装成功!")
        Catch ex As Exception
            MsgBox($"InstallService Error:{ex.Message}")
        End Try
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub

    ''' <summary>
    ''' 工具栏卸载按键
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnServiceUninstall_Click(sender As Object, e As EventArgs) Handles TsBtnServiceUninstall.Click
        If MsgBox($"是否确定卸载操作", MsgBoxStyle.OkCancel) <> MsgBoxResult.Ok Then Return

        Try
            _service.UnInstallService()
            MsgBox($"{_service.Name}服务卸载成功!")
        Catch ex As Exception
            MsgBox($"UnInstallService Error:{ex.Message}")
        End Try
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub

    ''' <summary>
    ''' 工具栏启用服务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnStartService_Click(sender As Object, e As EventArgs) Handles TsBtnStartService.Click
        Try
            _service.StartService()
        Catch ex As Exception
            MsgBox($"StartService Error:{ex.Message}")
        End Try
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub

    ''' <summary>
    ''' 工具栏停止服务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnCloseService_Click(sender As Object, e As EventArgs) Handles TsBtnCloseService.Click
        Try
            _service.StopService()
        Catch ex As Exception
            MsgBox($"StopService Error:{ex.Message}")
        End Try
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub


    ''' <summary>
    ''' 工具栏重启服务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnRestartService_Click(sender As Object, e As EventArgs) Handles TsBtnRestartService.Click
        Try
            _service.RestartService()
        Catch ex As Exception
            MsgBox($"RestartService Error:{ex.Message}")
        End Try
        UpdateServiceStatusTip(_service.ServicesStatus())
    End Sub

#End Region


#Region "任务表格操作"
    Enum ColNameEnum
        Sn
        Act
        Type
        Name
        Max
    End Enum


    Private Sub InitGrid()
        With Grid1
            .NewFile()
            .BorderStyle = FlexCell.BorderStyleEnum.None
            .BackColorBkg = Color.Transparent
            .DisplayRowNumber = True
            .AutoRedraw = False
            .ExtendLastCol = True
            .Rows = 1
            .Cols = ColNameEnum.Max

            .Column(ColNameEnum.Sn).Width = 20
            .Column(ColNameEnum.Act).Width = 30
            .Column(ColNameEnum.Type).Width = 40
            .Column(ColNameEnum.Act).CellType = FlexCell.CellTypeEnum.CheckBox

            For col As Integer = 0 To ColNameEnum.Max - 1
                .Cell(0, col).Text = [Enum].GetName(GetType(ColNameEnum), col) '设置列名
            Next

            .AutoRedraw = True
            .Refresh()
        End With
    End Sub

    Private Sub Grid1_SelChange(sender As Object, e As FlexCell.Grid.SelChangeEventArgs) Handles Grid1.SelChange
        If e.FirstRow > 0 Then
            TabTasks.SelectedIndex = e.FirstRow - 1
        End If
    End Sub




#End Region


#Region "服务通讯"
    Private _tcpClient As AutsTcpClient

    ''' <summary>
    ''' 连接服务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnConnService_Click(sender As Object, e As EventArgs) Handles TsBtnConnService.Click
        UpdateTcpClient()
    End Sub

    ''' <summary>
    ''' 初始化网络套接字
    ''' 注册表中无端口号时会引发异常
    ''' </summary>
    Private Sub InitTcpClient()
        Static remoteIp As String = "127.0.0.1"
        Static remotePort As Integer = -1 '默认55533,实际使用从注册表中获取

        remotePort = CInt(UtsRegistry.DataServicePort)

        _tcpClient = New AutsTcpClient(remoteIp, remotePort)
    End Sub


    Private Sub UpdateTcpClient()
        Dim tcpConnect As Boolean
        If _tcpClient IsNot Nothing AndAlso _tcpClient.IsOpen Then
            _tcpClient.Close()
            tcpConnect = False
        Else
            Try
                InitTcpClient()
                _tcpClient.Open()
                tcpConnect = True
            Catch ex As Exception
                Console.WriteLine($"Open Tcp Client Error:{ex.Message}")
                tcpConnect = False
            End Try
        End If

        UpdateTcpTip(tcpConnect) '更新连接提示
        UpdateConnectionEnabled(tcpConnect) '根据连接,设置控件可操作性
    End Sub


    ''' <summary>
    ''' 更新网络的提示状态
    ''' </summary>
    ''' <param name="connected">是否连接成功</param>
    Private Sub UpdateTcpTip(connected As Boolean)
        If connected Then
            TssLblConnState.Text = $"已建立TCP连接！"
            TssLblConnState.ForeColor = Color.Green

            TsBtnConnService.Text = $"断连服务"
            TsBtnConnService.ForeColor = Color.Red
        Else
            TssLblConnState.Text = $"无TCP连接！"
            TssLblConnState.ForeColor = Color.Red

            TsBtnConnService.Text = $"连接服务"
            TsBtnConnService.ForeColor = Color.Green
        End If

    End Sub


    Private Sub UpdateConnectionEnabled(connected As Boolean)
        TsBtDelTasks.Enabled = connected
        TsBtnAddTasks.Enabled = connected
        TsBtnStartTasks.Enabled = connected
        TsBtnStopTasks.Enabled = connected
        TsBtnRestartTasks.Enabled = connected
        TsBtnGetTask.Enabled = connected
        TsBtnSetTasks.Enabled = connected
    End Sub

#End Region


#Region "任务命令"
    ''' <summary> 公共用户 </summary>
    Private _user As String = "Root"

    Private _tasks As New TaskForms

    ''' <summary>
    ''' 校验回复字符串
    ''' </summary>
    ''' <param name="replyString"></param>
    ''' <param name="cmdName"></param>
    ''' <returns></returns>
    Private Function CheckReplyString(replyString As String, cmdName As TaskJsonParam.CmdNamesEnum) As TaskJsonParam
        If String.IsNullOrWhiteSpace(replyString) Then Return Nothing

        Dim replyParam As TaskJsonParam
        replyParam = TaskJsonParam.DeserializeFormJson(replyString)

        If replyParam.CmdName <> cmdName Then Return Nothing

        Return replyParam
    End Function


    ''' <summary>
    ''' 添加任务
    ''' </summary>
    Private Sub AddTasks()
        _addFrom = New FrmAddTask
        If _addFrom.ShowDialog <> DialogResult.OK Then Return

        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.AddTasks, _user, Application.ProductName)
        taskParam.TasksInfo.Add(_addFrom.TaskForm.GetParams())
        ServiceCommunicator(taskParam)

        _addFrom.Dispose()
    End Sub


    Private Sub AddTaskGrid(taskStatus As String, taskType As String, taskName As String)
        Grid1.AddItem("")
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Act).Text = CStr(IIf(taskStatus = "Start", "1", "0"))
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Type).Text = taskType
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Name).Text = taskName
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Sn).SetFocus()
    End Sub

    Private Sub ChangeTaskGrid(taskStatus As String, taskType As String, taskName As String)
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Act).Text = CStr(IIf(taskStatus = "Start", "1", "0"))
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Type).Text = taskType
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Name).Text = taskName
        Grid1.Cell(Grid1.Rows - 1, ColNameEnum.Sn).SetFocus()
    End Sub


    Private Sub AddTaskForm(taskForm As ITaskForm)
        Dim tp As New TabPage
        taskForm.ShowForm(tp)
        TabTasks.TabPages.Add(tp)
    End Sub

    Private Sub RemoveTaskGrid(index As Integer)
        Grid1.Row(index + 1).Delete()
    End Sub

    Private Sub RemoveAtTaskForm(index As Integer)
        TabTasks.TabPages.RemoveAt(index)
    End Sub

    Private Sub StartTaskForm(index As Integer)
        Grid1.Cell(index + 1, ColNameEnum.Act).Text = "1"
    End Sub

    Private Sub StopTaskForm(index As Integer)
        Grid1.Cell(index + 1, ColNameEnum.Act).Text = "0"
    End Sub


    ''' <summary>
    ''' 删除任务
    ''' </summary>
    Private Sub DeleteTasks()
        If MsgBox("是否删除当前任务？", MsgBoxStyle.OkCancel) <> MsgBoxResult.Ok Then Return

        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.DeleteTasks, _user, Application.ProductName)
        taskParam.TasksName.Add(Grid1.Cell(TabTasks.SelectedIndex + 1, ColNameEnum.Name).Text)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 开启任务
    ''' </summary>
    Private Sub StartTasks()
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.StartTasks, _user, Application.ProductName)
        taskParam.TasksName.Add(Grid1.Cell(TabTasks.SelectedIndex + 1, ColNameEnum.Name).Text)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 暂停任务
    ''' </summary>
    Private Sub StopTasks()
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.StopTasks, _user, Application.ProductName)
        taskParam.TasksName.Add(Grid1.Cell(TabTasks.SelectedIndex + 1, ColNameEnum.Name).Text)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 获取任务参数
    ''' </summary>
    Private Sub GetTasksParam()
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.GetTasks, _user, Application.ProductName)
        taskParam.TasksName.Add(Grid1.Cell(TabTasks.SelectedIndex + 1, ColNameEnum.Name).Text)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 设置任务参数
    ''' </summary>
    Private Sub SetTasksParam()
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.SetTasks, _user, Application.ProductName)
        taskParam.TasksName.Add(Grid1.Cell(TabTasks.SelectedIndex + 1, ColNameEnum.Name).Text)
        taskParam.TasksInfo.Add(_tasks.GetParams(TabTasks.SelectedIndex))
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 重启任务，立即执行
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnRestartTasks_Click(sender As Object, e As EventArgs) Handles TsBtnRestartTasks.Click
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.RestartTasks, _user, Application.ProductName)
        taskParam.TasksName.Add(Grid1.Cell(TabTasks.SelectedIndex + 1, ColNameEnum.Name).Text)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 工具栏添加任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnAddTasks_Click(sender As Object, e As EventArgs) Handles TsBtnAddTasks.Click, CmsBtnAddTasks.Click
        AddTasks()
    End Sub


    ''' <summary>
    ''' 工具栏删除任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtDelTasks_Click(sender As Object, e As EventArgs) Handles TsBtDelTasks.Click, CmsBtnDeleteTasks.Click
        DeleteTasks()
    End Sub


    ''' <summary>
    ''' 工具栏开启任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnStartTasks_Click(sender As Object, e As EventArgs) Handles TsBtnStartTasks.Click, CmsBtnStartTasks.Click
        StartTasks()
    End Sub

    ''' <summary>
    ''' 工具栏暂停任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnStopTasks_Click(sender As Object, e As EventArgs) Handles TsBtnStopTasks.Click, CmsBtnStopTasks.Click
        StopTasks()
    End Sub

    ''' <summary>
    ''' 工具栏获取任务参数
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnGetTask_Click(sender As Object, e As EventArgs) Handles TsBtnGetTask.Click, CmsBtnGetTasks.Click
        GetTasksParam()
    End Sub

    ''' <summary>
    ''' 工具栏设置任务参数
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsBtnSetTasks_Click(sender As Object, e As EventArgs) Handles TsBtnSetTasks.Click, CmsBtnSetTasks.Click
        SetTasksParam()
    End Sub


    ''' <summary>
    ''' 右键菜单全部开启任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub CmsBtnStartAllTasks_Click(sender As Object, e As EventArgs) Handles CmsBtnStartAllTasks.Click
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.StartAllTasks, _user, Application.ProductName)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 右键菜单全部暂停任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub CmsBtnStopAllTasks_Click(sender As Object, e As EventArgs) Handles CmsBtnStopAllTasks.Click
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.StopAllTasks, _user, Application.ProductName)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 右键菜单全部删除任务
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub CmsBtnDeleteAllTasks_Click(sender As Object, e As EventArgs) Handles CmsBtnDeleteAllTasks.Click
        If MsgBox("是否删除所有任务？", MsgBoxStyle.OkCancel) <> MsgBoxResult.Ok Then Return
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.DeleteAllTasks, _user, Application.ProductName)
        ServiceCommunicator(taskParam)
    End Sub


    ''' <summary>
    ''' 右键菜单获取全部任务参数
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub CmsBtnGetAllTasks_Click(sender As Object, e As EventArgs) Handles CmsBtnGetAllTasks.Click, CmsBtnRefreshList.Click
        Dim taskParam As New TaskJsonParam(TaskJsonParam.CmdNamesEnum.GetAllTasks, _user, Application.ProductName)
        ServiceCommunicator(taskParam)
    End Sub

    ''' <summary>
    ''' 与服务通讯,包含发送，接收，处理过程
    '''→◆Recv:     '接收
    '''←◇Send:     '发送
    ''' </summary>
    ''' <param name="taskParam"></param>
    Private Sub ServiceCommunicator(taskParam As TaskJsonParam)
        Dim aTime As String = Date.Now.ToString("yyyy-MM-dd HH:mm:ss:fff ")
        Try
            Dim jsonString As String = TaskJsonParam.SerializeToJson(taskParam) & vbCrLf
            _tcpClient.WriteJsonString(jsonString)  '发送数据

            AppendTextTip($"←◇Send[{aTime}]{vbLf}", Color.Gray)
            AppendTextTip($"{jsonString}{vbCrLf}", Color.Blue)
        Catch ex As Exception
            MsgBox($"SendJsonString Error:{ex.Message}")
            Return
        End Try

        Dim replyString As String = _tcpClient.ReadJsonString()

        Try
            Dim replyParam As TaskJsonParam = CheckReplyString(replyString, taskParam.CmdName)  '接收数据校验
            AppendTextTip($"→◆Recv[{aTime}]{vbLf}", Color.Gray)
            AppendTextTip($"{replyString}{vbCrLf}", Color.Green)

            If replyParam.CmdStatus = TaskJsonParam.CmdStatusEnum.Pass.ToString() Then
                DealFunction(replyParam)
                TssLblExcuteTip.Text = $"Cmd:{replyParam.CmdName},Excute Pass!"
                TssLblExcuteTip.ForeColor = Color.Green
            Else
                TssLblExcuteTip.Text = $"Cmd:{replyParam.CmdName} {replyParam.CmdStatus},Msg:{replyParam.CmdMsg}"
                TssLblExcuteTip.ForeColor = Color.Red
            End If
        Catch ex As Exception
            TssLblExcuteTip.Text = $"Cmd:{taskParam.CmdName} Deal ReplyString Error:{ex.Message}"
            TssLblExcuteTip.ForeColor = Color.Blue
            Return
        End Try
    End Sub



    Private Sub DealFunction(replyParam As TaskJsonParam)
        Select Case replyParam.CmdName
            Case TaskJsonParam.CmdNamesEnum.AddTasks
                DealAddTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.DeleteTasks
                DealDeleteTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.StartTasks, TaskJsonParam.CmdNamesEnum.RestartTasks
                DealStartTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.StopTasks
                DealStopTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.GetTasks
                DealGetTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.SetTasks
                DealSetTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.StartAllTasks, TaskJsonParam.CmdNamesEnum.RestartAllTasks
                DealStartAllTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.StopAllTasks
                DealStopAllTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.DeleteAllTasks
                DealDeleteAllTasks(replyParam)
            Case TaskJsonParam.CmdNamesEnum.GetAllTasks
                DealGetAllTasks(replyParam)
        End Select
    End Sub


    Private Sub DealStartAllTasks(replyParam As TaskJsonParam)
        For i As Integer = 1 To Grid1.Rows - 1
            Grid1.Cell(i, ColNameEnum.Act).Text = "1"
        Next
    End Sub

    Private Sub DealStopAllTasks(replyParam As TaskJsonParam)
        For i As Integer = 1 To Grid1.Rows - 1
            Grid1.Cell(i, ColNameEnum.Act).Text = "0"
        Next
    End Sub

    Private Sub DealDeleteAllTasks(replyParam As TaskJsonParam)
        Grid1.Rows = 1
        TabTasks.TabPages.Clear()
        _tasks.Clear()
    End Sub


    Private Sub DealGetAllTasks(replyParam As TaskJsonParam)
        DealDeleteAllTasks(replyParam)

        For Each taskInfo As Dictionary(Of String, String) In replyParam.TasksInfo
            Dim taskType As ServiceTask.ServiceTaskTypeEnum = CType([Enum].Parse(GetType(ServiceTask.ServiceTaskTypeEnum), taskInfo("Type")), ServiceTask.ServiceTaskTypeEnum)
            Dim taskForm As ITaskForm
            Select Case taskType
                Case ServiceTask.ServiceTaskTypeEnum.DbSync
                    taskForm = New FrmSyncTasks()
                Case ServiceTask.ServiceTaskTypeEnum.ListenJsonFile
                    taskForm = New FrmListenTasks()
                Case Else
                    Throw New Exception($"Unknow TaskType:{taskType}")
            End Select

            _tasks.Add(taskForm)
            AddTaskForm(taskForm)
            AddTaskGrid(taskInfo("Status"), taskInfo("Type"), taskInfo("Name"))

            taskForm.SetParam(taskInfo)
        Next
    End Sub


    Private _addFrom As FrmAddTask
    Private Sub DealAddTasks(replyParam As TaskJsonParam)
        _tasks.Add(_addFrom.TaskForm)
        AddTaskForm(_addFrom.TaskForm)
        AddTaskGrid("0", _addFrom.TaskForm.GetParams("Type"), _addFrom.TaskForm.GetParams("Name"))
    End Sub

    Private Sub DealDeleteTasks(replyParam As TaskJsonParam)
        _tasks.RemoveAt(TabTasks.SelectedIndex)
        RemoveTaskGrid(TabTasks.SelectedIndex)
        RemoveAtTaskForm(TabTasks.SelectedIndex)
    End Sub

    Private Sub DealStartTasks(replyParam As TaskJsonParam)
        _tasks.SetStatus(TabTasks.SelectedIndex, ServiceTask.ServiceTaskStatusEnum.Start)
        StartTaskForm(TabTasks.SelectedIndex)
    End Sub

    Private Sub DealStopTasks(replyParam As TaskJsonParam)
        _tasks.SetStatus(TabTasks.SelectedIndex, ServiceTask.ServiceTaskStatusEnum.Stop)
        StopTaskForm(TabTasks.SelectedIndex)
    End Sub

    Private Sub DealGetTasks(replyParam As TaskJsonParam)
        For Each taskInfo As Dictionary(Of String, String) In replyParam.TasksInfo
            If taskInfo.ContainsKey("Name") Then
                If _tasks.GetParams(TabTasks.SelectedIndex).Item("Name") = taskInfo.Item("Name") Then
                    ChangeTaskGrid(taskInfo("Status"), taskInfo("Type"), taskInfo("Name"))
                    _tasks.SetParams(TabTasks.SelectedIndex, taskInfo)
                Else
                    Console.WriteLine($"Unsearch Name:{taskInfo.Item("Name")}")
                End If
            Else
                Console.WriteLine($"UnExitst Name Filed!")
            End If
        Next
    End Sub


    Private Sub DealSetTasks(replyParam As TaskJsonParam)


    End Sub

#End Region

#Region "添加通讯记录"
    Private _isShowLog As Boolean = True '是否显示通讯记录数据
    Private _isShowTip As Boolean = True '是否显示通讯记录提示
    Private _isClosing As Boolean = False '是否窗体处于关闭状态
    ''' <summary>
    ''' 添加记录并设置格式
    ''' </summary>
    ''' <param name="str">添加的记录内容</param>
    ''' <param name="cor">需要设置的记录颜色</param>
    Private Sub AppendTextTip(ByVal str As String, ByVal cor As Color)
        Dim selStart As Integer
        Dim selLength As Integer
        selStart = RtxCommunicationLogs.TextLength
        RtxCommunicationLogs.AppendText(str)
        RtxCommunicationLogs.ScrollToCaret()  '关键语句：将焦点滚动到文本内容后 
        selLength = RtxCommunicationLogs.TextLength - selStart
        RtxCommunicationLogs.Select(selStart, selLength)
        RtxCommunicationLogs.SelectionColor = cor
    End Sub

    Private Sub AppendTipText(recordString As String, col As Color)
        If _isClosing Then Return
        If _isShowTip = False Then Return
        If RtxCommunicationLogs.InvokeRequired Then
            RtxCommunicationLogs.Invoke(New Action(Sub()
                                                       If RtxCommunicationLogs.Lines.Count >= 256 Then RtxCommunicationLogs.Clear()
                                                       AppendTextTip($"{recordString}", col)
                                                       RtxCommunicationLogs.ScrollToCaret()
                                                   End Sub))
        Else
            If RtxCommunicationLogs.Lines.Count >= 256 Then RtxCommunicationLogs.Clear()
            AppendTextTip($"{recordString}", col)
            RtxCommunicationLogs.ScrollToCaret()
        End If
    End Sub

    ''' <summary>
    ''' 点击是否收起通讯日志
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsmPackUpRecord_Click(sender As Object, e As EventArgs) Handles TsmPackUpRecord.Click
        SplMain.Panel2Collapsed = Not SplMain.Panel2Collapsed
        If Not SplMain.Panel2Collapsed Then
            TsmPackUpRecord.Text = $"隐藏通讯日志"
        Else
            TsmPackUpRecord.Text = $"显示通讯日志"
        End If

    End Sub

    ''' <summary>
    ''' 点击清空通讯日志
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TsmClearRecord_Click(sender As Object, e As EventArgs) Handles TsmClearRecord.Click
        RtxCommunicationLogs.Clear()
    End Sub

#End Region


#Region "一键配置更新"

    Private Sub TsmConfigUpdate_Click(sender As Object, e As EventArgs) Handles TsmConfigUpdate.Click
        Dim root As String = $"software\AUTS"
        If UtsRegistry.RootDirExists = False Then
            Try
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey($"{root}\LocalDb")
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey($"{root}\AUTS_DataService")
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey($"{root}\AUTS_UpdateService")
            Catch ex As Exception
                Console.WriteLine($"创建注册表项失败! 失败原因：{ex.Message}")
            End Try
        End If

        '配置更新

        Dim result As DialogResult = FrmUpdateConfig.ShowDialog()
        InitSerName()
    End Sub

#End Region


#Region "关闭窗体"

    Private Sub FrmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing

    End Sub


    Private Sub 卸载服务ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 卸载服务ToolStripMenuItem.Click
        Dim filePath As String
        Using fileOpen As OpenFileDialog = New OpenFileDialog()
            fileOpen.Filter = $"服务执行程序(*.exe)|*.exe"
            If fileOpen.ShowDialog() <> DialogResult.OK Then
                Return
            End If
            filePath = fileOpen.FileName
        End Using

        If WinService.UnInstallService(filePath, Nothing) Then
            MsgBox($"路径：{filePath},卸载服务成功")
        Else
            MsgBox($"路径：{filePath},卸载服务失败！")
        End If
    End Sub

    Private Sub 输入路径卸载服务ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 输入路径卸载服务ToolStripMenuItem.Click
        Dim filePath As String = InputBox($"请输入服务执行文件路径", "卸载服务")
        If String.IsNullOrWhiteSpace(filePath) Then
            MsgBox($"路径：{filePath},是无效路径,请重新输入！")
            Return
        End If

        If WinService.UnInstallService(filePath, Nothing) Then
            MsgBox($"路径：{filePath},卸载服务成功")
        Else
            MsgBox($"路径：{filePath},卸载服务失败！")
        End If
    End Sub

#End Region



End Class