Imports System.IO
Imports System.Net
Imports System.Text
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_P3_FrmStationTest
    Implements IProcessStation
    Private _utsApp As UtsAppForm
    Private _stationPlan As StationPackagePlan
    Private NodePtr As TreeNode
    '最大装载数量 赋值需要减一  
    Private Max_Loading As Integer = 10

    Private PrintfNum As Integer = 0
    Private Printfcnt As Integer = 0
#Region "UTS框架"
    ''' <summary>
    ''' 站位改变事件
    ''' </summary>
    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)
        Integer.TryParse(_stationPlan.BoxMumEditKey, Max_Loading)
        Max_Loading = Max_Loading - 1
        '清除表格数据
        'InitBarcodeGrid()

        ApplicationLog.WriteInfoLog($"测试页面站位变更完成!")
    End Sub
    ''' <summary>
    ''' 初始化App
    ''' </summary>
    ''' <returns></returns>
    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
    ''' <summary>
    ''' 加载窗体
    ''' </summary>
    ''' <param name="parentControl"></param>
    Public Sub ShowForm(parentControl As Control)
        FormBorderStyle = FormBorderStyle.None
        TopLevel = False
        Dock = DockStyle.Fill
        Parent = parentControl

        Show()

    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 = datenow
        _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

#End Region



#Region "Web 数据接口"


    Public Function AccessApi2(uart As String, dbName As String, theKey As String， Optional dic As Dictionary(Of String, String) = Nothing) As JsonPtr

        Dim jsonString As String = String.Empty

        Dim ptr As String = $"Pwd=actop00803&DBName={dbName}&Key={theKey}"
        If Not IsNothing（dic） Then
            ptr = ptr & $"&JsonData={JsonConvert.SerializeObject(dic)}"
        End If
        '/http://uts-data.com/CommonApi/Combind_Sn_Info? Pwd%3D%26*$@%23235%26DBName%3Duts_zongqing%26Key%3DBarcode%26Barcode%3D1
        Try
            jsonString = PostData(uart, ptr)
            Console.WriteLine(jsonString)

            If jsonString = Nothing Then
                Return Nothing
            End If
            Dim login As JsonPtr = JsonConvert.DeserializeObject(Of JsonPtr)(jsonString)
            If login.Message.Contains（"成功"） Then
                Return login
            Else
                Return Nothing
            End If

        Catch ex As Exception
            MsgBox($"{ex.Message}！盒码获取失败请联系管理员")
            Return Nothing
        End Try

    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

#End Region
#Region "UIEven"
    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
        RichTextBox1.SelectionStart = RichTextBox1.TextLength
        RichTextBox1.ScrollToCaret()

    End Sub
    Delegate Sub IPSetRichTextBox1Text(TextBox1 As RichTextBox, text As String， txtcolor As Color)
    Private Sub SetRichTextBox1Text(TextBox1 As RichTextBox, text As String， txtcolor As Color)
        If InvokeRequired = True Then
            Dim dev As New IPSetRichTextBox1Text(AddressOf SetRichTextBox1Text)
            Me.Invoke(dev, New Object() {TextBox1, text, txtcolor})
        Else
            With TextBox1
                .SuspendLayout()


                .SelectionColor = txtcolor

                .AppendText(text & vbCrLf)
                .ResumeLayout(False)
            End With
        End If


    End Sub
    Public Sub initTreeViewEx1()
        TreeViewEx1.Nodes.Clear()
        TreeViewEx1.ItemHeight = 21
        TreeViewEx1.CheckBoxes = False
        TreeViewEx1.HideSelection = True
        TreeViewEx1.SelectedImageKey = TreeViewEx1.ImageKey
    End Sub
    Private Sub TextBox1_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles TextBox1.PreviewKeyDown
        If e.KeyData = Keys.Enter Then
            If String.IsNullOrWhiteSpace(TextBox1.Text) Then
                MsgBox("箱号为空，请输入箱号！")
                Return
            End If

            Dim jsonclass As JsonPtr = AccessApi2("http://uts-data.com/CommonApi/Get_Sn_Info"， "uts_zongqing", TextBox1.Text.Trim)
            If IsNothing(jsonclass) Then
                NodePtr = New TreeNode
                NodePtr.Text = "箱体码:" & TextBox1.Text.Trim
                NodePtr.Tag = Now
                TextBox2.Focus()
                TextBox2.SelectAll()
                TextBox1.ReadOnly = True

                TreeViewEx1.Nodes.Clear()
                TreeViewEx1.Nodes.Add(NodePtr)
                TreeViewEx1.Nodes(0).Expand()
            Else
                MsgBox("该箱号已使用，请更换箱号！")
                TextBox1.Focus()
                TextBox1.SelectAll()
                Return
            End If


        End If
    End Sub

    Private Sub TextBox2_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles TextBox2.PreviewKeyDown
        If e.KeyData = Keys.Enter Then
            If String.IsNullOrWhiteSpace(TextBox2.Text) Then
                MsgBox("彩盒码为空，请输入箱号！")
                TextBox2.Focus()
                TextBox2.SelectAll()
                Return
            End If
            If IsNothing(NodePtr) Then
                MsgBox("箱号为空，请输入箱号再进行录入")
                TextBox1.Focus()
                TextBox1.SelectAll()
                TextBox1.ReadOnly = False
                Return
            End If

            If NodePtr.Nodes.Count < Max_Loading Then
                Dim jsonclass As JsonPtr = AccessApi2("http://uts-data.com/CommonApi/Get_Sn_Info", "uts_zongqing", TextBox2.Text.Trim)
                If IsNothing(jsonclass) Then
                    MsgBox("未查询到彩盒码关联数据，请核实彩盒码！")
                    TextBox2.Focus()
                    TextBox2.SelectAll()
                    Return
                End If

                If DuplicateChecking(NodePtr, TextBox2.Text.Trim) Then

                    Dim node As New TreeNode
                    node.Text = "彩盒码:" & TextBox2.Text.Trim
                    node.Tag = jsonclass

                    NodePtr.Nodes.Add(node)
                    NodePtr.ExpandAll()
                    TextBox2.Focus()
                    TextBox2.SelectAll()
                    If _stationPlan.AutoPrint Then
                        If NodePtr.Nodes.Count = Max_Loading Then
                            TextBox1.Focus()
                            TextBox1.SelectAll()
                            TextBox1.ReadOnly = False
                            Button2.PerformClick()
                            Return
                        End If
                    End If



                Else
                    MsgBox("彩盒码已记录，请输入箱号！")
                    TextBox2.Focus()
                    TextBox2.SelectAll()
                    Return
                End If

            Else
                MsgBox($"装箱数已满，最大装载量为:{Max_Loading}")
                TextBox1.Focus()
                TextBox1.SelectAll()
                TextBox1.ReadOnly = False
                Return
            End If


        End If

    End Sub


    Public Function DuplicateChecking(node As TreeNode， txt As String) As Boolean
        For Each index As TreeNode In node.Nodes
            If index.Text.Equals(txt.Trim) Then
                Return False
            End If
        Next
        Return True
    End Function

    Private Sub ZQ_Mars_P3_FrmStationTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ApplicationLog.WriteInfoLog($"测试页面加载中。")
        If InitializeUtsApp() = False Then Return
        initTreeViewEx1()
    End Sub


    Private Sub TreeViewEx1_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TreeViewEx1.NodeMouseClick
        If e.Button <> MouseButtons.Left Then Return
        Dim node As TreeNode = TreeViewEx1.SelectedNode

        If node Is Nothing Then Return
        If node.Level = 0 Then
            txt_inputnum.Text = node.Nodes.Count.ToString
            txt_MacCode.Text = "------"
            txt_colorbox.Text = "------"
            txt_labstring.Text = "------"
            txt_SnCode.Text = "------"
            txt_unitweight.Text = "------"
            Return
        End If

        Dim jsonclass As JsonPtr = CType(node.Tag, JsonPtr)
        txt_MacCode.Text = jsonclass.Data.Mars_MacCodeP
        txt_colorbox.Text = jsonclass.Data.Mars_ColorBox_BarCode
        txt_inputnum.Text = "1"
        txt_labstring.Text = jsonclass.Data.Barcode & "/" & jsonclass.Data.Mars_MacCodeP
        txt_SnCode.Text = jsonclass.Data.Barcode
        txt_unitweight.Text = jsonclass.Data.Mars_UnitWeigth

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        If IsNothing(TreeViewEx1) Then Return
        Dim node As TreeNode = TreeViewEx1.SelectedNode
        If TreeViewEx1.Nodes(0).Equals（node.Text） Then
            If MsgBox("该节点为箱体节点，删除将丢失已存在该箱体的记录。是否删除？", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                TreeViewEx1.Nodes.RemoveAt(0)
                TreeViewEx1.Nodes.Clear()
                TextBox1.Text = ""
                TextBox1.Focus()
                TextBox1.SelectAll()
                TextBox1.ReadOnly = False
            End If
        Else
            TreeViewEx1.Nodes(0).Nodes.Remove(node)
        End If

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If TreeViewEx1.Nodes.Count = 0 Then
            MsgBox("未添加箱体码信息，请先添加箱体码信息再进行数据录入！")
            Return
        ElseIf TreeViewEx1.Nodes.Count = 1 Then
            If TreeViewEx1.Nodes(0).Nodes.Count < Max_Loading Then
                If MsgBox("该箱体未满。是否继续装载？", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                    Return
                End If
            End If
            InputBoxInformation(TreeViewEx1)
        Else
            MsgBox("箱体码信息异常，请联系开发者")
        End If


    End Sub

    Public Sub InputBoxInformation(TreeView As UTS_Core.UTSModule.Station.TreeViewEx)
        Dim Customfield As New Dictionary(Of String， String)
        Dim headnode As TreeNode = TreeView.Nodes(0)
        Dim jsonclass As JsonPtr
        Dim ricttxt As String = $"{Now:yyyy:HH:mm:ss:fff}箱体号：{headnode.Text} {vbCrLf }"
        Dim datenow As Date = CDate(headnode.Tag)
        Dim strbuff() As String = headnode.Text.Split(CChar(":"))
        For i As Integer = 0 To headnode.Nodes.Count - 1
            Dim index As TreeNode = headnode.Nodes(i)
            jsonclass = CType(index.Tag, JsonPtr)
            Customfield.Clear()
            Customfield.Add("Mars_OutBoxCode", strbuff(1))

            Customfield.Add("MacCode", jsonclass.Data.Mars_MacCodeP)
            Customfield.Add("SnCode", jsonclass.Data.Barcode)
            Customfield.Add("ColorBoxCode", jsonclass.Data.Mars_ColorBox_BarCode)
            Customfield.Add("label_string", jsonclass.Data.Barcode & "/" & jsonclass.Data.Mars_MacCodeP)
            Customfield.Add("Mars_UnitWeigth", jsonclass.Data.Mars_UnitWeigth)

            If Not SetMars_OutBoxCode(strbuff(1), jsonclass.Data.Mars_ColorBox_BarCode) Then
                MsgBox($"第{i}个彩盒码录入数据库失败,请联系开发者。彩盒码：{jsonclass.Data.Mars_ColorBox_BarCode}")
            End If
            TheTestResults(jsonclass.Data.Barcode, TestResult.TestResultEnum.Pass, datenow, Nothing, Customfield)

            ricttxt = $"{ricttxt}{i}:{index.Text }{vbCrLf }"
        Next
        ricttxt = $"{ricttxt}-----------------{vbCrLf}"
        SetRichTextBox1Text(RichTextBox1, ricttxt, Color.Blue)
        'TestBoxnum = TestBoxnum + 1
        'Label3.Text = TestBoxnum.ToString & "箱"


        PrintfNum = PrintfNum + 1
        'Label7.Text = PrintfNum.ToString & "个"
        lab_test_num.Text = PrintfNum.ToString & "箱"
        Printfcnt = My.Settings.P1_cnt + PrintfNum
        lab_Test_cnt.Text = Printfcnt.ToString & "箱"
        My.Settings.Save()
    End Sub

    Public Function SetMars_OutBoxCode(BoxCode As String, colorcode As String) As Boolean
        Dim dic As New Dictionary(Of String, String）
        dic.Add("Mars_OutBoxCode"， BoxCode) '称重值
        dic.Add("Mars_ColorBox_BarCode"， colorcode)
        Dim Writesql As JsonPtr = AccessApi2("http://uts-data.com/CommonApi/Combind_Sn_Info", "uts_zongqing", "Mars_ColorBox_BarCode"， dic)
        If IsNothing(Writesql) Then
            Return False
        End If
        Return True
    End Function


#End Region




End Class