Imports System.Data.Common
Imports System.IO.Ports
Imports Steema.TeeChart

Public Class Form1


    '定义队列变量
    Public Queue As New Queue(Of String)
    Public oldtime As Date = Now
    Public Starttime As Date = Now
    Public lincolorArry = {Color.Red, Color.Blue, Color.Green,
        Color.Black, Color.Orange, Color.BlueViolet,
         Color.Coral, Color.Navy, Color.Chocolate,
        Color.Blue, Color.DarkOrange, Color.DarkMagenta,
        Color.Purple, Color.MediumPurple, Color.DeepPink,
        Color.DarkGoldenrod, Color.HotPink, Color.CadetBlue}
    Private Sub SerialPort1_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        '获取串口数据并加入队列
        Dim data As String
        Starttime = Now.AddMilliseconds(100)
        'Try
        data = SerialPort1.ReadLine()
        'Console.WriteLine($"DataReceived cntime:{(Starttime - oldtime).TotalMilliseconds}|  Now:{Starttime.ToString("yyyy-MM-dd HH:mm:ss")}| oldtime：{oldtime.ToString("yyyy-MM-dd HH:mm:ss") }{vbLf} Data:{data}   ")
        oldtime = Now
        'Console.Clear()
        '往文件写入信息如果文件不存在则创建文件 
        'IO.File.AppendAllLines(Application.StartupPath & "\log.txt", {$"Queue:{Queue.Count} Ctime:{(Now - oldtime).TotalMilliseconds}  PP:  { Now.ToString("yyyy-MM-dd HH:mm:ss")} Data:{data}"})


        '清空读缓存区
        'SerialPort1.DiscardInBuffer()
        'Catch ex As Exception
        '    MsgBox(ex.Message)
        'End Try

        'Console.WriteLine(data)

        '判断是否开启采集
        If IsStart Then
            If data.Split(",").Length = 19 Then
                ' Console.WriteLine($"Queue:{Queue.Count} Ctime:{(Now - oldtime).TotalMilliseconds}  PP:  { Now.ToString("yyyy-MM-dd HH:mm:ss")} Data:{data}")
                Queue.Enqueue($"{ Starttime.ToString("yyyy-MM-dd HH:mm:ss")},{data}")

                'Dim selectstr As String = String.Empty
                'Dim Insert As String
                'Dim buf = data.Split(",")
                'Insert = $"INSERT INTO [Logdata]
                '                  ([SN] ,                                                                     
                '                      [Datatime] ,
                '                         [V1] ,
                '                         [T1] ,
                '                         [C1] ,
                '                         [V2] ,
                '                         [T2] ,
                '                         [C2] ,
                '                         [V3] ,
                '                         [T3] ,
                '                         [C3] ,
                '                         [V4] ,
                '                         [T4] ,
                '                         [C4] ,
                '                         [V5] ,
                '                         [T5] ,
                '                         [C5] ,
                '                         [V6] ,
                '                         [T6] ,
                '                         [C6] )
                '                 VALUES
                '                 ('{buf(0)}',
                '                        '{Now.ToString("yyyy-MM-dd HH:mm:ss")}',
                '                        '{buf(1)}',
                '                        '{buf(2)}',
                '                        '{buf(3)}',
                '                        '{buf(4)}',
                '                  '{buf(5)}',
                '                  '{buf(6)}',
                '                  '{buf(7)}',
                '                  '{buf(8)}',
                '                  '{buf(9)}',
                '                  '{buf(10)}',
                '                  '{buf(11)}',
                '                  '{buf(12)}',
                '                  '{buf(13)}',
                '                  '{buf(14)}',
                '                  '{buf(15)}',
                '                  '{buf(16)}',
                '                        '{buf(17)}',
                '                        '{buf(18)}'
                '                        );{vbCrLf }"
                'selectstr = $"{selectstr}{Insert}"
                'InsertData(selectstr)

            Else
                Console.WriteLine($"Error   Queue:{Queue.Count} Ctime:{(Now - oldtime).TotalMilliseconds}  PP:  { Now.ToString("yyyy-MM-dd HH:mm:ss")} Data:{data}")
                oldtime = Now
            End If

        End If

    End Sub

    Private Sub SerialPortlist_DropDown(sender As Object, e As EventArgs) Handles SerialPortlist.DropDown
        '获取串口列表
        SerialPortlist.Items.Clear()
        For Each sp As String In My.Computer.Ports.SerialPortNames
            SerialPortlist.Items.Add(sp)
        Next
    End Sub

    Private Sub ToolStripComboBox2_DropDown(sender As Object, e As EventArgs) Handles ToolStripComboBox2.DropDown
        '获取波特率列表

        Dim baudRates() As String = {9600, 14400, 19200, 38400, 57600, 115200, 512000}

        ToolStripComboBox2.Items.Clear()
        'For Each sp As String In My.Computer.Ports.SerialPortNames
        ToolStripComboBox2.Items.AddRange(baudRates)
        'Next
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        ''当串口处于打开时 ， 按钮显示为“关闭串口”， 否则显示为“打开串口”并且设置对应背景色。且相关下拉框禁用
        If String.IsNullOrEmpty(SerialPortlist.Text) OrElse String.IsNullOrEmpty(ToolStripComboBox2.Text) Then Return
        If SerialPort1.IsOpen Then
            SerialPort1.Close()
            ToolStripButton1.Text = "打开串口"
            ToolStripButton1.BackColor = Color.Green
            SerialPortlist.Enabled = True
            ToolStripComboBox2.Enabled = True
        Else
            SerialPort1.PortName = SerialPortlist.Text
            SerialPort1.BaudRate = ToolStripComboBox2.Text
            SerialPort1.DataBits = 8
            SerialPort1.StopBits = StopBits.One
            SerialPort1.Handshake = Handshake.None
            Try
                SerialPort1.Open()
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                Return
            End Try

            ToolStripButton1.Text = "关闭串口"
            ToolStripButton1.BackColor = Color.Red
            SerialPortlist.Enabled = False
            ToolStripComboBox2.Enabled = False

        End If



    End Sub
    '定义采集数据开关变量
    Public IsStart As Boolean = False
    '定义采集数据线程
    Public RuningThred As Threading.Thread

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        '判读采集数据开关变量，如果为True，则关闭采集，否则开启采集
        If IsStart Then
            IsStart = False
            ToolStripButton2.Text = "开始采集"
            ToolStripButton2.BackColor = Color.Green
            Timer1.Stop()
        Else
            IsStart = True
            ToolStripButton2.Text = "停止采集"
            ToolStripButton2.BackColor = Color.Red
            '记录开始采集的时间
            LabelstartTime.Text = "Start Time:" + Now.ToString("yyyy-MM-dd HH:mm:ss")
            '判断线程是否实例化
            'If RuningThred Is Nothing Then
            '    '实例化线程
            '    RuningThred = New Threading.Thread(AddressOf RuningThreadFunction)
            'End If
            '开始运行采集线程
            Queue.Clear()
            CorrectionTime = Now
            ChartBar.Axes.Bottom.Minimum = Date.Parse(Now.ToString("yyyy-MM-dd HH:mm:ss")).ToOADate
            ' ChartBar.Axes.Bottom.MinXValue = Now.ToOADate
            Timer1.Start()

        End If
    End Sub

    Public Sub RuningThreadFunction()
        While True
            If IsStart Then
                '判断队列是否有数据
                If Queue.Count > 0 Then

                End If
            End If
        End While
    End Sub

    Public lineSetDic As New Dictionary(Of String, (Boolean, Dictionary(Of String, Steema.TeeChart.Styles.Bezier)))

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Queue = New Queue(Of String)
        Queue.Clear()
        '初始化Gridinfo
        Gridinfo_Init()
        GridMessageInit()
        InitLineSet()
        GridMessagedicInit()
        ' InitCursor()
        ClearDeviceform()
    End Sub
    '初始化信息组

    Private Sub GridMessagedicInit()
        lineSetDic = New Dictionary(Of String, (Boolean, Dictionary(Of String, Steema.TeeChart.Styles.Bezier)))
        Dim timedata As Dictionary(Of String, Steema.TeeChart.Styles.Bezier)
        Dim indexline As Steema.TeeChart.Styles.Bezier
        Dim red As Integer
        Dim green As Integer
        Dim blue As Integer
        Dim MyRnd As New Random
        For i As Integer = 1 To 6

            timedata = New Dictionary(Of String, Steema.TeeChart.Styles.Bezier)
            For j As Integer = 0 To 2
                indexline = New Steema.TeeChart.Styles.Bezier(ChartBar.Chart)
                red = MyRnd.Next(i * j * 10, 255)
                green = MyRnd.Next(100, 255)
                blue = MyRnd.Next(100, 255)
                Select Case j
                    Case 0

                        timedata.Add($"V{i}", indexline)
                        indexline.LinePen.Color = lincolorArry(i * 3 - 3) ' Color.FromArgb(red, green, blue)
                        ' indexline.Colors.Item(0) = lincolorArry(i * 3 - 3)
                        ' Console.WriteLine($"V{i} c1:{indexline.Color} c2:{lincolorArry(i * 3 - 3)}")
                        indexline.LinePen.Width = 1
                        indexline.Title = $"V{i}"
                        indexline.Visible = False
                        indexline.Marks.Visible = False
                        indexline.XValues.DateTime = True
                        indexline.XValues.Modified = False
                        indexline.Pointer.Visible = False
                        'indexline.Pointer.Style = Steema.TeeChart.Styles.PointerStyles.Circle
                        ' indexline.FillSampleValues(200)
                        'indexline.border.Visible = False
                        'indexline.Smoothed = True

                    Case 1

                        timedata.Add($"C{i}", indexline)
                        indexline.LinePen.Color = lincolorArry(i * 3 - 2) 'Color.FromArgb(red, green, blue)
                        'indexline.Colors.Item(0) = lincolorArry(i * 3 - 2)
                        indexline.LinePen.Width = 1
                        indexline.Title = $"C{i}"
                        indexline.Visible = False
                        indexline.Marks.Visible = False
                        indexline.XValues.DateTime = True
                        indexline.XValues.Modified = False
                        indexline.Pointer.Visible = False

                        'indexline.Pointer.Style = Steema.TeeChart.Styles.PointerStyles.Circle
                        ' indexline.FillSampleValues(200)

                        'indexline.Smoothed = True
                        'indexline.XValues.DateTime = True
                    Case 2

                        timedata.Add($"T{i}", indexline)
                        indexline.LinePen.Color = lincolorArry(i * 3 - 1) 'Color.FromArgb(red, green, blue)
                        ' indexline.Colors.Item(0) = lincolorArry(i * 3 - 1)
                        indexline.LinePen.Width = 1
                        indexline.Title = $"T{i}"
                        indexline.Visible = False
                        indexline.Marks.Visible = False
                        indexline.XValues.DateTime = True
                        indexline.XValues.Modified = False
                        indexline.Pointer.Visible = False
                        'indexline.Pointer.Style = Steema.TeeChart.Styles.PointerStyles.Circle
                        'indexline.FillSampleValues(200)


                        'indexline.Smoothed = True
                        'indexline.XValues.DateTime = True
                End Select
            Next
            lineSetDic.Add("CH" + i.ToString(), (False, timedata))
        Next
        ' Testadd()
    End Sub

    Public Sub Testadd()
        '' Dim timedata As Dictionary(Of String, Steema.TeeChart.Styles.Line)
        Dim MyRnd As New Random
        For Each item In lineSetDic
            For Each inem1 In item.Value.Item2.Values
                'Console.WriteLine(inem1.Title)
                For i As Integer = 0 To 100
                    inem1.Add(Now.AddMilliseconds(-Now.Millisecond).AddSeconds(MyRnd.Next(0, 100)).ToOADate, MyRnd.Next(0, 100))
                Next
            Next
        Next

    End Sub

    Private Sub tcChart_ChartMouseWheel(sender As Object, e As MouseEventArgs)
        ' 在这里添加你的逻辑
        ' 例如，根据e.Delta判断滚轮滚动方向
        'Dim tx， ty As Integer
        'If IsNothing(_fastLine) OrElse _fastLine.Count = 0 Then Return
        'Dim fl = _fastLine.Values(0)
        If e.Delta > 0 Then
            'MessageBox.Show("鼠标向上滚动")
            'tx = ChartBar.Zoom.
            '    ty =
            ' ChartBar.Zoom.ZoomRect(New Rectangle(0, 50, ChartBar.Width, 100))


            '  If ChartBar.Zoom.HistorySteps.Count > 0 Then
            'ChartBar.Zoom.Undo()

            'Else
            ChartBar.Zoom.ZoomRect(New Rectangle(0, 0, ChartBar.Width, ChartBar.Height))
            '    Console.WriteLine($"鼠标向上滚动{ChartBar.Width},{ChartBar.Height}")
            ''   End If
            'Dim rectc = ChartBar.RectangleToClient(New Rectangle(0, 0, ChartBar.Width, ChartBar.Height))
            'Console.WriteLine(fl.Chart.ChartRect.X)
        Else
            'MessageBox.Show("鼠标向下滚动")
            ChartBar.Zoom.Undo()
            ' fl = _fastLine.Item(node.Key)
            'If ChartBar.Zoom.HistorySteps.Count > 0 Then
            '    ChartBar.Zoom.Undo()
            '    Console.WriteLine($"鼠标向上滚动_Undo")
            'Else
            '    ChartBar.Zoom.ZoomRect(New Rectangle((ChartBar.Width / 2) - 300, 0, (ChartBar.Width / 2) + 100, ChartBar.Height))
            '    Console.WriteLine($"鼠标向上滚动{(ChartBar.Width / 2) - 100},{(ChartBar.Width / 2) + 200}")
            'End If


            'ChartBar.Zoom.ZoomRect(New Rectangle(100, 100, 120, 120))
        End If

        'Dim X As Integer = Points1.CalcXPos(2)
        'Dim Y As Integer = TChart1.Axes.Left.CalcYPosValue(TChart1.Axes.Left.MaxYValue)
        'Dim Height As Integer = TChart1.Axes.Left.CalcYPosValue(TChart1.Axes.Left.MinYValue) - TChart1.Axes.Left.CalcYPosValue(TChart1.Axes.Left.MaxYValue)
        'Dim Width As Integer = Points1.CalcXPos(5) - X
        'Dim R As New Rectangle(X, Y, Width, Height)
        'TChart1.Zoom.ZoomRect(R)


    End Sub
    '初始化线表



    Private Sub InitLineSet()
        '' ChartBar.Zoom.ZoomPercent(100)
        ''ChartBar.AutoRepaint = False
        ChartBar.Series.Clear()
        RemoveHandler ChartBar.MouseWheel, AddressOf tcChart_ChartMouseWheel
        AddHandler ChartBar.MouseWheel, AddressOf tcChart_ChartMouseWheel
        ChartBar.Header.Lines = New String() {""} 'TeeChart标题

        ChartBar.Zoom.Animated = True
        ChartBar.Zoom.AnimatedSteps = 1
        ChartBar.Zoom.Direction = ZoomDirections.Horizontal
        ChartBar.Panning.Allow = ScrollModes.Horizontal
        ChartBar.Panning.InsideBounds = False

        'ChartBar.Axes.Bottom.Title.Caption = "时间轴"
        ChartBar.Axes.Bottom.Title.Visible = False
        ChartBar.Axes.Bottom.MaximumOffset = 4 '最大值偏移
        ChartBar.Axes.Bottom.MinimumOffset = 4 '最小值偏移
        ChartBar.Axes.Bottom.Grid.Style = System.Drawing.Drawing2D.DashStyle.Dash
        ChartBar.Axes.Bottom.Grid.Width = 2
        ChartBar.Axes.Bottom.Ticks.Color = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer))
        ChartBar.Axes.Bottom.Ticks.Length = 2 '标记长度
        ChartBar.Axes.Bottom.Ticks.Width = 2 '标记宽度
        ChartBar.Axes.Bottom.Grid.Transparency = 60
        ChartBar.Axes.Bottom.Automatic = False
        ChartBar.Axes.Bottom.Logarithmic = False
        ChartBar.Axes.Bottom.Labels.MultiLine = True
        'ChartBar.Axes.Bottom.Increment = TimeSpan.FromSeconds(1).TotalDays
        'ChartBar.Axes.Bottom.Labels.DateTimeFormat = " HH:mm:ss" ' // 设置时间格式
        'ChartBar.Axes.Bottom.DateTime = True
        'ChartBar.Axes.Bottom.RelativePosition = 50
        'ChartBar.Axes.Bottom.Increment = yt.ToOADate
        ChartBar.Axes.Bottom.AutomaticMaximum = False
        ' ChartBar.Axes.Bottom.Increment = 1
        ChartBar.Axes.Bottom.AutomaticMinimum = False
        'ChartBar.Axes.Bottom.Automatic = False
        'Dim yt As Date = Now
        'ChartBar.Axes.Bottom.Maximum = yt.ToOADate
        ChartBar.Axes.Bottom.Scroll(3, False)

        ChartBar.Axes.Bottom.Labels.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
        'ChartBar.Axes.Bottom.Labels.ValueFormat = "#.0000000"
        ChartBar.CurrentTheme = ThemeType.Opera
        'ChartBar.Axes.Bottom.Scroll(3, False)
        ChartBar.Axes.Bottom.IncrementOffset = 1
        ChartBar.Axes.Bottom.ZoomLimitToAxisBounds = True
        'ChartBar.Axes.Bottom.Logarithmic = True
        'ChartBar.Axes.Bottom.LogarithmicBase = 30
        'ChartBar.Axes.Bottom.Maximum = 11255
        'ChartBar.Axes.Bottom.Minimum = 0


        'ChartBar.Axes.Left.Title.Caption = "电流-电压轴"
        ChartBar.Axes.Left.Title.Visible = False
        ChartBar.Axes.Left.MaximumOffset = 1 '最大值偏移
        ChartBar.Axes.Left.MinimumOffset = 1 '最小值偏移
        ChartBar.Axes.Left.Grid.Style = System.Drawing.Drawing2D.DashStyle.Dash
        ChartBar.Axes.Left.Grid.Width = 2
        ChartBar.Axes.Left.Ticks.Color = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer))
        ChartBar.Axes.Left.Ticks.Length = 2 '标记长度
        ChartBar.Axes.Left.Ticks.Width = 2 '标记宽度
        ChartBar.Axes.Left.Grid.Transparency = 60
        ChartBar.Axes.Left.Automatic = False
        ChartBar.Axes.Left.Minimum = 0.000
        ChartBar.Axes.Left.Maximum = 10
        ChartBar.Axes.Left.Logarithmic = False
        ChartBar.Axes.Left.AutomaticMaximum = True
        ChartBar.Axes.Left.AutomaticMinimum = False
        ChartBar.Axes.Left.ZoomLimitToAxisBounds = True
        'ChartBar.Axes.Left.Increment = 20
        ChartBar.Axes.Bottom.Labels.ValueFormat = "#.0000000"


        ChartBar.Axes.Left.ZoomLimitToAxisBounds = True
        ChartBar.Axes.Left.UsePartnerAxis = True
        ChartBar.Axes.Left.Increment = 1
        'ChartBar.Header.Font.Size = 10
        'ChartBar.Axes.Bottom.FixedLabelSize = False

        'ChartBar.Legend.LegendStyle = Steema.TeeChart.LegendStyles.Auto
        ChartBar.AutoRepaint = True
        ChartBar.Refresh()
    End Sub

    '初始化表格
    Private Sub Gridinfo_Init()
        Gridinfo.NewFile()
        Gridinfo.ExtendLastCol = True
        Gridinfo.Rows = 7
        Gridinfo.Cols = 9
        Gridinfo.Column(3).CellType = FlexCell.CellTypeEnum.CheckBox
        Gridinfo.Column(3).Width = 20
        Gridinfo.Column(0).Visible = False
        Gridinfo.Column(2).Locked = True

        Gridinfo.Column(4).Locked = True
        Gridinfo.Column(5).Locked = True
        Gridinfo.Column(6).Locked = True
        Gridinfo.Column(7).Locked = True
        Gridinfo.Column(8).Locked = True

        Gridinfo.Range(0, 0, Gridinfo.Rows - 1, Gridinfo.Cols - 1).FontBold = True
        Gridinfo.Range(1, 3, Gridinfo.Rows - 1, Gridinfo.Cols - 1).ForeColor = Color.LightGray
        For i As Integer = 0 To 8
            Gridinfo.Column(i).Alignment = FlexCell.AlignmentEnum.CenterCenter
        Next

        Gridinfo.Cell(0, 1).Text = "测试名称"
        Gridinfo.Cell(0, 2).Text = "CH"
        Gridinfo.Cell(0, 3).Text = "显示"
        Gridinfo.Cell(0, 4).Text = "时间"
        Gridinfo.Cell(0, 5).Text = "电压"
        Gridinfo.Cell(0, 6).Text = "容量"
        Gridinfo.Cell(0, 7).Text = "温度"
        Gridinfo.Cell(0, 8).Text = "累计时间"


        For i As Integer = 1 To 6
            Gridinfo.Cell(i, 2).Text = $"CH{i.ToString}"
            Gridinfo.Cell(i, 1).Text = $"CH{i.ToString}"
        Next

    End Sub
    Private _curTool As Steema.TeeChart.Tools.CursorTool
    Private Sub ChartBar_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles ChartBar.MouseDoubleClick
        If e.Button = MouseButtons.Middle Then
            ChartBar.Zoom.Undo()
        ElseIf e.Button = MouseButtons.Left Then
            Dim idx As Integer
            Dim row As Integer

            'If _curTool Is Nothing Then
            '    idx = 0
            '    _curTool = _curSor(idx)
            '    _curTool.FollowMouse = True
            '    'row = _rowChart.Cursor + idx * (EnCursor.Width + 2) + 1 + EnCursor.FollowMouse + 1
            '    'GrdChartInfo.Cell(row, EnGridCol.Value).Text = $"1"

            'Else
            '    If _curTool.FollowMouse = False Then
            '        idx = _curTool.Tag
            '        '  row = _rowChart.Cursor + idx * (EnCursor.Width + 2) + 1 + EnCursor.FollowMouse + 1
            '        '_isUserChange = False
            '        _curTool.FollowMouse = False
            '        'GrdChartInfo.Cell(row, EnGridCol.Value).Text = $"0"

            '        idx += 1
            '        If idx >= _curSor.Length Then
            '            idx = 0
            '            _curTool = _curSor(idx)
            '            _curTool.FollowMouse = True
            '        Else
            '            _curTool = _curSor(idx)
            '            _curTool.FollowMouse = True
            '            '  row = _rowChart.Cursor + idx * (EnCursor.Width + 2) + 1 + EnCursor.FollowMouse + 1
            '            'GrdChartInfo.Cell(row, EnGridCol.Value).Text = $"1"
            '        End If


            '        '_isUserChange = True
            '    End If

            'End If

        End If
    End Sub
    Private xlen As Boolean = False
    Private Sub ChartBar_MouseClick(sender As Object, e As MouseEventArgs) Handles ChartBar.MouseClick
        ' ZoomX1 = 0

        If e.Button = MouseButtons.Middle Then
            ChartBar.Zoom.Undo()
        ElseIf e.Button = MouseButtons.Right Then
            'Console.WriteLine(e.X)
            'ChartBar.Axes.Bottom.Maximum = e.X
            'ChartBar.Axes.Bottom.Maximum = e.X
            If IsNothing(_curTool) Then Return
            _curTool.FollowMouse = False
        ElseIf e.Button = MouseButtons.Left Then
            'xlen = True
            Dim values As Double = ChartBar.Axes.Bottom.CalcPosPoint(e.X)
            Dim values1 As Double = ChartBar.Axes.Left.CalcPosPoint(e.Y)
            'ZoomX1 = values
            'Dim cu = ChartBar.GetChildAtPoint(New Point(e.X, e.Y))
            'Console.WriteLine(cu)
            'MessageBox.Show("MouseDown X: " & values.ToString() & ", Y: " & values1.ToString())
            Console.WriteLine("MouseClick X: " & values.ToString() & ", Y: " & values1.ToString())
        End If

    End Sub
    Private _curSor(1) As Steema.TeeChart.Tools.CursorTool
    Private Sub InitCursor()
        ChartBar.Tools.Clear()
        For i = 0 To _curSor.Length - 1
            _curSor(i) = New Steema.TeeChart.Tools.CursorTool
            ChartBar.Tools.Add(_curSor(i))
            _curSor(i).Style = Steema.TeeChart.Tools.CursorToolStyles.Vertical
            _curSor(i).OriginalCursor = System.Windows.Forms.Cursors.Default
            _curSor(i).Pen.Style = System.Drawing.Drawing2D.DashStyle.Dot
            _curSor(i).Pen.Width = 2
            _curSor(i).Tag = i
            '_curSor(i).Series = _fastLine.Item("执行条件状态")
            _curSor(i).Active = True
            _curSor(i).FollowMouse = False
            '_curSor(i).Pen.Visible = False
            _curSor(i).Pen.Visible = True
            '_curSor(i).Chart.ShowCoord
            '_curSor(i).ValueFormat = "X: {X}, Y: {Y}"
            Dim cursorTool As New Steema.TeeChart.Tools.CursorTool()

            'AddHandler _curSor(i).Change, AddressOf CursorChange
            Select Case i
                Case 0
                    _curSor(i).Pen.Color = System.Drawing.Color.OrangeRed
                Case 1
                    _curSor(i).Pen.Color = System.Drawing.Color.Green
                Case 2
                    _curSor(i).Pen.Color = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer))
            End Select
        Next
    End Sub
    Private Sub GridMessageInit()
        GridMessage.NewFile()
        GridMessage.ExtendLastCol = True
        GridMessage.Rows = 1
        GridMessage.Cols = 6
        GridMessage.Column(0).Visible = False
        'GridMessage.DisplayRowNumber = True
        For i As Integer = 0 To 5
            Gridinfo.Column(i).Alignment = FlexCell.AlignmentEnum.CenterCenter
        Next
        GridMessage.Cell(0, 0).Text = "NO"
        GridMessage.Cell(0, 1).Text = "SN"
        GridMessage.Cell(0, 2).Text = "DateTime"
        GridMessage.Cell(0, 3).Text = "V"
        GridMessage.Cell(0, 4).Text = "C"
        GridMessage.Cell(0, 5).Text = "T"

    End Sub

    Private Sub Gridinfo_CellChange(Sender As Object, e As FlexCell.Grid.CellChangeEventArgs) Handles Gridinfo.CellChange
        If e.Row = 0 Then Return
        Select Case e.Col
            Case 3
                ShowOrHidecursor(Gridinfo.Cell(e.Row, 2).Text, Gridinfo.Cell(e.Row, 3).Text, e.Row)

        End Select

    End Sub

    '显示或隐藏光标

    Public Sub ShowOrHidecursor(name As String, start As String, rowi As Integer)
        If IsNothing(lineSetDic) OrElse lineSetDic.Count = 0 Then Return
        If lineSetDic.ContainsKey(name) Then
            Dim lineSet = lineSetDic(name)
            Dim node As Steema.TeeChart.Styles.Bezier
            For i = 0 To lineSet.Item2.Values.Count - 1
                node = lineSet.Item2.Values(i)
                If start = "1" Then
                    node.Visible = True
                    Gridinfo.Cell(rowi, 5 + i).ForeColor = node.Color
                Else
                    node.Visible = False
                    Gridinfo.Cell(rowi, 5 + i).ForeColor = Color.LightGray
                End If
            Next



        End If

    End Sub
    '矫正时间变量
    Public CorrectionTime As DateTime
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        '以秒为单位判断上次时间和当前时间差是否大于1秒 
        If (DateTime.Now - CorrectionTime).TotalSeconds > 1 Then
            '如果大于1秒，则更新时间
            CorrectionTime = DateTime.Now.AddMilliseconds(-DateTime.Now.Millisecond)
            '判断队列是否有数据
            If Queue.Count > 0 Then
                Dim data As String
                Dim buf() As String
                Dim selectstr As String = String.Empty
                Dim Insert As String
                Dim lin As Steema.TeeChart.Styles.Bezier
                Dim t As DateTime
                Dim dint As Double
                'SetseriesSmoothed(False)

                For i As Integer = 0 To Queue.Count - 1

                    data = Queue.Dequeue()
                    ' If Queue.Count > 1 Then
                    'Console.WriteLine($"Queue  :  {data}")
                    'End If
                    buf = data.Split(",")
                    t = Date.Parse(buf(0))
                    ToolStripLabel4.Text = $"当前时间：{buf(0)}"
                    ' ChartBar.Axes.Bottom.Maximum = t.ToOADate
                    dxRectangle(t.ToOADate)


                    'If （TChart1.Axes.Bottom.Maximum - TChart1.Axes.Bottom.Minimum） > 15 Then
                    '    TChart1.Axes.Bottom.Minimum = TChart1.Axes.Bottom.Minimum + 1
                    'End If
                    'TChart1.Axes.Bottom.Maximum = Double.Parse(buf(1))

                    'Bezier1.ColorEachLine = True
                    ' Console.WriteLine($"Maximum:{ TChart1.Axes.Bottom.Maximum}  Maximum:{ TChart1.Axes.Bottom.Maximum}  x:{ Double.Parse(buf(1))} y:{buf(7)}")

                    For Each item In lineSetDic
                        For index As Integer = 0 To item.Value.Item2.Values.Count - 1
                            'Console.WriteLine($" {item.Value.Item2.Keys(index)} {t.ToString("yyyy-MM-dd HH:mm:ss")}:{vbCrLf}:{buf(index + 2)}")
                            lin = item.Value.Item2.Values(index)

                            dint = Double.Parse(buf(index + 2))
                            'Console.WriteLine($"Milliseconds:{t.Millisecond}")
                            lin.Add(t.ToOADate, dint)
                            lin.Title = item.Value.Item2.Keys(index)
                            'lin.Smoothed = True
                            'lin.XValues.DateTime = True

                        Next
                    Next
                    ShowlastData(buf)


                    Insert = $"INSERT INTO [Logdata]
                                      ([SN] ,                                                                     
                                          [Datatime] ,
                                             [V1] ,
                                             [T1] ,
                                             [C1] ,
                                             [V2] ,
                                             [T2] ,
                                             [C2] ,
                                             [V3] ,
                                             [T3] ,
                                             [C3] ,
                                             [V4] ,
                                             [T4] ,
                                             [C4] ,
                                             [V5] ,
                                             [T5] ,
                                             [C5] ,
                                             [V6] ,
                                             [T6] ,
                                             [C6] )
                                     VALUES
                                     ('{buf(1)}',
                                            '{buf(0)}',
                                            '{buf(2)}',
                                            '{buf(3)}',
                                            '{buf(4)}',
                                            '{buf(5)}',
                                      '{buf(6)}',
                                      '{buf(7)}',
                                      '{buf(8)}',
                                      '{buf(9)}',
                                      '{buf(10)}',
                                      '{buf(11)}',
                                      '{buf(12)}',
                                      '{buf(13)}',
                                      '{buf(14)}',
                                      '{buf(15)}',
                                      '{buf(16)}',
                                      '{buf(17)}',
                                            '{buf(18)}',
                                            '{buf(19)}'
                                            );{vbCrLf }"
                    selectstr = $"{selectstr}{Insert}"

                Next

                InsertData1(selectstr)
                'SetseriesSmoothed(True)
                ' Refresh()
            Else
                'For Each lineSet In lineSetDic
                '    For Each node In lineSet.Item2.Values
                '        If start = "1" Then
                '            node.Visible = True

                '        Else
                '            node.Visible = False
                '        End If
                '    Next
                'Next

            End If
        End If


        'While True
        '    If IsStart Then

        '    End If
        'End While
    End Sub
    '在表格显示数据
    Public Sub ShowlastData(data() As String)

        For r = 1 To Gridinfo.Rows - 1
            Gridinfo.Cell(r, 4).Text = data(0)
            Gridinfo.Cell(r, 5).Text = data(r * 3 - 1)
            Gridinfo.Cell(r, 6).Text = data(r * 3)
            Gridinfo.Cell(r, 7).Text = data(r * 3 + 1)
        Next
    End Sub

    '插入数据
    Public Function InsertData1(selectstr As String) As DataTable
        Dim localConn As New DbConnectionStringBuilder
        localConn.Add("Data Source", Application.StartupPath.ToString() & "\Log.db")
        'localConn.Add("Password", "123456")
        Dim LocalConnString = localConn.ToString()
        Dim dt As DataTable
        Using db As New DbExecutor(DbExecutor.DbTypeEnum.Sqlite, LocalConnString)
            db.Open()
            Try
                ' 开始一个事务
                db.BeginTransaction()
                dt = db.ExecuteDataTable(selectstr)
                db.CommitTransaction()
            Catch ex As Exception
                db.RollbackTransaction()
            End Try
            db.Close()
        End Using
        Return dt
    End Function
    Public Function InsertData(selectstr As String) As DataTable
        Dim localConn As New DbConnectionStringBuilder
        localConn.Add("Data Source", Application.StartupPath.ToString() & "\Log.db")
        'localConn.Add("Password", "123456")
        Dim LocalConnString = localConn.ToString()
        Dim dt As DataTable
        Using db As New DbExecutor(DbExecutor.DbTypeEnum.Sqlite, LocalConnString)
            db.Open()
            Try
                ' 开始一个事务
                'db.BeginTransaction()
                dt = db.ExecuteDataTable(selectstr)
                'db.CommitTransaction()
            Catch ex As Exception
                'db.RollbackTransaction()
            End Try
            db.Close()
        End Using
        Return dt
    End Function

    '创建sqlite数据库
    Public Function ClearDeviceform() As Boolean

        Dim localConn As New DbConnectionStringBuilder
        localConn.Add("Data Source", Application.StartupPath.ToString() & "\Log.db")
        'localConn.Add("Password", "123456")
        Dim LocalConnString = localConn.ToString()


        Dim selectstr As String = $"CREATE TABLE  IF NOT EXISTS [Logdata] (
	                                                                [ID] integer COLLATE BINARY NOT NULL PRIMARY KEY AUTOINCREMENT, 
	                                                                [SN] nvarchar(254) COLLATE BINARY,                                                                     
	                                                                [Datatime] nvarchar(254) COLLATE BINARY,
                                                                    [V1] nvarchar(254) COLLATE BINARY,
                                                                    [T1] nvarchar(254) COLLATE BINARY,
                                                                    [C1] nvarchar(254) COLLATE BINARY,
                                                                    [V2] nvarchar(254) COLLATE BINARY,
                                                                    [T2] nvarchar(254) COLLATE BINARY,
                                                                    [C2] nvarchar(254) COLLATE BINARY,
                                                                    [V3] nvarchar(254) COLLATE BINARY,
                                                                    [T3] nvarchar(254) COLLATE BINARY,
                                                                    [C3] nvarchar(254) COLLATE BINARY,
                                                                    [V4] nvarchar(254) COLLATE BINARY,
                                                                    [T4] nvarchar(254) COLLATE BINARY,
                                                                    [C4] nvarchar(254) COLLATE BINARY,
                                                                    [V5] nvarchar(254) COLLATE BINARY,
                                                                    [T5] nvarchar(254) COLLATE BINARY,
                                                                    [C5] nvarchar(254) COLLATE BINARY,
                                                                    [V6] nvarchar(254) COLLATE BINARY,
                                                                    [T6] nvarchar(254) COLLATE BINARY,
                                                                    [C6] nvarchar(254) COLLATE BINARY                                                                                                         
                                                                    )"

        Dim dt As DataTable
        Try
            Using db As New DbExecutor(DbExecutor.DbTypeEnum.Sqlite, LocalConnString)

                db.Open()
                'Try
                '    'Dim vselectstr = $"DELETE FROM {Tftp_Log};"
                '    'db.ExecuteNonQuery(vselectstr)
                'Catch ex As Exception


                'End Try
                dt = db.ExecuteDataTable(selectstr)
                db.Close()
                If IsNothing(dt) Then
                    MsgBox($"数据表创建失败！！！{vbCrLf }")
                    Return False
                Else
                    Return True
                End If
                Return True

            End Using

        Catch ex As Exception
            MsgBox($"数据表创建失败！！！{vbCrLf }原因:{vbCrLf }{ex.Message }")
            Return False
        End Try
    End Function

    Private Sub ToolStripButton5_Click(sender As Object, e As EventArgs) Handles ToolStripButton8.Click
        '查询数据库Logdata表格并显示到Grid_config
        Dim localConn As New DbConnectionStringBuilder
        localConn.Add("Data Source", Application.StartupPath.ToString() & "\Log.db")
        Dim LocalConnString = localConn.ToString()
        Dim selectstr As String = $"SELECT * FROM Logdata"
        Dim dt As DataTable
        Try
            Using db As New DbExecutor(DbExecutor.DbTypeEnum.Sqlite, LocalConnString)
                db.Open()
                dt = db.ExecuteDataTable(selectstr)
                db.Close()
                If IsNothing(dt) Then
                    MsgBox($"数据表查询失败！！！{vbCrLf }")
                    Return
                Else
                    Grid_config.DataSource = dt

                End If
            End Using
        Catch ex As Exception
            MsgBox($"数据库异常！！！{vbCrLf }")
        End Try
    End Sub

    Private Sub Gridinfo_Click(Sender As Object, e As EventArgs) Handles Gridinfo.Click
        Dim C_x, C_y As Integer
        C_x = Gridinfo.ActiveCell.Row
        C_y = Gridinfo.ActiveCell.Col
        If C_x = 0 Then Return
        Select Case C_y
            Case 1
                ToolStripLabel3.Text = $"测试名称{Gridinfo.Cell(C_x, 1).Text}"
                QuerySqliteData(C_x)

        End Select

    End Sub
    '按条件查询数据表
    Public Function QuerySqliteData(index As Integer) As Boolean
        '' GridMessage.Range(1, 1, GridMessage.Rows - 1, 1).SelectCells.Clear()
        Dim selectstr As String = $"SELECT  [ID],
                                            [SN] ,                                                                     
	                                        [Datatime] ,
                                            [V{index}] ,
                                            [T{index}] ,
                                            [C{index}] 
                                            FROM [Logdata] ORDER BY [ID] "
        Dim dt = InsertData(selectstr)
        If IsNothing(dt) Then
            MsgBox($"数据表查询失败！！！{vbCrLf }")
            Return False
        End If
        GridMessage.DataSource = dt
        ToolStripLabel5.Text = $"信息数量({dt.Rows.Count})"
    End Function
    Public ZoomX1, ZoomX2 As Double
    Private Sub ChartBar_Zoomed(sender As Object, e As EventArgs) Handles ChartBar.Zoomed
        'Console.WriteLine(e)
        ''Console.WriteLine(sender)
        ''AccessibilityObject = {ControlAccessibleObject: Owner = Steema.TeeChart.TChart}
        ' Dim mChartBar As Steema.TeeChart.TChart = sender
        'ZoomX1 = ChartBar.Axes.Bottom.CalcXPosValue(mChartBar.AccessibilityObject.Bounds.X)
        ''xMin = ChartBar.Axes.Bottom.CalcPosValue(mChartBar.AccessibilityObject.Bounds.X)
        ''Console.WriteLine(xMin)
        ''Console.WriteLine(xMin)
        'ZoomX2 = ZoomX1 + mChartBar.AccessibilityObject.Bounds.Width
        'ZoomX2 = ChartBar.Axes.Bottom.CalcPosPoint(ZoomX2)
        'ZoomX2 = ZoomX1
        'ZoomX1 = mChartBar.AccessibilityObject.Bounds.X

        'Console.WriteLine($"ZoomX1:{ZoomX1}  ZoomX2:{ZoomX2}")
        'ChartBar.Zoom.ZoomRect(New Rectangle(xMin, 0, MyValue, ChartBar.Height))
        'ZoomX1 = 1
    End Sub

    Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
        Dim li As List(Of Integer) = New List(Of Integer)()
        For i = 1 To Gridinfo.Rows - 1
            If Gridinfo.Cell(i, 3).Text = "1" Then
                li.Add(i)
            End If


        Next

        Form1_Load(Nothing, Nothing)
        CorrectionTime = Now
        ChartBar.Axes.Bottom.Minimum = Date.Parse(Now.ToString("yyyy-MM-dd HH:mm:ss")).ToOADate
        ZoomX1 = 0
        ZoomX2 = 0
        For Each index In li
            Gridinfo.Cell(index, 3).Text = "1"
        Next
    End Sub



    Private Sub ChartBar_MouseUp(sender As Object, e As MouseEventArgs) Handles ChartBar.MouseUp
        If xlen = True AndAlso isMouseMove = True Then
            '计算按下点位在图标的坐标
            Dim values As Double = ChartBar.Axes.Bottom.CalcPosPoint(e.X)
            Dim values1 As Double = ChartBar.Axes.Left.CalcPosPoint(e.Y)
            'MessageBox.Show("MouseUp  X: " & values.ToString() & ", Y: " & values1.ToString())
            ZoomX2 = values
            ' Console.WriteLine($"MouseUp  X: {values} , Y: {values1}")
            If ZoomX1 > 0 And ZoomX2 > 0 Then

                '判断缩放方向
                If ZoomX1 > ZoomX2 Then '缩小
                    'ChartBar.Zoom.Undo()
                    ChartBar.Axes.Bottom.Minimum = ChartBar.Axes.Bottom.MinXValue
                    ChartBar.Axes.Bottom.Maximum = ChartBar.Axes.Bottom.MaxXValue
                ElseIf ZoomX1 = ZoomX2 Then
                    Return
                Else
                    ChartBar.Axes.Bottom.Minimum = ZoomX1
                    ChartBar.Axes.Bottom.Maximum = ZoomX2
                End If

                'Console.WriteLine($"ZoomX1:{ZoomX1}  ZoomX2:{ZoomX2}")
            End If
        End If
        xlen = False
        isMouseMove = False
    End Sub
    Public isMouseMove As Boolean = False
    Private Sub ChartBar_MouseMove(sender As Object, e As MouseEventArgs) Handles ChartBar.MouseMove
        If xlen = True Then
            isMouseMove = True
            'Console.WriteLine($"isMouseMove:{isMouseMove}")
        Else
            isMouseMove = False
        End If

    End Sub

    Private Sub ChartBar_MouseDown(sender As Object, e As MouseEventArgs) Handles ChartBar.MouseDown
        xlen = False
        If e.Button = MouseButtons.Left Then
            xlen = True
            Dim values As Double = ChartBar.Axes.Bottom.CalcPosPoint(e.X)
            Dim values1 As Double = ChartBar.Axes.Left.CalcPosPoint(e.Y)
            ZoomX1 = values
            ' Console.WriteLine($"MouseDown  X: {values} , Y: {values1}")
        End If
    End Sub

    Private Sub ToolStripButton6_Click(sender As Object, e As EventArgs) Handles ToolStripButton6.Click
        'If ToolStripButton6.Text.Equals("波形数据") Then
        '    ToolStripButton6.Text = "折线数据"
        '    For Each series In ChartBar.Series
        '        series.Smoothed = False
        '        series.XValues.DateTime = True
        '    Next
        'Else
        '    ToolStripButton6.Text = "波形数据"
        '    For Each series In ChartBar.Series
        '        series.Smoothed = True
        '        series.XValues.DateTime = False
        '    Next
        'End If
        'For Each series In ChartBar.Series
        '    Dim MyRnd As New Random
        '    series.Color = lincolorArry(MyRnd.Next(0, 16))
        'Next


        'Line1.Smoothed = Not Line1.Smoothed
    End Sub
    Public Sub SetseriesSmoothed(isSmoothed As Boolean)
        For Each series In ChartBar.Series
            If isSmoothed = True Then
                'series.Smoothed = True
                series.XValues.DateTime = False
            Else
                series.Smoothed = False
                series.XValues.DateTime = True
            End If
        Next
        If isSmoothed = True Then
            For Each series In ChartBar.Series
                series.Smoothed = False
                series.XValues.DateTime = True
            Next
        End If

    End Sub
    Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton5.Click
        '查询数据库Logdata表格并显示到Grid_config
        Dim localConn As New DbConnectionStringBuilder
        localConn.Add("Data Source", Application.StartupPath.ToString() & "\Log.db")
        Dim LocalConnString = localConn.ToString()
        Dim selectstr As String = $"DELETE FROM Logdata; "
        Dim dt As DataTable
        Try
            Using db As New DbExecutor(DbExecutor.DbTypeEnum.Sqlite, LocalConnString)
                db.Open()
                db.ExecuteNonQuery(selectstr)
                db.Close()

            End Using
        Catch ex As Exception
            MsgBox($"数据库异常！！！{vbCrLf }")
        End Try
    End Sub

    Private Sub TChart1_Click(sender As Object, e As EventArgs) Handles TChart1.Click
        Dim TLineSeries As Steema.TeeChart.Styles.Line = New Steema.TeeChart.Styles.Line
        'TLineSeries.Add(1, 2, True)
        ' FastLine1.bBrush
        ' Bezier1.Add(1, 2, True)
    End Sub

    Private Sub ToolStripButton7_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
        For Each series In ChartBar.Series
            series.Marks.Visible = Not series.Marks.Visible
            series.Pointer.Visible = series.Marks.Visible
        Next


    End Sub


    '局部放大图标
    Public Sub dxRectangle(dx As Double)

        'Console.WriteLine($"1 Bottom.Minimum:{ChartBar.Axes.Bottom.Minimum} Bottom.Maximum:{ ChartBar.Axes.Bottom.Maximum} ChartBar.Axes.Bottom.MaxXValue:{ChartBar.Axes.Bottom.MaxXValue} ChartBar.Axes.Bottom.MinXValue:{ChartBar.Axes.Bottom.MinXValue}")


        If ZoomX1 > 0 And ZoomX2 > 0 Then
            ChartBar.Axes.Bottom.Minimum = DateTime.FromOADate(ChartBar.Axes.Bottom.Minimum).AddSeconds(1).ToOADate
            ChartBar.Axes.Bottom.Maximum = DateTime.FromOADate(ChartBar.Axes.Bottom.Maximum).AddSeconds(1).ToOADate
            ChartBar.Refresh()
            'ZoomX1 = 0
            'ZoomX2 = 0
        Else
            ' Console.WriteLine($"Bottom.Maximum :{  ChartBar.Axes.Bottom.Maximum }  dx：{dx}")
            ChartBar.Axes.Bottom.Maximum = dx


        End If


        'If ChartBar.Axes.Bottom.Minimum < ChartBar.Axes.Bottom.MinXValue Then
        '    ChartBar.Axes.Bottom.Minimum = ChartBar.Axes.Bottom.MinXValue
        'End If
        'If ChartBar.Axes.Bottom.Maximum > ChartBar.Axes.Bottom.MaxXValue Then
        '    ChartBar.Axes.Bottom.Maximum = ChartBar.Axes.Bottom.MaxXValue

        'End If
        'Console.WriteLine($"ZoomX1:{ZoomX1} ZoomX2:{ZoomX2} Bottom.Minimum:{ChartBar.Axes.Bottom.Minimum} Bottom.Minimum:{ ChartBar.Axes.Bottom.Maximum} ChartBar.Axes.Bottom.MaxXValue:{ChartBar.Axes.Bottom.MaxXValue} ChartBar.Axes.Bottom.MaxXValue:{ChartBar.Axes.Bottom.MaxXValue}")
        ' Console.WriteLine($"2 Bottom.Minimum:{ChartBar.Axes.Bottom.Minimum} Bottom.Maximum:{ ChartBar.Axes.Bottom.Maximum} ChartBar.Axes.Bottom.MaxXValue:{ChartBar.Axes.Bottom.MaxXValue} ChartBar.Axes.Bottom.MinXValue:{ChartBar.Axes.Bottom.MinXValue}")

    End Sub

End Class
