Imports Excel = Microsoft.Office.Interop.Excel
Imports System.IO

Public Class frmNachverfolgung
    Private Shared _Instance As frmNachverfolgung = Nothing
    Public Shared Function Instance() As frmNachverfolgung
        If _Instance Is Nothing OrElse _Instance.IsDisposed = True Then
            _Instance = New frmNachverfolgung
        End If
        _Instance.BringToFront()
        Return _Instance
    End Function
    Private Sub chkbDatumfilter_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkbDatumfilter.CheckedChanged
        If Me.chkbDatumfilter.Checked Then
            dtpVerfolgung_bis.Enabled = True
            dtpVerfolgung_von.Enabled = True
        Else
            dtpVerfolgung_bis.Enabled = False
            dtpVerfolgung_von.Enabled = False
        End If
    End Sub
    Sub Save_GridLayout_GeraeteVerfolgung()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridControlGeraeteVerfolgung")
        GridControlGeraeteVerfolgung.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Load_GridLayout_GeraeteVerfolgung()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridControlGeraeteVerfolgung")
            If File.Exists(XMLPath) Then
                GridControlGeraeteVerfolgung.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewGeraeteVerfolgung.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewGeraeteVerfolgung.ClearSelection()
                GridViewGeraeteVerfolgung.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Save_GridLayout_Geraete()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridControlGeraetVerfolgung")
        GridControlGeraet.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Load_GridLayout_Geraete()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridControlGeraetVerfolgung")
            If File.Exists(XMLPath) Then
                GridControlGeraet.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewGeraet.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewGeraet.ClearSelection()
                GridViewGeraet.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Save_GridLayout_SupplyVerfolgung()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridControlSupplyVerfolgung")
        GridControlSupplyverfolgung.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Load_GridLayout_SupplyVerfolgung()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridControlSupplyVerfolgung")
            If File.Exists(XMLPath) Then
                GridControlSupplyverfolgung.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewSupplyverfolgung.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewSupplyverfolgung.ClearSelection()
                GridViewSupplyverfolgung.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Private Sub frmNachverfolgung_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.verf_id = 0
        Save_GridLayout_Geraete()
        Save_GridLayout_GeraeteVerfolgung()
        Save_GridLayout_SupplyVerfolgung()
    End Sub
    Private Sub frmNachverfolgung_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Me.tscmbaktiv.SelectedIndex = 0
        Me.TBGERAETTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
        Me.VWGERAETE_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
        Me.VWSUPPLY_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
        Load_GridLayout_Geraete()
        Load_GridLayout_GeraeteVerfolgung()
        Load_GridLayout_SupplyVerfolgung()
        If My.Settings.verf_id <> 0 Then
            Refresh_Geraete(My.Settings.verf_id, True)
        Else
            Refresh_Geraete(0, True)
        End If

    End Sub

    Private Sub tsbGeraeteRefresh_Click(sender As System.Object, e As System.EventArgs) Handles tsbGeraeteRefresh.Click
        Refresh_Geraete(0)
    End Sub
    Private Sub Refresh_Geraete(guid As Integer, Optional start As Boolean = False)
        If start = True Then
            If guid <> 0 Then
                Try
                    Me.Cursor = Cursors.WaitCursor
                    Me.TBGERAETTableAdapter.FillByGUID(Me.MyDataset.TBGERAET, guid)
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Gerätedaten für GUID: " & guid)
                End Try
            Else
                Load_Geraete()
            End If
        Else
            Load_Geraete()
        End If
        Me.Cursor = Cursors.Default
    End Sub
    Sub Load_Geraete()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim aktiv As Boolean
            If Me.tscmbaktiv.SelectedIndex = 0 Then
                aktiv = 1
            Else
                aktiv = 0
            End If
            Me.TBGERAETTableAdapter.Fill(Me.MyDataset.TBGERAET, aktiv, My.Settings.Mandant_ID)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Gerätedaten:")
        End Try
    End Sub

    Private Sub ToolStripButton5_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton5.Click
        Refresh_Geraeteverfolgung()
    End Sub
    Sub Refresh_Geraeteverfolgung()
        Cursor = Cursors.WaitCursor
        'Try

        Dim Geraet_id = GridViewGeraet.GetFocusedRowCellValue(GridViewGeraet.Columns("GUID"))
        If chkbDatumfilter.Checked Then
            Me.VWGERAETE_VERFOLGUNGTableAdapter.FillByDate(Me.MyDataset.VWGERAETE_VERFOLGUNG, Geraet_id, dtpVerfolgung_von.Text, dtpVerfolgung_bis.Text)
        Else
            Me.VWGERAETE_VERFOLGUNGTableAdapter.Fill(Me.MyDataset.VWGERAETE_VERFOLGUNG, Geraet_id)
        End If
        GridViewGeraeteVerfolgung.ViewCaption = "Geräteverfolgung für Geräte-ID: " & Geraet_id
        'Catch ex As System.Exception
        'MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Nachverfolgung zu Gerät:")
        'End Try
        Cursor = Cursors.Default
    End Sub
    Private Sub ToolStripButton10_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton10.Click
        Refresh_Supplyverfolgung()
    End Sub
    Sub Refresh_Supplyverfolgung()
        Cursor = Cursors.WaitCursor
        Try
            Dim Geraet_id = GridViewGeraet.GetFocusedRowCellValue(GridViewGeraet.Columns("GUID"))
            If chkbDatumfilter.Checked Then
                Me.VWSUPPLY_VERFOLGUNGTableAdapter.FillByDate(Me.MyDataset.VWSUPPLY_VERFOLGUNG, Geraet_id, dtpVerfolgung_von.Text, dtpVerfolgung_bis.Text)
            Else
                Me.VWSUPPLY_VERFOLGUNGTableAdapter.Fill(Me.MyDataset.VWSUPPLY_VERFOLGUNG, Geraet_id)
            End If
            ' DGVVWSUPPLY_VERFOLGUNG.Caption = "Supplyverfolgung für Geräte-ID: " & GERAET_ID
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Supplyverfolgung zu Gerät:")
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        Select Case TabControl1.SelectedIndex
            Case 1
                Refresh_Supplyverfolgung()
        End Select
    End Sub

    Private Sub ToolStripButton11_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton11.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel (*.xls)|*.xls|Excel (*.xlsx)|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            If saveFileDialog1.FileName.EndsWith("xlsx") Then
                GridViewGeraeteVerfolgung.ExportToXlsx(saveFileDialog1.FileName)
            Else
                GridViewGeraeteVerfolgung.ExportToXls(saveFileDialog1.FileName)
            End If
            Dim result As MsgBoxResult
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If
        End If
        Cursor = Cursors.Default
    End Sub
    Public Sub XLS_Mit_Filter(ByVal vDataset As DataSet, ByVal vds_dt As String, ByVal vSheet_Name As String)
        Dim dt As DataTable

        'To manipulate an Excel workbook, the code needs to instantiate an Excel Application object, 
        'and then use the object model to add a new workbook, change the name (to Northwind Customers in this example), and do other UI chores.

        'Create an instance of Excel 2003, add a workbook, 
        'and let the user know what's happening
        Dim xl As New Excel.Application
        xl.Workbooks.Add()
        xl.ActiveSheet.Name = vSheet_Name
        xl.Visible = True
        xl.Range("A1").Value = "Exportiere Daten aus Datenbank...."

        'Once Excel is loaded and running, the code needs a reference to the table in the DataSet ds. 
        'Then it loops through the Columns collection of that DataTable object and places the field names 
        'in the first row of the worksheet. This example uses a Customers table and a Customers column heading.

        Try
            xl.ScreenUpdating = False

            'Start with the Customers table
            dt = vDataset.Tables(vds_dt) '"VWDWD_EXP_KPI"

            'Add the column headings for the Customers
            Dim dc As DataColumn
            Dim iCols As Int32 = 0
            For Each dc In dt.Columns
                xl.Range("A1").Offset(0, iCols).Value = dc.ColumnName
                iCols += 1
            Next

            'All that's left is to loop through the rows in the table and use the ItemArray property of the DataRow 
            'object to write the contents of each data row to a row of the worksheet. This is about as close as Excel 
            'comes to supporting a DataSet object directly.

            'Add the data
            Dim iRows As Int32
            For iRows = 0 To dt.Rows.Count - 1
                xl.Range("A2").Offset(iRows).Resize(1, iCols).Value = dt.Rows(iRows).ItemArray()
            Next
        Catch ex As Exception

            'The remaining code in the procedure updates the UI and applies built-in formatting to the worksheet.

        Finally
            xl.ScreenUpdating = True
        End Try
        'Make the sheet pretty
        With xl.ActiveSheet.Range("A1")
            .AutoFilter()
            .AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple) 'xlRangeAutoFormatSimple
        End With

        xl = Nothing
    End Sub
    Private Sub ToolStripButton12_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton12.Click
        Me.Cursor = Cursors.WaitCursor
        XLS_Mit_Filter(MyDataset, "VWSUPPLY_VERFOLGUNG", "Suppl.-Verfolgung")

        'Try

        '    Dim saveFileDialog1 As New SaveFileDialog()
        '    With saveFileDialog1
        '        .Filter = "Excel-Mappe (*.xls)|*.xls|All files (*.*)|*.*"
        '        .FilterIndex = 1
        '        .RestoreDirectory = True
        '        .Title = "Excel-Speicherort wählen:"
        '    End With
        '    'DGVVWSUPPLY_VERFOLGUNG.Splits(0).DisplayColumns("Markt").Visible = True
        '    'DGVVWSUPPLY_VERFOLGUNG.Splits(0).DisplayColumns("Modell").Visible = True
        '    'DGVVWSUPPLY_VERFOLGUNG.Splits(0).DisplayColumns("SerienNr").Visible = True
        '    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        '        '   DGVVWSUPPLY_VERFOLGUNG.ExportToExcel(saveFileDialog1.FileName)
        '        MsgBox("Export nach Excel erfolgreich abgeschlossen!", MsgBoxStyle.Information, "Erfolg:")
        '    End If


        '    'DGVVWSUPPLY_VERFOLGUNG.Splits(0).DisplayColumns("Markt").Visible = False
        '    'DGVVWSUPPLY_VERFOLGUNG.Splits(0).DisplayColumns("Modell").Visible = False
        '    'DGVVWSUPPLY_VERFOLGUNG.Splits(0).DisplayColumns("SerienNr").Visible = False
        'Catch ex As Exception
        '    MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Export Excel:")
        'End Try

        Cursor = Cursors.Default
    End Sub
End Class