Imports System.Threading
Imports Newtonsoft.Json

Public Class Form1
    Public G_Dictionary As Dictionary(Of String, (Boolean, String, Integer, String, Color）)
    Public G_SerialPortli As Dictionary(Of String, CommuniNode)
    Public G_msgqueue As Queue(Of (String, Color, String))
    Public G_thread As Thread
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '设置页面标题为项目名称+版本号
        Me.Text = Application.ProductName & " " & Application.ProductVersion

        G_SerialPortli = New Dictionary(Of String, CommuniNode)()
        G_msgqueue = New Queue(Of (String, Color, String))
        loadSeting()
        Initgrid()
        G_thread = New Thread(AddressOf ThreadFun)
        G_thread.Start()
    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        saveSeting()
        If Not IsNothing(G_thread) AndAlso G_thread.IsAlive Then
            G_thread.Abort()
        End If
    End Sub

    '加载Seting
    Public Sub loadSeting()
        '刷新内存
        My.Settings.Reload()
        If String.IsNullOrEmpty(My.Settings.SerialPortSettings) Then
            G_Dictionary = New Dictionary(Of String, (Boolean, String, Integer, String, Color）)
        Else
            G_Dictionary = JsonConvert.DeserializeObject(Of Dictionary(Of String, (Boolean, String, Integer, String, Color）))(My.Settings.SerialPortSettings)
        End If

    End Sub
    Public Sub saveSeting()
        My.Settings.SerialPortSettings = JsonConvert.SerializeObject(G_Dictionary)
    End Sub
    Delegate Sub Deleg_ThreadFun(msg As (String, Color, String))

    Private Sub ThreadFun()
        Dim msg As (String, Color, String)
        While True
            If G_msgqueue.Count > 0 Then
                msg = G_msgqueue.Dequeue()
                AddMsgToGrid(msg)
            End If
            Thread.Sleep(10)
        End While
    End Sub

    Public Sub AddMsgToGrid(msg As (String, Color, String))
        Dim ts1, ts2, ts3 As String
        Dim t1, t2, t3 As DateTime
        Dim tc1, tc2 As Integer
        Dim buf() As String
        If Grid1.InvokeRequired Then
            Dim d As New Deleg_ThreadFun(AddressOf AddMsgToGrid)
            Grid1.Invoke(d, msg)
        Else
            '从表格末尾开始遍历但是不遍历第0行
            For i As Integer = Grid1.Rows - 1 To 1 Step -1
                If i = Grid1.Rows - 1 Then
                    ts2 = Grid1.Cell(i, 2).Text
                    't2 = DateTime.Parse(ts2)
                    DateTime.TryParseExact(ts2, "yyyy-MM-dd HH:mm:ss:fff",
                         System.Globalization.CultureInfo.InvariantCulture,
                         Globalization.DateTimeStyles.None, t2)
                End If
                If msg.Item1.Equals(Grid1.Cell(i, 5).Text) Then
                    ts1 = Grid1.Cell(i, 2).Text
                    't1 = DateTime.Parse(ts1)
                    DateTime.TryParseExact(ts1, "yyyy-MM-dd HH:mm:ss:fff",
                          System.Globalization.CultureInfo.InvariantCulture,
                          Globalization.DateTimeStyles.None, t1)
                    Exit For
                End If

            Next

            buf = msg.Item3.Split("_")
            ts3 = buf(0)
            DateTime.TryParseExact(ts3, "yyyy-MM-dd HH:mm:ss:fff",
                          System.Globalization.CultureInfo.InvariantCulture,
                          Globalization.DateTimeStyles.None, t3)
            If IsNothing(t1) Then
                tc1 = 0
            Else
                Try
                    tc1 = (t3 - t1).TotalMilliseconds
                Catch ex As Exception
                    tc1 = 65535
                End Try

            End If
            If IsNothing(t2) Then
                tc2 = 0
            Else
                Try
                    tc2 = (t3 - t2).TotalMilliseconds
                Catch ex As Exception
                    tc2 = 65535
                End Try

            End If

            Grid1.AddItem("")
            Grid1.Cell(Grid1.Rows - 1, 0).Text = Grid1.Rows - 1
            'Grid1.Cell(Grid1.Rows - 1, 1).Text = ts3

            Grid1.Cell(Grid1.Rows - 1, 2).Text = ts3
            Grid1.Cell(Grid1.Rows - 1, 3).Text = tc1
            Grid1.Cell(Grid1.Rows - 1, 4).Text = tc2
            Grid1.Cell(Grid1.Rows - 1, 5).Text = msg.Item1
            Grid1.Cell(Grid1.Rows - 1, 6).Text = msg.Item3.Replace(ts3 & "_", "").Length
            Grid1.Cell(Grid1.Rows - 1, 7).Text = msg.Item3.Replace(ts3 & "_", "")
            Grid1.Cell(Grid1.Rows - 1, 8).Text = publicMode.StringToHexString(msg.Item3.Replace(ts3 & "_", ""))



            Grid1.Range(Grid1.Rows - 1, 0, Grid1.Rows - 1, 8).WrapText = True
            Grid1.Range(Grid1.Rows - 1, 0, Grid1.Rows - 1, 8).ForeColor = msg.Item2
            Grid1.Cell(Grid1.Rows - 1, 0).SetFocus()

        End If

    End Sub


    Public Sub Initgrid()
        With Grid1
            .NewFile()
            .Cols = 9
            .Rows = 1
            .ExtendLastCol = True
            .DisplayRowNumber = True
            .Cell(0, 0).Text = "序号"
            .Cell(0, 1).Text = "选择"
            .Cell(0, 2).Text = "时间"
            .Cell(0, 3).Text = "同串口时间差"
            .Cell(0, 4).Text = "时间差"
            .Cell(0, 5).Text = "串口名称"
            .Cell(0, 6).Text = "包长"
            .Cell(0, 7).Text = "TEXT"
            .Cell(0, 8).Text = "HEX"
            .Column(0).Width = 50
            .Column(1).Width = 20
            .Column(1).CellType = FlexCell.CellTypeEnum.CheckBox
            .Column(2).Width = 150
            .Column(3).Width = 50
            .Column(4).Width = 50
            .Column(5).Width = 100
            .Column(6).Width = 50
            .Column(7).Width = 300
            .Column(8).Width = 300

            .Column(6).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(2).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(3).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(4).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(5).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(6).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(7).Alignment = FlexCell.AlignmentEnum.CenterCenter
            .Column(8).Alignment = FlexCell.AlignmentEnum.CenterCenter


            .HighLightMode = FlexCell.HighLightModeEnum.Both

        End With



    End Sub



    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        '创建设串口页面
        Dim form2 As New SetingSerialPort
        form2.G_Dictionary = G_Dictionary
        form2.ShowDialog()
        '判断是否确定关闭
        If form2.DialogResult = DialogResult.OK Then
            G_Dictionary = form2.G_Dictionary
        End If
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        If ToolStripButton1.Text.Equals("打开") Then
            ToolStripButton1.Text = "关闭"
            ToolStripButton2.Enabled = False
            Dim nCommuniNode As CommuniNode
            '遍历G_Dictionary
            For Each item In G_Dictionary
                If item.Value.Item1 Then

                    nCommuniNode = New CommuniNode(item.Value.Item2, item.Value.Item3, item.Value.Item4, item.Value.Item5, G_msgqueue)
                    G_SerialPortli.Add(item.Value.Item4, nCommuniNode)
                    nCommuniNode.SetSerialPortOpen(True)


                End If
            Next
            Button2.Text = "停止接收"
            Button2.BackColor = Color.Red
            SetReadFlag(True)

        Else
            ToolStripButton1.Text = "打开"
            ToolStripButton2.Enabled = True
            For Each item In G_SerialPortli
                item.Value.SetSerialPortOpen(False)
            Next

            Button2.Text = "开始接收"
            Button2.BackColor = Color.Green
            SetReadFlag(False)

            G_SerialPortli.Clear()
            ComboBox1.Items.Clear()
            ComboBox1.Text = ""
        End If




    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If IsNothing(G_SerialPortli) OrElse G_SerialPortli.Count = 0 Then Return
        For Each item In G_SerialPortli
            item.Value.SetShowHex(CheckBox1.Checked)
        Next
    End Sub

    Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged
        If IsNothing(G_SerialPortli) OrElse G_SerialPortli.Count = 0 Then Return
        For Each item In G_SerialPortli
            item.Value.SetSendHex(CheckBox2.Checked)
        Next
    End Sub

    Private Sub ComboBox1_DropDown(sender As Object, e As EventArgs) Handles ComboBox1.DropDown
        ComboBox1.Items.Clear()
        If IsNothing(G_SerialPortli) OrElse G_SerialPortli.Count = 0 Then Return
        For Each item In G_SerialPortli

            ComboBox1.Items.Add(item.Value.G_aliasname)
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If IsNothing(G_SerialPortli) OrElse G_SerialPortli.Count = 0 Then Return
        For Each item In G_SerialPortli
            If ComboBox1.Text.Equals(item.Value.G_aliasname) Then
                item.Value.SendData(TextBox1.Text.Trim)
                Return
            End If

        Next
    End Sub


    Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
        Grid1.Rows = 1
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If Button2.Text.Equals("停止接收") Then
            Button2.Text = "开始接收"
            Button2.BackColor = Color.Green
            SetReadFlag(False)
        Else
            Button2.Text = "停止接收"
            Button2.BackColor = Color.Red
            SetReadFlag(True)
        End If

    End Sub

    Public Sub SetReadFlag(ByVal flag As Boolean)
        If IsNothing(G_SerialPortli) OrElse G_SerialPortli.Count = 0 Then Return
        For Each item In G_SerialPortli
            item.Value.SetReadFlag(flag)
        Next
    End Sub

    Private Sub CheckBox3_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox3.CheckedChanged, CheckBox9.CheckedChanged, CheckBox8.CheckedChanged, CheckBox7.CheckedChanged, CheckBox6.CheckedChanged, CheckBox5.CheckedChanged, CheckBox4.CheckedChanged
        Dim chBox As CheckBox = sender
        '判断是否选中
        '取到tag
        Dim tag As Integer = CInt（chBox.Tag)
        If chBox.Checked Then
            Grid1.Column(tag).Visible = False
        Else

            Grid1.Column(tag).Visible = True
        End If
    End Sub

    Private Sub Grid1_Click(Sender As Object, e As EventArgs) Handles Grid1.Click
        '获取选中单元格
        Dim C_x, C_y As Integer
        C_x = Grid1.ActiveCell.Row
        C_y = Grid1.ActiveCell.Col
        '判断行》0
        If C_x > 0 Then
            '获取行号设置到Xlabel
            Xlabel.Text = "RowID:" & Grid1.Cell(C_x, 0).Text
            Ylabel.Text = "ColumnName:" & Grid1.Cell(0, C_y).Text
            TextBox2.Text = Grid1.Cell(C_x, C_y).Text
        End If
    End Sub
End Class
