Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Threading
Imports Newtonsoft.Json
Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Test
Imports UTS_Core.UTSModule.Test.StatusMonitor

Public Class ZQ_Mars_P2_FrmStationTest
    Implements IProcessStation
    Public Isopenflag As Boolean = False
    Private _stationPlan As StationPackagePlan
    Private Stnum As Integer = 0
    Private Utnum As Integer = 0
    Private Stnum_cnt As Integer = 0

    Public _Uart1Tack As Thread

    Private _utsApp As UtsAppForm
    Public Sub ConfigSerialPort(Serial As IO.Ports.SerialPort, BaudRate As Integer, portName As String)
        With Serial
            .PortName = portName                '串口名
            .BaudRate = BaudRate ' _BaudRate      '波特率
            .DataBits = 8      '数据位
            .StopBits = Ports.StopBits.One            '停止位
            .Parity = Ports.Parity.None              '偶校验
            .RtsEnable = True
            .ReceivedBytesThreshold = 1
        End With
    End Sub

    Private Sub ZQ_Mars_P2_FrmStationTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ApplicationLog.WriteInfoLog($"测试页面加载中。")
        If InitializeUtsApp() = False Then Return

        'InitializeForm()

        _Uart1Tack = New Thread(AddressOf ReadUart1DataThread)
        _Uart1Tack.Start()
    End Sub
    Private Function InitializeUtsApp() As Boolean
        _utsApp = UtsAppForm.CreateSingleton()
        _utsApp.AddStatisticsObserver(CType(Me, IProcessStation))

        Try
            If _utsApp.IsInitialized = False Then
                _utsApp.Initialize(ProcessStation.StationTypeEnum.Package) 'Todo:可根据需要限定可选站位
            End If
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"初始化窗体失败,原因：{ex.Message}!")

            MsgBox($"初始化窗体失败,原因：{ex.Message}")
            Close()
            Return False
        End Try

        Return True

    End Function
    Public Sub Station_Changed() Implements IProcessStation.StationChanged
        'Todo:站位变化代码
        ApplicationLog.WriteInfoLog($"测试页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}!")

        _stationPlan = CType(_utsApp.ProcessStation.Packet.StationPlan, StationPackagePlan)
        '清除表格数据
        'InitBarcodeGrid()

        ApplicationLog.WriteInfoLog($"测试页面站位变更完成!")
    End Sub
    Public Sub ReadUart1DataThread()
        Dim readStr As String
        Dim bufflen As Integer = 0
        Dim readUartStr As String = ""
        Dim uartport As IO.Ports.SerialPort = SerialPort1
        While True

            Try
                If uartport.IsOpen Then
                    bufflen = uartport.BytesToRead
                    If uartport.BytesToRead > 0 Then
                        Dim therecvBuffer(bufflen) As Byte
                        uartport.Read(therecvBuffer, 0, bufflen)
                        readStr = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

                        If readStr.Equals(vbNullChar) Then Continue While
                        readUartStr = readUartStr & readStr
                        readUartStr = readUartStr.Replace（vbNullChar, ""）

                        If readUartStr.Substring(readUartStr.Length - 2).Equals(vbCrLf) Then

                            UartGetNumber(readUartStr)
                        Else

                            Continue While

                        End If

                        readUartStr = ""
                    Else
                        Continue While
                    End If
                Else
                    Continue While
                End If
            Catch ex As Exception
                MsgBox("串口线程错误，请重新打开软件。")
                Return
            End Try


            Thread.Sleep(100)

        End While

    End Sub
    Public Sub ShowForm(parentControl As Control)
        FormBorderStyle = FormBorderStyle.None
        TopLevel = False
        Dock = DockStyle.Fill
        Parent = parentControl

        Show()
    End Sub


    Public Sub UartGetNumber(number As String)
        Dim buff() As String = number.Trim.Split(CType（" "， Char）)
        If buff.Length = 4 Then Return
        If number.ToLower.Contains（"US".ToLower） Then
            Settxt_testnum(number, Color.Blue)
            Stnum_cnt = 0
        ElseIf number.ToLower.Contains（"ST".ToLower） Then
            If Stnum_cnt > 5 Then
                Settxt_testnum(number, Color.Green)
            Else
                Stnum_cnt = Stnum_cnt + 1
            End If

        End If


    End Sub

    Public Function ConvertDAta(ptr（） As String) As String
        If ptr(4).ToLower.Equals("kg") Then
            Dim num As Integer = 0
            Integer.TryParse(ptr(3), num)
            Return CType(num * 1000, String)
        ElseIf ptr(4).ToLower.Equals("g") Then
            Return ptr(3)
        Else
            Return "-1"
        End If

    End Function


    Delegate Sub Settxttestnum(txt As String, thecolor As Color)
    Public Sub Settxt_testnum(txt As String, thecolor As Color)
        If Me.InvokeRequired Then '判断是否需要开委托
            'StuMain.Invoke(New Action(Of NetWorkStatusEnum)(AddressOf UpdateNetWorkStatus), New Object() {netStatus})
            Me.Invoke(New Settxttestnum（AddressOf Settxt_testnum）, {txt, thecolor})
            Return
        End If
        Dim buff() As String = txt.Trim.Split(CType（" "， Char）)
        txt_testnum.Text = ConvertDAta（buff）
        If txt_testnum.Text.Equals("-1") Then
            txt_testnum.ForeColor = Color.Red
            Return
        End If
        txt_testnum.ForeColor = thecolor



    End Sub



    Private Sub Btn_IsOpenSerialPort_Click(sender As Object, e As EventArgs) Handles Btn_IsOpenSerialPort.Click
        Dim BaudRate As Integer
        If Isopenflag Then

            SerialPort1.Close()
            Btn_IsOpenSerialPort.Text = "关闭串口"
            Btn_IsOpenSerialPort.BackColor = Color.LightGray
            Btn_IsOpenSerialPort.Enabled = False
            _Uart1Tack.Abort()

        Else

            If String.IsNullOrEmpty(Txt_BaudRate.Text.Trim) Then
                MsgBox("串口为空，请选择串口")
                Return
            End If
            Integer.TryParse(Txt_BaudRate.Text.Trim, BaudRate)
            ConfigSerialPort(SerialPort1, BaudRate, Cbo_SerialPort.Text.Trim)

            Try
                SerialPort1.Open()
            Catch ex As Exception
                MsgBox($"串口打开失败，详情：{ex.Message}")
                SerialPort1.Close()
                Return
            End Try
            _Uart1Tack = New Thread(AddressOf ReadUart1DataThread)
            _Uart1Tack.Start()

            Btn_IsOpenSerialPort.Text = "关闭串口"
            Btn_IsOpenSerialPort.BackColor = Color.Green
            Btn_IsOpenSerialPort.Enabled = True
        End If



    End Sub




    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Cbo_SerialPort.Items.Clear()
        Dim portNames As String() = Ports.SerialPort.GetPortNames
        Cbo_SerialPort.Items.AddRange（portNames）
    End Sub

    Private Sub Cbo_SerialPort_DropDown(sender As Object, e As EventArgs) Handles Cbo_SerialPort.DropDown
        Cbo_SerialPort.Items.Clear()
        Dim portNames As String() = Ports.SerialPort.GetPortNames
        Cbo_SerialPort.Items.AddRange（portNames）
    End Sub

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

        If IsNothing(testGrid) Then
        Else
            testGrid.SaveFile("E:\Mars_Edvt1_CodeTable.flx")
        End If

        If IsNothing(_Uart1Tack) Then
        Else
            If _Uart1Tack.IsAlive Then
                _Uart1Tack.Abort()
            End If
        End If
    End Sub

    Public testGrid As FlexCell.Grid

    Public Sub datalist()
        Dim dic As New Dictionary(Of String， String())

        testGrid = New FlexCell.Grid
        testGrid.OpenFile("E:\\Mars_Edvt1_CodeTable.flx")



    End Sub

    Public Function getAutSN(grid As FlexCell.Grid, colorode As String) As Dictionary(Of String, String)
        Dim dic As Dictionary(Of String, String)

        For rowid As Integer = 1 To grid.Rows - 1

            If grid.Cell(rowid, 6).Text.ToLower.Equals(colorode.ToLower) Then
                dic = New Dictionary(Of String, String)
                For colid As Integer = 1 To grid.Cols - 1
                    dic.Add(grid.Cell(0, colid).Text, grid.Cell(rowid, colid).Text)
                Next


            End If

        Next
        Return dic


        dic.Add(dic.Keys(3), dic.Values(3))
        dic.Add(dic.Keys(6), dic.Values(6))
        dic.Add(dic.Keys(7), dic.Values(7))
        dic.Add(dic.Keys(8), dic.Values(8))
        dic.Add(dic.Keys(9), dic.Values(9))
    End Function




    Private Sub btn_OK_Click(sender As Object, e As EventArgs) Handles btn_OK.Click


        'Dim jsonString As JsonPtr = AccessApi2("123", "uts_zongqing", "Barcode", "1",,)

        datalist()

    End Sub

    Public Function AccessApi2（pwd As String， dbName As String, theKey As String， Optional Barcode As String = "", Optional ColorBox_BarCode As String = "", Optional OutBoxCode As String = ""） As JsonPtr
        Dim jsonString As String = String.Empty

        Dim ptr As String = $"Pwd={pwd}&DBName={dbName}&Key={theKey}"
        If Not String.IsNullOrEmpty（Barcode） Then
            ptr = ptr & $"&Barcode={Barcode}"
        End If
        If Not String.IsNullOrEmpty（ColorBox_BarCode） Then
            ptr = ptr & $"&ColorBox_BarCode={ColorBox_BarCode}"
        End If

        If Not String.IsNullOrEmpty（OutBoxCode） Then
            ptr = ptr & $"&OutBoxCode={OutBoxCode}"
        End If
        '/http://uts-data.com/CommonApi/Combind_Sn_Info? Pwd%3D%26*$@%23235%26DBName%3Duts_zongqing%26Key%3DBarcode%26Barcode%3D1
        Try
            jsonString = PostData("http://uts-data.com/CommonApi/Combind_Sn_Info", ptr)
            'jsonString = PostData("http://47.119.147.104:90/OTApi/Login", $"Uid={user}&Pwd={pwd}&appid=1")
        Catch ex As Exception
            MsgBox($"{ex.Message}！盒码获取失败请联系管理员")
            Return Nothing
        End Try
        Console.WriteLine(jsonString)

        If jsonString = Nothing Then
            Return Nothing
        End If
        Dim login As JsonPtr = JsonConvert.DeserializeObject(Of JsonPtr)(jsonString)
        Return login

    End Function
    Public Shared Function PostData(ByVal url As String, ByVal data As String) As String

        ServicePointManager.Expect100Continue = False
        Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        '//Post请求方式
        request.Method = "post"

        '内容类型
        request.ContentType = "application/x-www-form-urlencoded"
        '将URL编码后的字符串转化为字节
        Dim encoding As New UTF8Encoding()
        Dim bys As Byte() = encoding.GetBytes(data)
        '设置请求的 ContentLength 
        request.ContentLength = bys.Length
        '获得请 求流
        Dim newStream As Stream = request.GetRequestStream()
        newStream.Write(bys, 0, bys.Length)
        newStream.Close()
        '获得响应流
        Dim sr As StreamReader = New StreamReader(request.GetResponse().GetResponseStream)
        Return sr.ReadToEnd
    End Function

    Private Sub DevCode_txt_PreviewKeyDown()
        Dim buff() As String
        Dim Customfield As New Dictionary(Of String， String)
        Dim ColorBox As String = ""
        Dim node As New RowNode
        Dim Dut_SN As String = ""
        Dim datenow As Date = Now

        If String.IsNullOrEmpty(txt_testnum.Text) Then
            MsgBox("未获取测量数据")
            Return
        End If
        If String.IsNullOrEmpty(TextBox2.Text) AndAlso String.IsNullOrEmpty(TextBox3.Text) Then
            MsgBox("未获取条码数据")
            Return
        End If

        Dim testresuli As String = CopmareTheSize()


        If Not testresuli.Equals("False") Then
            Dim jsonString As JsonPtr = AccessApi2("123", "uts_zongqing", "Barcode", "1",,)
            If IsNothing(jsonString) Then
                node.RowListIndex = 1
                node.Description = "获取DUT_SN失败！"
                TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
            End If

            TheTestResults("", TestResult.TestResultEnum.Pass, datenow, Nothing, Customfield)

        Else
            node.RowListIndex = 1
            node.Description = "称量数据校准失败！"
            TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
        End If

        'ColorBox = AccessApi("$%@132", buff(0).Trim, "uts_zongqing")
        '        EnclosureCode_txt.Text = ColorBox
        '        TextBox1.Text = buff(0).Trim
        '        'If GetTheColorBoxCode(DevCode_txt.Text， Dut_SN) Then

        '        If Not ColorBox.Equals("False") Then

        '            SetBarTendertoGrid（GrdPriview, DicBarTender）
        '            Customfield.Clear()
        '            Customfield.Add("MacCode", buff(1).Trim)
        '            Customfield.Add("SnCode", buff(0).Trim)
        '            Customfield.Add("ColorBoxCode", ColorBox)

        '            TheTestResults(buff(0).Trim, TestResult.TestResultEnum.Pass, datenow, Nothing, Customfield)
        '        Else
        '            node.RowListIndex = 1
        '            node.Description = "机身码绑定失败"

        '            TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
        '        End If

        '    Else

        '        node.RowListIndex = 1
        '        node.Description = "机身码错误"

        '        TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
        '    End If


    End Sub

    Private Sub TheTestResults(dutSn As String, ispass As TestResult.TestResultEnum, datenow As Date, Optional FailMsg As RowNode = Nothing, Optional Customfield As Dictionary(Of String， String) = Nothing)

        '重置信息
        _utsApp.TestResult.ResetTestResult()
        '产线索引
        _utsApp.TestResult.ProductionLineID = -1
        '测试开始时间
        _utsApp.TestResult.StartTime = Now
        _utsApp.TestResult.DUT_SN = dutSn
        _utsApp.TestResult.TestResult = ispass
        _utsApp.TestResult.UsedTime = Now - datenow
        If Not IsNothing(FailMsg) Then
            _utsApp.TestResult.FailSteps.Add(FailMsg)
        End If


        If Not IsNothing(Customfield) Then
            For indexptr As Integer = 0 To Customfield.Count - 1
                _utsApp.TestResult.AddCustomRecord($"{Customfield.Keys(indexptr)}", $"{Customfield.Values(indexptr)}")
            Next
        End If


        Try
            '提交测试记录,缺省参数默认为False，True则测试记录唯一,覆盖相同条码记录
            _utsApp.CommitTestResult(True)

            If ispass = TestResult.TestResultEnum.Pass Then
                TestStatusMonitor.TestStatus = StatusMonitor.TestStatusMonitor.TestStatusEnum.TestPass
            Else
                TestStatusMonitor.TestStatus = TestStatusMonitor.TestStatusEnum.TestFail
            End If
            TestStatusMonitor.TestStatus = TestStatusMonitor.TestStatusEnum.TestPass
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"写入称量数据失败：{ex.Message}")
            MsgBox($"写入称量数据失败：{ex.Message}")
            'LblResult.Text = "FAIL"
            'LblResult.ForeColor = Color.Red
            TestStatusMonitor.TestStatus = TestStatusMonitor.TestStatusEnum.TestFail
            Return
        End Try


    End Sub

    Public Function CopmareTheSize() As String
        Dim loadnum As Integer = 0
        Dim upnum As Integer = 0
        Dim connum As Integer = 0

        If Integer.TryParse(txt_LooadNum.Text, loadnum) AndAlso Integer.TryParse(txt_testnum.Text, connum) AndAlso Integer.TryParse(txt_UpNum.Text, upnum) Then
            If loadnum < connum AndAlso connum < upnum Then
                Return CStr(connum)
            Else
                Return "False"
            End If
        Else
            Return "False"
        End If


    End Function

    Private Sub TextBox2_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles TextBox2.PreviewKeyDown
        If e.KeyData = Keys.Enter Then



        End If
    End Sub

    Private Sub SplitContainer2_Panel2_Paint(sender As Object, e As PaintEventArgs) Handles SplitContainer2.Panel2.Paint

    End Sub
End Class

Public Class JsonPtr
    Public Data As List(Of jsonrusil)
    Public Message As String

End Class
Public Class jsonrusil
    Public ID As String
    Public Project As String
    Public importdateTime As Date
    Public updatetime As Date
    Public mars_colorBoxcode As String
    Public mars_outboxcode As String
    Public mars_MacCode As String
    Public mars_Unitweight As String
End Class



