Imports UTS_Core.Database
Imports UTS_Core.UTSModule.DbTableModel.Customer
Imports UTS_Core.UTSModule.Test
Imports UTS_Core.UTSModule.Test.TestResult

Public Class AttributeTest

    Enum ColNames
        No
        Content
        DataSource
        SendData
        PassResult
        RetryCount
        RetryInterval
        ReadInterval
        OperatingMode
        Lower
        Upper
        TestVal
        TestResult
        IsRecord
        RecordName
        Max
    End Enum

    Public Val_mac As String
    Public Val_version As String
    Public Val_voltage As String
    Public Val_tempre As String
    Public Val_humiture As String
    Public Val_keyleft As String
    Public Val_keyright As String
    Public Val_pir As String

    Public Userkeyval_Key As IO.Ports.SerialPort
    Public Userkeyval_Rictext As RichTextBox
    Public cmdcolor As Color
    Public txtcolor As Color

    Public Userkeyval_ComboBox As ComboBox
    Public Userkeyval_ProgressBar As ProgressBar
    Public Userkeyval_Station As Label
    Public Userkeyval_PASS As Label
    Public Userkeyval_StepTip As Label
    Public Userkeyval_Tip As Label
    Public Userkeyval_check As CheckBox
    Public Userkeyval_grid As FlexCell.Grid

    Public Userkeyval_TestTable As TestResult

    Sub New（ByRef grid As FlexCell.Grid）
        Userkeyval_grid = grid
        UpdateStepTestRecord1()
        DefaultData()
        Userkeyval_TestTable = New TestResult
    End Sub
#Region "初始化表格"
    Public Sub UpdateStepTestRecord1()
        With Userkeyval_grid
            .AutoRedraw = False
            '.AutoSize = True
            .Cols = ColNames.Max
            .Rows = 1
            .ExtendLastCol = True   '最后一列自动扩充
            .DisplayRowNumber = True    '首列显示数字

            For col As Integer = 0 To ColNames.Max - 1
                .Cell(0, col).Text = [Enum].GetName(GetType(ColNames), col) '设置列名
                .Column(col).CellType = FlexCell.CellTypeEnum.TextBox '设置列型
                If col = ColNames.Content OrElse col = ColNames.SendData Then
                    .Column(col).Width = 140 '设置列宽
                Else
                    .Column(col).Width = 70 '设置列宽
                End If
                .Column(col).Alignment = FlexCell.AlignmentEnum.RightCenter '设置对齐位置
            Next
            .ForeColorComment = Color.Blue

            ' .FrozenCols = ColNames.Description '冻结列

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


#End Region

