Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Test.StatusMonitor

Public Class ZQ_Phobos_T1_FrmStationPlan


#Region "框架部分 要放在最前段"
    Implements IProcessStation

    Private _utsApp As UtsAppForm
    Private _stationPlan As StationPackagePlan
    Public Sub Station_Changed() Implements IProcessStation.StationChanged
        ApplicationLog.WriteInfoLog($"编辑页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}!")

        Try
            _stationPlan = CType(_utsApp.ProcessStation.Packet.StationPlan, StationPackagePlan)
        Catch ex As Exception
            MsgBox($"加载项目流程失败,{ex.Message}")
        End Try

        'InitGrid(_stationPlan)
        FileToLoadTable(_stationPlan.TemplateFile, _stationPlan.CompanyLogo)
        ApplicationLog.WriteInfoLog($"编辑页面站位变更完成。")


    End Sub

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

        Show()
    End Sub

#End Region


#Region "界面控件初始化"

    Private Sub ZQ_Phobos_T1_FrmStationPlan_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ApplicationLog.WriteInfoLog($"编辑页面加载中。")

        '初始化UTS窗体信息,失败则关闭窗体
        If InitializeUtsApp() = False Then Return

        '初始化窗体页面
        InitializeForm()

        ApplicationLog.WriteInfoLog($"编辑页面加载完成。")

    End Sub
    Private Function InitializeUtsApp() As Boolean
        _utsApp = UtsAppForm.CreateSingleton()
        _utsApp.AddStatisticsObserver(Me)

        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


    Private Sub InitializeForm()
        InitGrid(_stationPlan)
    End Sub
#Region "Package表格"


    Public Sub FileToLoadTable(mainfilename As String, deputyfilename As String)

        If IO.File.Exists(mainfilename) Then
            GrdStationPlan.OpenFile(_stationPlan.TemplateFile)
        End If

        If IO.File.Exists(deputyfilename) Then
            Grid1.OpenFile(_stationPlan.TemplateFile)
        End If

    End Sub


    Private Sub InitGrid(Optional stationplan As StationPackagePlan = Nothing)


        GrdStationPlan = UpdateStepTestRecord(New FlexCell.Grid)
        Grid1 = UpdateStepTestRecord(New FlexCell.Grid)

    End Sub
