Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Station.StationPackagePlan
Imports UTS_Core.UTSModule.Test.StatusMonitor
Public Class ZQ_Mars_P3_FrmStationPlan


    ' Implements IProcessFileChanged
    Implements IProcessStation
    Implements IProductionLine

    Private _utsApp As UtsAppForm
    Private _stationPlan As StationPackagePlan

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

        Show()
    End Sub

    Public Sub utsbctfilechanged（）
        'For Each observer As IProcessStation In _observerList
        '       observer.StationChanged()
        '   Next
    End Sub

    ''' <summary>
    ''' 站位变更代码
    ''' </summary>
    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)

        ApplicationLog.WriteInfoLog($"编辑页面站位变更完成。")
    End Sub

    ''' <summary>
    ''' 产线变化代码
    ''' </summary>
    Public Sub ProductionLineChanged() Implements IProductionLine.ProductionLineChanged
        ApplicationLog.WriteInfoLog($"编辑页面生产线变更中。")


        ApplicationLog.WriteInfoLog($"编辑页面生产线变更完成。")
    End Sub

    Private Sub FrmStationPlan_Load(sender As Object, e As EventArgs) Handles Me.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

    Private Sub TsBtnOpen_Click(sender As Object, e As EventArgs) Handles TsBtnOpen.Click
        Using xml As New OpenFileDialog
            xml.Filter = $"流程文件(*.xml)|*.xml"

            If xml.ShowDialog() = DialogResult.OK Then
                ApplicationLog.WriteInfoLog($"编辑页面执行流程正在加载{xml.FileName}")
                LoadTreeViewFormXml(xml.FileName)
                ApplicationLog.WriteInfoLog($"编辑页面执行流程加载完成。")
            End If
        End Using
    End Sub

    Private Sub TsBtnLoad_Click(sender As Object, e As EventArgs) Handles TsBtnLoad.Click
        If MsgBox("重载会将流程返回为上一次保存的流程状态,是否继续", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
            ApplicationLog.WriteInfoLog($"编辑页面执行流程重载中。")
            LoadTreeViewFormXml()
            ApplicationLog.WriteInfoLog($"编辑页面执行流程重载完成。")
        End If
    End Sub


    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 LoadTreeViewFormXml()
        Dim revStationPlanPath As String = $"{UtsPath.GetStationPacketTestPlanDirPath(_stationPlan.ParentPacket.Name)}\Main.xml"

        Try
            _stationPlan.LoadFile(revStationPlanPath)
            InitGrid(_stationPlan)

            If StationEditStatusMonitor.StationEditStatus <> StationEditStatusMonitor.StationEditStatusEnum.Saved Then
                StationEditStatusMonitor.StationEditStatus = StationEditStatusMonitor.StationEditStatusEnum.Saved
            End If
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"加载测试站流程发生错误,原因：{ex.Message}")
            MsgBox($"加载测试站流程发生错误,原因：{ex.Message}")
            _stationPlan.CreateStationPlan()
        End Try

    End Sub

    ''' <summary>
    ''' 读取XML,加载树状视图
    ''' </summary>
    Private Sub LoadTreeViewFormXml(revStationPlanPath As String)
        Try
            _stationPlan.LoadFile(revStationPlanPath)
            InitGrid(_stationPlan)

            If StationEditStatusMonitor.StationEditStatus <> StationEditStatusMonitor.StationEditStatusEnum.Saved Then
                StationEditStatusMonitor.StationEditStatus = StationEditStatusMonitor.StationEditStatusEnum.Saved
            End If
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"加载测试站流程发生错误,原因：{ex.Message}")
            MsgBox($"加载测试站流程发生错误,原因：{ex.Message}")
            _stationPlan.CreateStationPlan()
        End Try
    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 TsBtnSaveAs_Click(sender As Object, e As EventArgs) Handles TsBtnSaveAs.Click
        Using dlg As New SaveFileDialog
            dlg.Filter = "Excel 文件(*.xls)|*.xls|CSV 文件(*.csv)|*.csv|PDF 文件(*.pdf)|*.pdf"
            dlg.AddExtension = True
            If dlg.ShowDialog <> DialogResult.OK Then Return
            Cursor = Cursors.WaitCursor

            ApplicationLog.WriteInfoLog($"编辑页面执行流程导出中。")
            Try
                Select Case dlg.FilterIndex
                    Case 1
                        GrdStationPlan.ExportToExcel(dlg.FileName, True, True)
                    Case 2
                        GrdStationPlan.ExportToCSV(dlg.FileName, True, True)
                    Case 3
                        GrdStationPlan.ExportToPDF(dlg.FileName)
                End Select

                ApplicationLog.WriteInfoLog($"编辑页面执行流程导出完成。")
            Catch ex As Exception
                ApplicationLog.WriteErrorLog($"编辑页面执行流程导出失败,原因：{ex.Message}")
                MsgBox($"编辑页面执行流程导出失败,原因：{ex.Message}")
            End Try
            Cursor = Cursors.Arrow
        End Using
    End Sub

#Region "Package表格"
    Private Sub InitGrid(Optional stationplan As StationPackagePlan = Nothing)
        With GrdStationPlan
            .AutoRedraw = False

            .NewFile()
            .BorderStyle = FlexCell.BorderStyleEnum.None

            .Cols = ColNames.Max
            .Rows = RowItems.Max

            .ExtendLastCol = True
            .DisplayRowNumber = True

            .Cell(0, ColNames.Item).Text = "Item"
            .Cell(0, ColNames.Value).Text = "Value"

            .Column(ColNames.Item).Width = 200
            .Column(ColNames.Item).Locked = True

            .DefaultRowHeight = 20
            .DefaultFont = New Font("微软雅黑", 10)

            For i As Integer = 1 To RowItems.Max - 1
                .Cell(i, ColNames.Item).Text = [Enum].GetName(GetType(RowItems), i)
            Next

            '.Cell(RowItems.CheckSnTested, ColNames.Value).CellType = FlexCell.CellTypeEnum.ComboBox
            '.Cell(RowItems.CheckSnPackaged, ColNames.Value).CellType = FlexCell.CellTypeEnum.ComboBox
            '.Cell(RowItems.CheckSnMO, ColNames.Value).CellType = FlexCell.CellTypeEnum.ComboBox
            '.Cell(RowItems.MissingQuantity, ColNames.Value).CellType = FlexCell.CellTypeEnum.ComboBox
            '.Cell(RowItems.BarCodeType, ColNames.Value).CellType = FlexCell.CellTypeEnum.ComboBox

            .Cell(RowItems.AutoPrint, ColNames.Value).CellType = FlexCell.CellTypeEnum.CheckBox
            .Cell(RowItems.BoxMumEditKey, ColNames.Item).Text = "MaxNum"
            '.Cell(RowItems.ErrorSound, ColNames.Value).CellType = FlexCell.CellTypeEnum.Button
            '.Cell(RowItems.TemplateFile, ColNames.Value).CellType = FlexCell.CellTypeEnum.Button
            '.Cell(RowItems.CompanyLogo, ColNames.Value).CellType = FlexCell.CellTypeEnum.Button

            FillGrid(stationplan)

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

    Private Sub FillGrid(stationplan As StationPackagePlan)
        If stationplan Is Nothing Then Return

        With GrdStationPlan
            '.Cell(RowItems.CheckSnTested, ColNames.Value).Text = stationplan.CheckSnTested.ToString
            '.Cell(RowItems.CheckSnPackaged, ColNames.Value).Text = stationplan.CheckSnPackaged.ToString
            '.Cell(RowItems.CheckSnMO, ColNames.Value).Text = stationplan.CheckSnMO.ToString

            '.Cell(RowItems.PictureCount, ColNames.Value).Text = stationplan.PictureCount.ToString
            '.Cell(RowItems.UnlockKey, ColNames.Value).Text = stationplan.UnlockKey

            '.Cell(RowItems.BarCodeType, ColNames.Value).Text = stationplan.BarCodeType.ToString

            '.Cell(RowItems.MissingQuantity, ColNames.Value).Text = stationplan.MissingQuantity.ToString
            '.Cell(RowItems.MissingQuantityKey, ColNames.Value).Text = stationplan.MissingQuantityKey

            .Cell(RowItems.AutoPrint, ColNames.Value).Text = stationplan.AutoPrint.ToString

            '.Cell(RowItems.ErrorSound, ColNames.Value).Text = stationplan.ErrorSound
            '.Cell(RowItems.TemplateFile, ColNames.Value).Text = stationplan.TemplateFile

            .Cell(RowItems.BoxMumEditKey, ColNames.Value).Text = stationplan.BoxMumEditKey

            '.Cell(RowItems.CompanyLogo, ColNames.Value).Text = stationplan.CompanyLogo
            '.Cell(RowItems.CompanyName, ColNames.Value).Text = stationplan.CompanyName

            '.Cell(RowItems.BoxNumText, ColNames.Value).Text = stationplan.BoxNumText
            '.Cell(RowItems.BoxBarCode, ColNames.Value).Text = stationplan.BoxBarCode
        End With


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


    Private Sub UpdateGrid(stationplan As StationPackagePlan)
        If _stationPlan Is Nothing Then Return

        With GrdStationPlan
            'If [Enum].TryParse(.Cell(RowItems.CheckSnTested, ColNames.Value).Text, stationplan.CheckSnTested) = False Then
            '    MsgBox("更新CheckSnTested失败!")
            '    Return
            'End If
            'If [Enum].TryParse(.Cell(RowItems.CheckSnPackaged, ColNames.Value).Text, stationplan.CheckSnPackaged) = False Then
            '    MsgBox("更新CheckSnPackaged失败!")
            '    Return
            'End If
            'If [Enum].TryParse(.Cell(RowItems.CheckSnMO, ColNames.Value).Text, stationplan.CheckSnMO) = False Then
            '    MsgBox("更新CheckSnMO失败!")
            '    Return
            'End If

            'If [Enum].TryParse(.Cell(RowItems.BarCodeType, ColNames.Value).Text, stationplan.BarCodeType) = False Then
            '    MsgBox("更新BarCodeType失败!")
            '    Return
            'End If

            'If [Enum].TryParse(.Cell(RowItems.MissingQuantity, ColNames.Value).Text, stationplan.MissingQuantity) = False Then
            '    MsgBox("更新MissingQuantity失败!")
            '    Return
            'End If

            'stationplan.PictureCount = .Cell(RowItems.PictureCount, ColNames.Value).IntegerValue

            'stationplan.UnlockKey = .Cell(RowItems.UnlockKey, ColNames.Value).Text

            'stationplan.MissingQuantityKey = .Cell(RowItems.MissingQuantityKey, ColNames.Value).Text

            stationplan.AutoPrint = .Cell(RowItems.AutoPrint, ColNames.Value).BooleanValue

            'stationplan.ErrorSound = .Cell(RowItems.ErrorSound, ColNames.Value).Text
            ' stationplan.TemplateFile = .Cell(RowItems.TemplateFile, ColNames.Value).Text

            stationplan.BoxMumEditKey = .Cell(RowItems.BoxMumEditKey, ColNames.Value).Text

            'stationplan.CompanyLogo = .Cell(RowItems.CompanyLogo, ColNames.Value).Text
            'stationplan.CompanyName = .Cell(RowItems.CompanyName, ColNames.Value).Text

            'stationplan.BoxNumText = .Cell(RowItems.BoxNumText, ColNames.Value).Text
            'stationplan.BoxBarCode = .Cell(RowItems.BoxBarCode, ColNames.Value).Text
        End With
    End Sub


    Private Sub GrdStationPlan_ButtonClick(Sender As Object, e As FlexCell.Grid.ButtonClickEventArgs) Handles GrdStationPlan.ButtonClick
        Select Case e.Row
            'Case RowItems.ErrorSound
            '    DlgOpenFile.Filter = "图像资源 (*.jpg;*.png;*.gif;*.ico)|*.jpg;*.png;*.gif;*.ico"
            'Case RowItems.TemplateFile
            '    DlgOpenFile.Filter = "模板资源 (*.btw)|*.btw"
            '    'Case RowItems.CompanyLogo
            '    DlgOpenFile.Filter = "图像资源 (*.jpg;*.png;*.gif;*.ico)|*.jpg;*.png;*.gif;*.ico"
        End Select

        DlgOpenFile.CheckFileExists = True
        DlgOpenFile.CheckPathExists = True
        If DlgOpenFile.ShowDialog() <> DialogResult.OK Then Return

        Dim fileName As String = $"{DlgOpenFile.SafeFileName}"
        Dim fileDir As String = UtsPath.GetStationPacketResourceDirPath(_stationPlan.ParentPacket.Name)
        Dim fliePath As String = $"{fileDir}\{fileName}"

        GrdStationPlan.Cell(e.Row, ColNames.Value).Text = fileName

        '导入文件
        Try
            IO.File.Copy(DlgOpenFile.FileName, fliePath, True)
        Catch ex As Exception
            MsgBox($"导入资源文件失败，{ex.Message}")
        End Try
    End Sub

    Private Sub GrdStationPlan_ComboDropDown(Sender As Object, e As FlexCell.Grid.ComboDropDownEventArgs) Handles GrdStationPlan.ComboDropDown
        GrdStationPlan.ComboBox(0).Items.Clear()
        Select Case e.Row
            'Case RowItems.CheckSnTested
            '    GrdStationPlan.ComboBox(0).Items.AddRange([Enum].GetNames(GetType(CheckStatus)))
            'Case RowItems.CheckSnPackaged
            '    GrdStationPlan.ComboBox(0).Items.AddRange([Enum].GetNames(GetType(CheckStatus)))
            'Case RowItems.CheckSnMO
            '    GrdStationPlan.ComboBox(0).Items.AddRange([Enum].GetNames(GetType(CheckStatus)))
            'Case RowItems.MissingQuantity
            '    GrdStationPlan.ComboBox(0).Items.AddRange([Enum].GetNames(GetType(MissCountStatus)))
            'Case RowItems.BarCodeType
            '    GrdStationPlan.ComboBox(0).Items.AddRange([Enum].GetNames(GetType(BarcodeTypes)))
        End Select
    End Sub

    Private Sub GrdStationPlan_CellChange(Sender As Object, e As FlexCell.Grid.CellChangeEventArgs) Handles GrdStationPlan.CellChange
        StationEditStatusMonitor.StationEditStatus = StationEditStatusMonitor.StationEditStatusEnum.Changed
    End Sub

    Enum ColNames
        SN
        Item
        Value
        Max
    End Enum



    Enum RowItems
        ''' <summary>固定行</summary>
        <System.ComponentModel.Description("固定行")>
        SN

        '''' <summary>校验条码未测试后处理方式</summary>
        '<System.ComponentModel.Description("校验条码未测试后处理方式")>
        'CheckSnTested

        '''' <summary>校验条码已参与包装后处理方式</summary>
        '<System.ComponentModel.Description("校验条码已参与包装后处理方式")>
        'CheckSnPackaged

        '''' <summary>校验条码不属于指定MO后处理方式</summary>
        '<System.ComponentModel.Description("校验条码不属于指定MO后处理方式")>
        'CheckSnMO

        '''' <summary>拍摄保存图像的数量</summary>
        '<System.ComponentModel.Description("拍摄保存图像的数量")>
        'PictureCount

        '''' <summary>解锁密码</summary>
        '<System.ComponentModel.Description("解锁密码")>
        'UnlockKey

        '''' <summary>条码类型</summary>
        '<System.ComponentModel.Description("条码类型")>
        'BarCodeType

        '''' <summary>缺失条码数量后的处理方式</summary>
        '<System.ComponentModel.Description("缺失条码数量后的处理方式")>
        'MissingQuantity

        '''' <summary>缺失条码数量后的解锁密码</summary>
        '<System.ComponentModel.Description("缺失条码数量后的解锁密码")>
        'MissingQuantityKey

        ''' <summary>是否自动打印</summary>
        <System.ComponentModel.Description("是否自动录入")>
        AutoPrint

        '''' <summary>发生错误后报警文件</summary>
        '<System.ComponentModel.Description("发生错误后报警文件")>
        'ErrorSound

        '''' <summary>模板文件名</summary>
        '<System.ComponentModel.Description("模板文件名")>
        'TemplateFile

        ''' <summary>箱号编辑密码</summary>
        <System.ComponentModel.Description("箱号编辑密码")>
        BoxMumEditKey

        '''' <summary>公司Logo文件</summary>
        '<System.ComponentModel.Description("公司Logo文件")>
        'CompanyLogo

        '''' <summary>公司名称</summary>
        '<System.ComponentModel.Description("公司名称")>
        'CompanyName

        '''' <summary>箱号规则</summary>
        '<System.ComponentModel.Description("箱号规则")>
        'BoxNumText

        '''' <summary>箱号条码</summary>
        '<System.ComponentModel.Description("箱号条码")>
        'BoxBarCode

        Max
    End Enum

    Private Sub GrdStationPlan_SelChange(Sender As Object, e As FlexCell.Grid.SelChangeEventArgs) Handles GrdStationPlan.SelChange
        If e.FirstRow <= RowItems.SN OrElse e.FirstRow > GrdStationPlan.Rows - 1 Then Return

        Dim row As Integer = e.FirstRow
        Dim a As RowItems
        If [Enum].TryParse(row.ToString, a) Then
            LblDesc.Text = $"Row:{row}{vbCrLf}Desc:{GetEnumDescription(a)}"
        Else
            LblDesc.Text = $"Row:{row}{vbCrLf}Desc:无说明"
        End If
    End Sub

    Public Function GetEnumDescription(enumValue As RowItems) As String
        Dim str As String = enumValue.ToString()
        Dim field As System.Reflection.FieldInfo = enumValue.GetType().GetField(str)
        Dim objs() As Object = field.GetCustomAttributes(GetType(System.ComponentModel.DescriptionAttribute), False)
        If objs Is Nothing OrElse objs.Length = 0 Then Return str
        Dim da As System.ComponentModel.DescriptionAttribute = CType(objs(0), ComponentModel.DescriptionAttribute)
        Return da.Description
    End Function
#End Region

End Class