#Region "加載表格數據"
    Public Sub DefaultData()

        Dim SendDatalist As New List(Of List(Of String））
        UartSendDataList(SendDatalist， "确认设备MAC地址", "设备", "mac", "", "5", "100", "", "len", "", "", "", "", "Y", "DUT_SN")
        UartSendDataList(SendDatalist， "确认设备固件版本", "设备", "version", "", "5", "100", "", "comparison", "0.1.1.1", "0.1.1.1", "", "", "Y", "FW_Ver")
        UartSendDataList(SendDatalist， "确认设备电压", "设备", "voltage", "", "5", "100", "", "scope", "1.8", "2.3", "", "", "Y", "Volt")
        UartSendDataList(SendDatalist， "确认设备温度", "设备", "tempre", "", "5", "100", "", "null", "", "", "", "", "Y", "DUT_Temp")
        UartSendDataList(SendDatalist， "确认设备湿度", "设备", "humiture", "", "5", "100", "", "null", "", "", "", "", "Y", "DUT_Humid")
        UartSendDataList(SendDatalist， "确认环境温度", "uts", "tempre", "", "", "", "", "null", "", "", "", "", "Y", "Enov_Temp")
        UartSendDataList(SendDatalist， "确认环境湿度", "uts", "humiture", "", "", "", "", "null", "", "", "", "", "Y", "Enov_Humdi")
        UartSendDataList(SendDatalist， "确认温度误差", "设备-uts", "4", "6", "", "", "", "null", "", "", "", "", "Y", "Diff_Temp")
        UartSendDataList(SendDatalist， "确认湿度误差", "设备-uts", "5", "7", "", "", "", "null", "", "", "", "", "Y", "Diff_Humidi")
        UartSendDataList(SendDatalist， "确认PIR数值", "设备", "pir", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "提示：请打开PIR窗口", "设备", "tip", "", "", "", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认PIR数值", "设备", "pir", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "提示：请关闭PIR窗口", "设备", "tip", "", "", "", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认PIR数值", "设备", "pir", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认左键键值", "设备", "keyleft", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认右键键值", "设备", "keyright", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "提示：请按下左键", "设备", "tip", "", "", "", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认左键键值", "设备", "keyleft", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认右键键值", "设备", "keyright", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "提示：请按下右键", "设备", "tip", "", "5", "100", "", "null", "", "", "", "", "", "")

        UartSendDataList(SendDatalist， "确认左键键值", "设备", "keyleft", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认右键键值", "设备", "keyright", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "提示：请松开按键", "设备", "tip", "", "", "", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认左键键值", "设备", "keyleft", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "确认右键键值", "设备", "keyright", "", "5", "100", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "读取平均电流", "uts", "run", "", "", "", "", "null", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "读取峰值电流", "uts", "current", "", "", "", "", "null", "", "", "", "", "", "")
        Grid5AddRow(SendDatalist)
    End Sub



    Public Function GetDeviceData(rowid As Integer, attri As String) As Boolean
        If attri.ToLower.Equals("mac") Then
            Return checkoutRusli(Val_mac, rowid)
        ElseIf attri.ToLower.Equals("version") Then
            'SetAttriGridt(Userkeyval_grid, rowid, ColNames.TestVal, )
            Return checkoutRusli(Val_version, rowid)
        ElseIf attri.ToLower.Equals("voltage") Then
            Return checkoutRusli(Val_voltage, rowid)
        ElseIf attri.ToLower.Equals("tempre") Then
            Return checkoutRusli(Val_tempre, rowid)
        ElseIf attri.ToLower.Equals("humiture") Then
            Return checkoutRusli(Val_humiture, rowid)
        ElseIf attri.ToLower.Equals("pir") Then
            Return checkoutRusli(Val_pir, rowid)
        ElseIf attri.ToLower.Equals("keyleft") Then
            Return checkoutRusli(Val_keyleft, rowid)
        ElseIf attri.ToLower.Equals("keyright") Then
            Return checkoutRusli(Val_keyright, rowid)
        ElseIf attri.ToLower.Equals("tip") Then
            Settiptext(Userkeyval_Tip, Userkeyval_grid.Cell(rowid, ColNames.Content).Text.Trim)
            Return True
        End If
    End Function


    Public Function checkoutRusli(Attri As String, rowid As Integer) As Boolean
        Dim celltxt As String = Userkeyval_grid.Cell(rowid, ColNames.OperatingMode).Text.Trim
        SetAttriGridt(Userkeyval_grid, rowid, ColNames.TestVal, Attri)
        If celltxt.Equals("len") Then
            If Attri.Length = 6 Then
                Return True
            Else
                Return False
            End If
        ElseIf celltxt.Equals("comparison") Then
            Dim Lower As String = Userkeyval_grid.Cell(rowid, ColNames.Lower).Text.Trim
            Dim Upper As String = Userkeyval_grid.Cell(rowid, ColNames.Upper).Text.Trim
            If Attri.Contains(Lower) OrElse Attri.Contains(Upper) Then
                Return True
            Else
                Return False
            End If
        ElseIf celltxt.Equals("scope") Then
            Dim Attriint As Double = 0
            Dim Lowerint As Double = 0
            Dim Upperint As Double = 0

            If Not Double.TryParse(Attri, Attriint) OrElse Not Double.TryParse(Attri, Lowerint) OrElse Not Double.TryParse(Attri, Lowerint) Then
                Return False
            End If
            If Attriint > Lowerint OrElse Attriint < Upperint Then
                Return False
            Else
                Return True
            End If
        ElseIf celltxt.Equals("Null") Then
            Return True

        End If

    End Function



    Public Function UartSendDataList(ByRef SendDatalist As List(Of List(Of String））， ParamArray ptr（） As String) As List(Of String）

        Dim Datalist As New List(Of String）
        Datalist.AddRange(ptr)
        SendDatalist.Add(Datalist)

    End Function

    Public Sub Grid5AddRow(SendDatalist As List(Of List(Of String））)
        If SendDatalist.Count < 1 Then Return

        For rowindex As Integer = 0 To SendDatalist.Count - 1

            Dim Datalist As List(Of String） = SendDatalist.Item(rowindex)


            AddRowToTable(Userkeyval_grid, Datalist)
        Next

    End Sub
    Public Sub AddRowToTable（tablegrid As FlexCell.Grid, Datalist As List(Of String））
        tablegrid.AddItem("")
        For colid As Integer = 1 To ColNames.Max - 1
            tablegrid.Cell(tablegrid.Rows - 1, colid).Text = Datalist.Item(colid - 1)
        Next
    End Sub

#End Region

#Region "流程动作"

    Delegate Sub IPSettiptext(tablegrid As Label, txt As String)
    Public Sub Settiptext(tablegrid As Label, txt As String)
        If tablegrid.InvokeRequired Then
            tablegrid.Invoke(New IPSettiptext(AddressOf Settiptext), New Object() {tablegrid, txt})
        Else
            tablegrid.Text = txt
        End If
    End Sub

    Delegate Sub IPSetAttriGridt(tablegrid As FlexCell.Grid, trowel As Integer, tcol As Integer, txt As String)
    Public Sub SetAttriGridt(tablegrid As FlexCell.Grid, trowel As Integer, tcol As Integer, txt As String)
        If tablegrid.InvokeRequired Then
            tablegrid.Invoke(New IPSetAttriGridt(AddressOf SetAttriGridt), New Object() {tablegrid, trowel, tcol, txt})
        Else
            tablegrid.Cell(trowel, tcol).Text = txt
            If trowel = ColNames.TestResult Then
                Userkeyval_PASS.Text = txt
                If txt.ToLower.Equals（"pass"） Then
                    Userkeyval_PASS.BackColor = Color.Green
                ElseIf txt.ToLower.Equals（"false"） Then
                    Userkeyval_PASS.BackColor = Color.Red
                End If
            End If

            Userkeyval_ProgressBar.Value =trowel
        End If
    End Sub

    Public Sub clearGridResult(tablegrid As FlexCell.Grid)
        For rowid As Integer = 1 To tablegrid.Rows - 1
            SetAttriGridt(tablegrid, rowid, ColNames.TestResult, "")
            SetAttriGridt(tablegrid, rowid, ColNames.TestVal, "")
        Next
    End Sub

    Public Function ADDTestRecordVal(testattribute As TestTableAttribute) As Dictionary(Of String, String)
        Dim dic As New Dictionary(Of String, String) From {
                  {$"{TestLogTable.ColNames.UserID}", testattribute.UserID.ToString()},
                  {$"{TestLogTable.ColNames.ServiceID}", testattribute.ServiceID.ToString()},
                  {$"{TestLogTable.ColNames.DUT_SN}", testattribute._dutSn},
                  {$"{TestLogTable.ColNames.AppName}", testattribute.AppName},
                  {$"{TestLogTable.ColNames.TestPlan}", testattribute.TestPlan},
                  {$"{TestLogTable.ColNames.StartTime}", testattribute.StartTime.ToString("yyyy-MM-dd HH:mm:ss")},
                  {$"{TestLogTable.ColNames.UsedTime}", testattribute.TotalSeconds.ToString("F2")},
                  {$"{TestLogTable.ColNames.TestResult}", IIf(testattribute.TestResult = TestResultEnum.Fail, 0, 1).ToString()},
                  {$"{TestLogTable.ColNames.ErrCode}", testattribute.ErrCode},
                  {$"{TestLogTable.ColNames.ProductionLineID}", testattribute.ProductionLineID.ToString()},
                  {$"{TestLogTable.ColNames.OrderID}", testattribute.OrderID.ToString()}
              }
        dic.Add($"{TestLogTable.ColNames.FailSteps}", testattribute.rownum.ToString())
        dic.Add($"{TestLogTable.ColNames.FailMsg}", testattribute.TertResult & testattribute.UpVal & testattribute.loadVal)

        For Each keyValue As KeyValuePair(Of String, String) In testattribute.AddSelf
            If dic.ContainsKey(keyValue.Key) Then
                dic(keyValue.Key) = keyValue.Value
            Else
                dic.Add(keyValue.Key, keyValue.Value)
            End If
        Next
        Return dic
    End Function
    Public Sub UpdateTestLogToRemote(db As DbExecutor, dbName As String, tbName As String, result As TestTableAttribute)
        Dim field As Dictionary(Of String, String) = ADDTestRecordVal(result)

        '新增不存在的字段
        CheckTestLogFiledToRemote(db, dbName, tbName, field)

        '添加测试记录
        Dim cmdText As String = db.CmdHelper.DbInsert(dbName, tbName, field)
        db.ExecuteNonQuery(cmdText)
    End Sub
#End Region
    ''' <summary>
    ''' 检测测试记录字段名是否存在远端数据库，如果不存在则新增，存在则检测字段长度是否需要加长
    ''' </summary>
    ''' <param name="db">数据库执行器</param>
    ''' <param name="dbName">数据库名</param>
    ''' <param name="tbName">数据表名</param>
    ''' <param name="field">测试记录字段集合</param>
    Public Shared Sub CheckTestLogFiledToRemote(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String))
        Dim dtCol As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tbName, "1 = 0"))

        Dim fieldName As List(Of String) = field.Keys.ToList
        Dim typeString As String
        Dim length As Integer
        For Each colName As String In fieldName
            If String.IsNullOrWhiteSpace(colName) Then Continue For '剔除无效数据库字段名

            If dtCol.Columns.Contains(colName) Then '当前数据表是否已经存在对应列信息
                Select Case dtCol.Columns(colName).DataType.Name
                    Case "String" '仅处理VarChar类型
                        If field(colName).Length > dtCol.Columns(colName).MaxLength Then
                            length = GetFiledLength(field(colName).Length)
                            If length = -1 Then
                                Throw New Exception($"字段[{colName}] 超过最大长度2048的限制,无法入库!")
                            Else
                                typeString = $"varchar({length})"
                            End If

                            '修改列字段长度
                            db.ExecuteNonQuery($"Call `{dbName}`.`AlterTestLogFiled`('{dbName}','{tbName}','{colName}','{length}')")
                        End If
                    Case Else
                        Console.WriteLine(colName & ":" & dtCol.Columns(colName).DataType.Name)
                End Select
            Else
                length = GetFiledLength(field(colName).Length)
                If length = -1 Then
                    Throw New Exception($"字段[{colName}] 超过最大长度4096的限制,无法入库!")
                Else
                    typeString = $"varchar({length})"
                End If

                '插入字段语句
                db.ExecuteNonQuery($"Call `{dbName}`.`AlterTestLogFiled`('{dbName}','{tbName}','{colName}','{length}')")
            End If
        Next
    End Sub
    Private Shared Function GetFiledLength(len As Integer) As Integer
        Dim result As Integer
        If len = 0 Then
            result = 8
        ElseIf len <= 2048 Then
            If len Mod 8 = 0 Then
                result = len
            Else
                result = ((len \ 8) + 1) * 8
            End If
        Else
            result = -1
        End If
        Return result
    End Function
End Class


Public Class TestTableAttribute
    Public UserID As String
    Public ServiceID As String
    Public _dutSn As String
    Public AppName As String
    Public TestPlan As String
    Public StartTime As Date
    Public TotalSeconds As Double
    Public TestResult As TestResultEnum
    Public ErrCode As String
    Public ProductionLineID As Integer
    Public OrderID As Integer

    Public rownum As Integer
    Public TertResult As String
    Public UpVal As String
    Public loadVal As String

    Public AddSelf As Dictionary(Of String, String)

    Public Sub New()
        AddSelf = New Dictionary(Of String, String)
    End Sub

    Public Sub AddSelfAttribute（clunm As String, val As String）
        AddSelf.Add(clunm, val)
    End Sub
    Public Sub AddSelfClear（）
        AddSelf.Clear()
    End Sub


End Class