#Region "主表初始化装载"
    Enum ColNames
        No
        Content
        DataSource
        SendData
        PassResult
        RetryCount
        RetryInterval
        ReadInterval
        OperatingMode
        Lower
        Upper
        TestVal
        TestResult
        IsRecord
        RecordName
        Max
    End Enum
    Public Function UpdateStepTestRecord(theGrid As FlexCell.Grid) As FlexCell.Grid
        With theGrid
            .AutoRedraw = False
            '.AutoSize = True
            .Cols = ColNames.Max
            .Rows = 1
            .ExtendLastCol = True   '最后一列自动扩充
            .DisplayRowNumber = True    '首列显示数字
            .DefaultRowHeight = 20
            .DefaultFont = New Font("微软雅黑", 10)
            For col As Integer = 0 To ColNames.Max - 1
                .Cell(0, col).Text = [Enum].GetName(GetType(ColNames), col) '设置列名
                .Column(col).CellType = FlexCell.CellTypeEnum.TextBox '设置列型

                .Column(col).Width = 140 '设置列宽

                .Column(col).Alignment = FlexCell.AlignmentEnum.CenterCenter  '设置对齐位置
            Next
            .ForeColorComment = Color.Blue


            .BackColorBkg = Color.DimGray
            .AutoRedraw = True
            .Refresh()
            .Locked = True
        End With

        DefaultData(theGrid)

        Return theGrid

    End Function

    Public Sub DefaultData(ByRef theGrid As FlexCell.Grid)

        Dim SendDatalist As New List(Of List(Of String））
        UartSendDataList(SendDatalist， "确认测试板连接", "uts", "*IDN?", "uts-Phobos-rev01", "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "设置输出限流", "uts", "SET_PPS_CURR:400", "SET_PPS_CURR:400:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "设置输出电压", "uts", "SET_PPS_VOLT:2000", "SET_PPS_VOLT:2000:TRUE"， "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "打开输出电压", "uts", "SET_PPS_OUTP:ON", "SET_PPS_OUTP:ON:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "清除峰值电流 - ch1", "uts", "CLR_PPS_CURR_PEAK:1", "CLR_PPS_CURR_PEAK:1:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "清除峰值电流 - ch2", "uts", "CLR_PPS_CURR_PEAK:2", "CLR_PPS_CURR_PEAK:2:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "清除峰值电流 - ch3", "uts", "CLR_PPS_CURR_PEAK:3", "CLR_PPS_CURR_PEAK:3:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")
        UartSendDataList(SendDatalist， "清除峰值电流 - ch4", "uts", "CLR_PPS_CURR_PEAK:4", "CLR_PPS_CURR_PEAK:4:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")

        UartSendDataList(SendDatalist， "读取平均电流(轮询直到勾选的属性测试结束)", "uts", "RUN", "10", "max", "100", "300", "split", "", "", "", "", "", "")

        UartSendDataList(SendDatalist， "发送关闭电源命令", "uts", "SET_PPS_OUTP:OFF"， "SET_PPS_OUTP:OFF:TRUE", "3", "100", "300", "comparison", "", "", "", "", "", "")

        Grid5AddRow(theGrid, SendDatalist)

    End Sub

    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(ByRef theGrid As FlexCell.Grid, 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(theGrid, Datalist)
        Next

    End Sub

    Public Sub AddRowToTable（ByRef 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 "副表初始化装载"

    Enum ColNames2
        No
        Content
        DataSource
        SendData
        PassResult
        RetryCount
        RetryInterval
        ReadInterval
        OperatingMode
        Lower
        Upper
        TestVal
        TestResult
        IsRecord
        RecordName
        Max
    End Enum
    Public Function UpdateStepTestRecord1(Userkeyval_grid As FlexCell.Grid) As FlexCell.Grid
        With Userkeyval_grid
            .AutoRedraw = False
            '.AutoSize = True
            .Cols = ColNames2.Max
            .Rows = 1
            .ExtendLastCol = True   '最后一列自动扩充
            .DisplayRowNumber = True    '首列显示数字

            For col As Integer = 0 To ColNames2.Max - 1
                .Cell(0, col).Text = [Enum].GetName(GetType(ColNames2), col) '设置列名
                .Column(col).CellType = FlexCell.CellTypeEnum.TextBox '设置列型
                If col = ColNames2.Content OrElse col = ColNames2.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
        DefaultData2(Userkeyval_grid)
        Return Userkeyval_grid
    End Function

    Public Sub DefaultData2(ByRef Userkeyval_grid As FlexCell.Grid)

        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", "", "", "", "", "", "")
        Grid5AddRow2(Userkeyval_grid, SendDatalist)
    End Sub

    Public Sub Grid5AddRow2(ByRef Userkeyval_grid As FlexCell.Grid, 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)


            AddRowToTable2(Userkeyval_grid, Datalist)
        Next

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

#Region "界面控件事件"
    Private Sub TsBtnSave_Click(sender As Object, e As EventArgs) Handles TsBtnSave.Click
        ApplicationLog.WriteInfoLog($"编辑页面执行流程保存中。")
        UpdateGrid(_stationPlan)

        ExportTreeViewToXml()
        ApplicationLog.WriteInfoLog($"编辑页面执行流程保存完成。")
    End Sub
    ''' <summary>
    ''' 将树状视图导出为Xml
    ''' </summary>
    Private Sub ExportTreeViewToXml()
        '保存至项目文件
        Dim revStationPlanPath As String = $"{UtsPath.GetStationPacketTestPlanDirPath(_stationPlan.ParentPacket.Name)}\Main.xml"
        _stationPlan.SaveFile(revStationPlanPath)

        '备份至临时文件
        Dim tempPath As String = $"{UtsPath.StationDesignDirPath()}\Main.xml"
        _stationPlan.SaveFile(tempPath)

        If StationEditStatusMonitor.StationEditStatus = StationEditStatusMonitor.StationEditStatusEnum.Changed Then
            StationEditStatusMonitor.StationEditStatus = StationEditStatusMonitor.StationEditStatusEnum.Saved
        End If
    End Sub

    Private Sub UpdateGrid(stationplan As StationPackagePlan)
        Dim revStationPlanPath As String = UtsPath.GetStationPacketTestPlanDirPath(_stationPlan.ParentPacket.Name)
        _stationPlan.TemplateFile = revStationPlanPath & "\Maintest.flx"
        _stationPlan.CompanyLogo = revStationPlanPath & "\Deputytest.flx"

        GrdStationPlan.SaveFile(revStationPlanPath & "\Maintest.flx")
        Grid1.SaveFile(revStationPlanPath & "\Deputytest.flx")
        GrdStationPlan.SaveFile(UtsPath.StationDesignDirPath() & "\Maintest.flx")
        Grid1.SaveFile(UtsPath.StationDesignDirPath() & "\Deputytest.flx")

    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        GrdStationPlan.Locked = Not GrdStationPlan.Locked
        If GrdStationPlan.Locked Then
            ToolStripButton1.Text = "编辑主流程"
        Else
            ToolStripButton1.Text = "锁定主流程"
        End If
    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        Grid1.Locked = Not Grid1.Locked
        If Grid1.Locked Then
            ToolStripButton2.Text = "编辑主流程"
        Else
            ToolStripButton2.Text = "锁定主流程"
        End If
    End Sub

#End Region


#End Region

#End Region



End Class