Imports IntraSell_DLL
Imports IntraSell_Net_Base

Public Class VorgangListe
    Inherits AbstractForm
    Implements InterfaceExportableGrid


    Const AbgeschlossenCheckBox_index As Integer = 10
    Const BezahltCheckBox_index As Integer = 8

    Public Event FilterChanged(Filter As String)
    Public SaveFilter As Boolean = True

    Protected filter As String
    Dim laden As Boolean = True

    Friend COLUMN_MITARBEITER = 11

    Friend FILTER_VAR_NAME_DATUM_VON = MitarbeiterID & "_" & Name & "_Filter_DatumVon"
    Friend FILTER_VAR_NAME_DATUM_BIS = MitarbeiterID & "_" & Name & "_Filter_DatumBis"
    Friend FILTER_VAR_NAME_TYP = MitarbeiterID & "_" & Name & "_Filter_Typ"
    'Dim FILTER_VAR_NAME_NUMMER = ModuleGlobals.MitarbeiterID & "_" & Me.Name & "_Filter_" & Me.NummerTextBox.Name
    Friend FILTER_VAR_NAME_MANDANT = MitarbeiterID & "_" & Name & "_Filter_Mandant"
    Friend FILTER_VAR_NAME_ZEIGE_ALLE_FILTER = MitarbeiterID & "_" & Name & "_Filter_ZEIGE_ALLE_FILTER"

    Const col_stk_index As Integer = 12
    Const col_brutto_index As Integer = 13 'Brutto
    Const col_netto_index As Integer = 14 'Netto
    Const col_mwst_index As Integer = 15 'MWST

    Private Sub Form_Verlassen() Handles MyBase.Verlassen
        Me.Close()
    End Sub

    Public Sub Export(sender As Object) Implements InterfaceExportableGrid.Export
        FunctionsDataGrid.ExportDGToCSV(VorgangListeDataGridView)
    End Sub

    Sub LoadData()
        If HasRecht(MitarbeiterID, Rechte.Vorgangliste, False) Then
            Try
                If AdressenControl1.IDNR > 0 Then
                    BuchVorgangListeTableAdapter.FillByKundNR(DsVorgaenge.buchVorgangListe, AdressenControl1.IDNR, DatumVon.Value, DatumUntil.Value)
                Else
                    BuchVorgangListeTableAdapter.Fill(DsVorgaenge.buchVorgangListe, DatumVon.Value, DatumUntil.Value)
                End If
            Catch ex As Exception
                HandleAppError(ex)
            End Try
        End If
    End Sub

    Private Sub VorgangListe_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Try
            If HasRecht(MitarbeiterID, "Vorgangliste", True) Then
                ds = DsVorgaenge
                ParentBindingNavigator.BindingSource = BuchVorgangListeBindingSource

                SichbtbareSpaltenConfig()

                If ExistsVarValue(FILTER_VAR_NAME_ZEIGE_ALLE_FILTER) Then
                    AlleFilterCheckBox.Checked = VarValue(FILTER_VAR_NAME_ZEIGE_ALLE_FILTER)
                    SetzeSichtbarkeitDerFilter()
                End If
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Sub LadeFormDaten()
        Try
            DatumVon.Format = DateTimePickerFormat.Custom
            DatumVon.CustomFormat = "dd MM yyyy HH mm"

            DatumUntil.Format = DateTimePickerFormat.Custom
            DatumUntil.CustomFormat = "dd MM yyyy HH mm"

            LoadFilter()
            'LoadData()
            FillComboBox(TypComboBox, "SELECT Typ, Bezeichnung FROM buchVorgangTyp ORDER By Bezeichnung", "Bezeichnung", "Typ")
            FillComboBox(StatusComboBox, "SELECT Status from buchVorgaengeStatus Group by Status", "Status")
            FillComboBox(LandComboBox, "SELECT Name from grLand Order by Name", "Name")
            FillComboBox(KundengruppeComboBox, "SELECT Gruppe from `ofAdressen-Kundengruppen` Order by Gruppe", "Gruppe")
            FillComboBox(PreislisteComboBox, SQL_PREISLISTEN, "PreislisteName")
            FillComboBox(ArtikelKategorieComboBox, "SELECT artkatnr, Name FROM `grArtikel-Kategorien` ORDER By Name", "Name", "artkatnr")
            FillComboBox(MandantComboBox, "SELECT IDNR, Firma FROM Mandant ORDER By Firma", "Firma", "IDNR")
            FillComboBox(SystemComboBox, "SELECT distinct SYSTEM, SYSTEM FROM buchVorgang GROUP By SYSTEM", "SYSTEM", "SYSTEM")

            TypComboBox.Text = ""
            StatusComboBox.Text = ""
            LandComboBox.Text = ""
            KundengruppeComboBox.Text = ""
            PreislisteComboBox.Text = ""
            LoadFilter()
            VorgangListeDataGridView.Dock = DockStyle.Fill
            laden = False

            FilterButton_Click(Nothing, Nothing)

            Dim fU = New FormUtility
            fU.MakeSplitterCustomizable(SplitContainer, "VORGANGLISTE_SPLITTER_SIZE")
            SetzeSichtbarkeitDerFilter()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub SichbtbareSpaltenConfig()
        Try
            KundNrDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_KUNDNR_SICHTBAR, False)
            FirmaDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_FIRMA_SICHTBAR, True)
            NameDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_NAME_SICHTBAR, True)
            VornameDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_VORNAME_SICHTBAR, False)
            StatusDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_SUMME_NETTO_SICHTBAR, True)
            MitarbeiterNrDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_SUMME_NETTO_SICHTBAR, False)
            SummeDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_SUMME_NETTO_SICHTBAR, False)
            SummeBruttoDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_SUMME_BRUTTO_SICHTBAR, True)
            SummeMWSTDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_MWST_SICHTBAR, False)
            WaehrungDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_WAEHRUNG_SICHTBAR, False)
            Ort.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_ORT_SICHTBAR, True)
            PLZ.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_PLZ_SICHTBAR, False)
            Adresse.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_ADRESSE_SICHTBAR, True)
            TransportMethodeDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_TRANSPORTMETHODE_SICHTBAR, False)
            ZahlungsbedingungDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_ZAHLUNGSMETHODE_SICHTBAR, False)
            ZahlungsMethodeDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_ZAHLUNGSBEDINGUNG_SICHTBAR, True)
            WoherDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_WOHER_SICHTBAR, False)
            WohinDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_WOHIN_SICHTBAR, False)
            LieferantNrDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_LIEFERANTNR_SICHTBAR, False)
            KundNr2DataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_KUNDNR2_SICHTBAR, False)
            ErstelltAmDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_ERSTELLTAM_SICHTBAR, False)
            NotizDataGridViewTextBoxColumn.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_NOTIZ_SICHTBAR, False)
            System2.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_SYSTEM_SICHTBAR, False)
            BetragEingangKassa.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_EINGANGKASSSA_SICHTBAR, True)
            MandantNr.Visible = VarValue_Default(Variablen.VORGANGLISTE_SPALTE_MANDANTNR_SICHTBAR, False)

        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub TypComboBox_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles TypComboBox.SelectedIndexChanged
        Try
            If VarType(TypComboBox.SelectedValue) = VariantType.String Then
                FillComboBox(StatusComboBox, "SELECT Status from buchVorgaengeStatus where VorgangTyp='" & TypComboBox.SelectedValue & "' Group by Status", "Status")
            End If
        Catch ex As Exception
            'Ignore
        End Try
    End Sub

    Private Sub SaveFilterCommand()
        Try
            If SaveFilter Then
                SetVarValue(FILTER_VAR_NAME_DATUM_VON, DatumVon.Value)
                SetVarValue(FILTER_VAR_NAME_DATUM_BIS, DatumUntil.Value)
                SetVarValue(FILTER_VAR_NAME_TYP, TypComboBox.SelectedValue)
                'SetVarValue(FILTER_VAR_NAME_NUMMER, Me.NummerTextBox.Text)
                SetVarValue(FILTER_VAR_NAME_MANDANT, MandantComboBox.SelectedValue)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

#Region "Filter"


    Private Sub LoadFilter()
        Try
            If SaveFilter Then

                If VarValue_Default(Variablen.KASSALISTE_FILTER_DATUM_MERKEN, "false") Then
                    DatumVon.Value = VarValue_Default(FILTER_VAR_NAME_DATUM_VON, Today)
                    DatumUntil.Value = VarValue_Default(FILTER_VAR_NAME_DATUM_BIS, Today.AddDays(1))
                Else
                    DatumVon.Value = AdaptZeiten(AdaptToday())
                    DatumUntil.Value = AdaptZeiten(AdaptToday().AddDays(1).AddSeconds(-1))
                End If

                Try
                    If TypComboBox.SelectedValue Is Nothing Then
                        TypComboBox.SelectedValue = VarValue_Default(FILTER_VAR_NAME_TYP, TypComboBox.SelectedValue)
                    End If
                Catch ex As Exception
                    'Ignore
                End Try
                'Me.NummerTextBox.Text = VarValue_Default(FILTER_VAR_NAME_NUMMER, Me.NummerTextBox.Text)
                'AdressenControl1.IDNR = KundenIDNR

                If VarValue_Default(Variablen.VORGANGLISTE_MITARBEITER_NR_VON_LOGIN, "false") Then
                    MitarbeiterComboBox.IDNR = MitarbeiterID
                End If

                Try
                    If ExistsVarValue(FILTER_VAR_NAME_MANDANT) Then
                        Dim val = VarValue(FILTER_VAR_NAME_MANDANT)
                        If Not IsDBNull(val) AndAlso val IsNot Nothing Then
                            MandantComboBox.SelectedValue = val
                        End If
                    End If
                Catch ex As Exception
                    'Ignore
                End Try
            End If
        Catch ex As Exception
            HandleAppError(ex, "LoadFilter", Silent:=True)
        End Try
    End Sub

    'Filtern
    Protected Sub FilterButton_Click(sender As Object, e As System.EventArgs) Handles FilterButton.Click
        Try
            Cursor = Cursors.WaitCursor

            If laden Then Exit Sub
            alreadyFormattedIndex = -1
            filter = "1=1"

            If TypComboBox.Text.Length > 0 Then
                filter &= " and Typ Like '" & TypComboBox.SelectedValue & "%'"
            End If

            If NummerTextBox.Text.Length > 0 Then
                filter = filter & " and Nummer = " & NummerTextBox.Text
            End If

            If StatusComboBox.Text.Length > 0 Then
                filter &= " and Status Like '" & StatusComboBox.Text & "%'"
            End If

            If ArtikelControl1.ArtNr > 0 Then
                filter = filter & " and ArtNr =  " & ArtikelControl1.ArtNr
            End If

            If ArtikelKategorieComboBox.Text.Length > 0 Then
                filter = filter & " and ArtKatNr =" & ArtikelKategorieComboBox.SelectedValue
            End If

            If Trim(AdressenControl1.Text) <> "" _
                AndAlso AdressenControl1.Text <> AdressenControl1.DEFAULT_TEXT _
                AndAlso IsNumeric(AdressenControl1.IDNR) _
                AndAlso AdressenControl1.IDNR >= 0 Then
                filter &= " and KundNr = " & CStr(AdressenControl1.IDNR)
            End If

            If IsNumeric(SummeVonTextBox.Text) AndAlso SummeVonTextBox.Text.Length > 0 Then
                filter = filter & " and Summe >=" & SummeVonTextBox.Text
            End If

            If IsNumeric(SummeBisTextBox.Text) AndAlso SummeBisTextBox.Text.Length > 0 Then
                filter &= " and Summe <=  " & SummeBisTextBox.Text
            End If

            If LandComboBox.Text.Length > 0 Then
                filter &= " and Land Like '" & LandComboBox.Text & "%'"
            End If

            If PLZVonTextBox.Text.Length > 0 Then
                filter &= " and PLZ >= '" & PLZVonTextBox.Text & "%'"
            End If

            If PLZBisTextBox.Text.Length > 0 Then
                filter &= " and PLZ <= '" & PLZBisTextBox.Text & "%'"
            End If

            If KundengruppeComboBox.Text.Length > 0 Then
                filter &= " and Kundengruppe Like '" & KundengruppeComboBox.Text & "%'"
            End If

            If PreislisteComboBox.Text.Length > 0 Then
                filter &= " and Preisliste Like '" & PreislisteComboBox.Text & "%'"
            End If

            If Me.BezahltCheckBox.CheckState = CheckState.Checked Then
                filter &= " and bezahlt=True"
            ElseIf Me.BezahltCheckBox.CheckState = CheckState.Unchecked Then
                filter &= " and bezahlt=False"
            End If

            If Me.AbgeschlossenCheckBox.CheckState = CheckState.Checked Then
                filter &= " and abgeschlossen=True"
            ElseIf Me.AbgeschlossenCheckBox.CheckState = CheckState.Unchecked Then
                filter &= " and abgeschlossen=False"
            End If

            If Me.AusgedrucktCheckBox.CheckState = CheckState.Checked Then
                filter &= " and ausgedruckt=True"
            ElseIf Me.AusgedrucktCheckBox.CheckState = CheckState.Unchecked Then
                filter &= " and ausgedruckt=False"
            End If

            If MitarbeiterComboBox.IDNR > 0 Then
                filter = filter & " and MitarbeiterNr = '" & MitarbeiterComboBox.IDNR & "'"
            End If

            If NotizTextBox.Text.Length > 0 Then
                filter &= " and ( Notiz Like '%" & NotizTextBox.Text & "%' or NotizExtern Like '%" & NotizTextBox.Text & "%' or  NotizIntern Like '%" & NotizTextBox.Text & "%') "
            End If

            If MandantComboBox.Text.Length > 0 Then
                filter = filter & " and MandantNr = '" & MandantComboBox.SelectedValue & "'"
            End If

            If SystemComboBox.Text.Length > 0 Then
                filter = filter & " and System = '" & SystemComboBox.SelectedValue & "'"
            End If

            If KundNrVonTextBox.Text.Length > 0 AndAlso IsNumeric(KundNrVonTextBox.Text) Then
                filter &= " and KundNr >= " & KundNrVonTextBox.Text
            End If

            If KundNrBisTextBox.Text.Length > 0 AndAlso IsNumeric(KundNrBisTextBox.Text) Then
                filter &= " and KundNr <= " & KundNrBisTextBox.Text
            End If

            LoadData()
            ApplyFilter(filter)
            SaveFilterCommand()

            RaiseEvent FilterChanged(filter)
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Cursor = Cursors.Default

        End Try
    End Sub

    Private Sub ButtonFilterReset_Click(sender As Object, e As EventArgs) Handles ButtonFilterReset.Click
        Try
            TypComboBox.Text = Nothing
            NummerTextBox.Text = Nothing
            StatusComboBox.Text = Nothing
            ArtikelControl1.ArtNr = 0
            ArtikelKategorieComboBox.Text = Nothing
            AdressenControl1.Text = Nothing
            AdressenControl1.IDNR = Nothing
            SummeVonTextBox.Text = Nothing
            SummeBisTextBox.Text = Nothing
            LandComboBox.Text = Nothing
            PLZVonTextBox.Text = Nothing
            PLZBisTextBox.Text = Nothing
            KundengruppeComboBox.Text = Nothing
            PreislisteComboBox.Text = Nothing
            BezahltCheckBox.CheckState = CheckState.Indeterminate
            AbgeschlossenCheckBox.CheckState = CheckState.Indeterminate
            AusgedrucktCheckBox.CheckState = CheckState.Indeterminate
            MitarbeiterComboBox.IDNR = Nothing
            NotizTextBox.Text = Nothing
            MandantComboBox.Text = Nothing
            SystemComboBox.Text = Nothing
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        Finally
            FilterButton_Click(sender, e)
        End Try
    End Sub

    Protected Sub ApplyFilter(filter As String)
        Try
            WriteDebug("ApplyFilter: " & filter)
            If VorgangListeDataGridView.Visible Then
                If filter IsNot Nothing Then
                    BuchVorgangListeBindingSource.Filter = filter
                Else
                    BuchVorgangListeBindingSource.Filter = Nothing
                End If
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

#End Region

    ''' <summary>
    ''' Vorgang Maske öffnen 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub VorgangListeDataGridView_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles VorgangListeDataGridView.CellDoubleClick
        ShowVorgang()
    End Sub

    Private Sub VorgangListeDataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles VorgangListeDataGridView.CellContentClick
        ShowAuswahl()
    End Sub

    Private Sub VorgangListeDataGridView_RowHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles VorgangListeDataGridView.RowHeaderMouseClick
        ShowAuswahl()
    End Sub

    Private Sub VorgangListeDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles VorgangListeDataGridView.SelectionChanged
        'ShowAuswahl()
    End Sub

    Sub ShowVorgang()
        Try
            If VorgangListeDataGridView.SelectedRows.Count = 1 Then
                Dim Nummer = VorgangListeDataGridView.SelectedRows(0).Cells(0).Value
                Dim Typ = VorgangListeDataGridView.SelectedRows(0).Cells(1).Value

                If (IsBarVorgang(Typ, Nummer)) Then
                    OeffneBarVorgangByNummer(Typ, Nummer)
                Else
                    OeffneVorgangByNummer(Typ, Nummer)
                End If
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub



    Private Sub DatumVon_ValueChanged(sender As Object, e As System.EventArgs) Handles DatumVon.ValueChanged
        Try
            If VarValue_Default(Variablen.VORGANGLISTE_AUTOFILTER, True) Then
                FilterButton_Click(Nothing, Nothing)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub DatumUntil_ValueChanged(sender As Object, e As EventArgs) Handles DatumUntil.ValueChanged
        Try
            If DatumUntil.Value.Hour = 0 Then
                DatumUntil.Value = DatumUntil.Value.AddMinutes(24 * 60 - 1)
            End If
            If VarValue_Default(Variablen.VORGANGLISTE_AUTOFILTER, True) Then
                FilterButton_Click(Nothing, Nothing)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Dim alreadyFormattedIndex = -1

    'Format 
    Private Sub DataGridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles VorgangListeDataGridView.CellFormatting
        Try

            Dim dr = VorgangListeDataGridView.Rows(e.RowIndex)
            Dim Vorgang As dsVorgaenge.buchVorgangListeRow = VorgangListeDataGridView.Rows(e.RowIndex).DataBoundItem.row

            If e.ColumnIndex = COLUMN_MITARBEITER AndAlso Not Vorgang.IsMitarbeiterNrNull Then
                dr.Cells(COLUMN_MITARBEITER).Style.BackColor = MitarbeiterFarbe(Vorgang.MitarbeiterNr)
            End If

            If e.ColumnIndex < 2 Then

                alreadyFormattedIndex = e.RowIndex

                If Vorgang.Bezahlt Then
                    e.CellStyle.BackColor = Color.LemonChiffon
                End If

                If Vorgang.Abgeschlossen Then 'Abgeschlossen
                    e.CellStyle.BackColor = Color.Gray
                End If
                'Next

                If Vorgang.Status IsNot Nothing Then
                    Dim clr = GetVorgangStatusColor(Vorgang.Typ, Vorgang.Status)
                    If clr <> Color.White Then
                        e.CellStyle.BackColor = clr
                    End If
                End If

            End If

        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub NotizTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles NotizTextBox.TextChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub PLZVonTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles PLZVonTextBox.TextChanged
        PLZBisTextBox.Text = PLZVonTextBox.Text
    End Sub

#Region "Menu"
    Private Sub ÖffneAlsBarvorgangToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ÖffneAlsBarvorgangToolStripMenuItem.Click
        OeffneVorgang("VorgangBar")
    End Sub

    Private Sub ÖffneAlsEasyKassaToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ÖffneAlsEasyKassaToolStripMenuItem.Click
        OeffneVorgang("EasyKassa")
    End Sub

    Private Sub ÖffneAlsVorgangToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ÖffneAlsVorgangToolStripMenuItem.Click
        OeffneVorgang("Vorgang")
    End Sub

    Private Sub EasyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EasyToolStripMenuItem.Click
        OeffneVorgang("VorgangEasy")
    End Sub

    Sub OeffneVorgang(form As String)
        Try
            If BuchVorgangListeBindingSource.Current IsNot Nothing Then
                Dim vorgangRow As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.Row
                If form = "Vorgang" Then
                    OeffneVorgangByNummer(vorgangRow.Typ, vorgangRow.Nummer)
                ElseIf form = "VorgangEasy" Then
                    OeffneVorgangByNummerEasy(vorgangRow.Typ, vorgangRow.Nummer)
                ElseIf form = "VorgangBar" Then
                    OeffneBarVorgangByNummer(vorgangRow.Typ, vorgangRow.Nummer)
                ElseIf form = "EasyKassa" Then
                    OeffneEasyKassaByNummer(vorgangRow.Typ, vorgangRow.Nummer)
                Else
                    MsgBox("Form " & form & " ist nicht bekannt!")
                End If
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub
#End Region

    ''' <summary>
    ''' Nicht löschen - sonst Fehlermeldungen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    ''' 
    Private Sub VorgangListeDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles VorgangListeDataGridView.DataError
        'Ignore
    End Sub

    'Auto filter
    Private Sub TypComboBox_DropDownClosed(sender As Object, e As EventArgs) Handles TypComboBox.DropDownClosed
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub NummerTextBox_TextChanged(sender As Object, e As EventArgs) Handles NummerTextBox.TextChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub StatusComboBox_Validated(sender As Object, e As EventArgs) Handles StatusComboBox.DropDownClosed
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ArtikelControl1_ArtNrChanged(ArtNr As Integer) Handles ArtikelControl1.ArtNrChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub AdressenControl1_IDNRChanged(IDNR As Integer) Handles AdressenControl1.IDNRChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub LieferantComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LieferantComboBox.SelectedIndexChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub LandComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LandComboBox.SelectedIndexChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub PLZBisTextBox_TextChanged(sender As Object, e As EventArgs) Handles PLZBisTextBox.TextChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ArtikelKategorieComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ArtikelKategorieComboBox.SelectedIndexChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ShowAuswahl()
        If Not IsNothing(BuchVorgangListeBindingSource.Current) Then
            VorgangOffnen.ShowAuswahl(BuchVorgangListeBindingSource.Current.row)
        End If
    End Sub

    Private Sub SucheAuftragNummerToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SucheAuftragNummerToolStripMenuItem.Click
        SucheNachNummer(VorgangTypen.AU, "Auftrag")
    End Sub

    Private Sub SucheNummerToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SucheNummerToolStripMenuItem.Click
        SucheNachNummer(VorgangTypen.AR, "Rechnung")
    End Sub


    Private Sub VorgängeAbschliessenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VorgängeAbschliessenToolStripMenuItem.Click
        Try

            If MsgBox("Möchten Sie alle Vorgänge von der Liste abschliessen?", vbYesNo) = vbYes Then
                Dim cnt As Integer = 0
                For Each r In VorgangListeDataGridView.Rows
                    Dim v As dsVorgaenge.buchVorgangListeRow = r.DataBoundItem.row
                    Dim Abgeschlossen As Boolean = IstVorgangAbgeschlossen(v.Typ, v.Nummer)
                    If Not Abgeschlossen Then
                        VorgangAbschliessen(v.Typ, v.Nummer, silent:=True, benutzeTransaktion:=True)
                        cnt += 1
                    End If

                Next

                MsgBox(String.Format("Fertig! {0} Vorgänge wurden erfolgreich abgeschlossen", cnt), vbInformation)
                FilterButton_Click(Nothing, Nothing)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub SammelrechnungErstellenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SammelrechnungErstellenToolStripMenuItem.Click
        Try
            If TypComboBox.SelectedValue <> VorgangTypen.AR Then
                MsgBox(Messages.Vorgangsliste_Rechnung_waehlen, vbInformation)
                Exit Sub
            End If
            If MandantComboBox.Text = "" Then
                MsgBox(Messages.Vorgangsliste_Mandant_waehlen, vbInformation)
                Exit Sub
            End If
            FilterButton_Click(sender, e)

            Dim RechnungsNummern As New List(Of dsVorgaenge.buchVorgangListeRow)
            For Each r In VorgangListeDataGridView.Rows
                Dim v As dsVorgaenge.buchVorgangListeRow = r.DataBoundItem.row
                RechnungsNummern.Add(v)
            Next

            VorgangWizzardSammelrechnung.MandantNr = MandantComboBox.SelectedValue
            VorgangWizzardSammelrechnung.RechnungsNummern = RechnungsNummern
            VorgangWizzardSammelrechnung.ShowDialog()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub SammelrechnungFürAufträgeErstellenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SammelrechnungFürAufträgeErstellenToolStripMenuItem.Click
        Try
            If Not (TypComboBox.SelectedValue = VorgangTypen.AU Or TypComboBox.SelectedValue = VorgangTypen.LI) Then
                MsgBox(Messages.Vorgangsliste_AuftragLieferschein_waehlen, vbInformation)
                Exit Sub
            End If
            If AdressenControl1.IDNR = 0 Then
                MsgBox(Messages.Vorgangsliste_Kunde_waehlen, vbInformation)
                Exit Sub
            End If
            FilterButton_Click(sender, e)

            Dim RechnungsNummern As New List(Of dsVorgaenge.buchVorgangListeRow)
            For Each r In VorgangListeDataGridView.Rows
                Dim v As dsVorgaenge.buchVorgangListeRow = r.DataBoundItem.row
                RechnungsNummern.Add(v)
            Next

            'VorgangWizzardSammelrechnung.MandantNr = MandantComboBox.SelectedValue
            'VorgangWizzardSammelrechnung.RechnungsNummern = RechnungsNummern
            'VorgangWizzardSammelrechnung.ShowDialog()

            Dim mandantNr = -1
            If MandantComboBox.SelectedValue IsNot Nothing Then
                mandantNr = MandantComboBox.SelectedValue
            End If
            SammelRechnungErstellen(mandantNr, AdressenControl1.IDNR, TypComboBox.SelectedValue, RechnungsNummern:=RechnungsNummern)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub NichtAusgedrucktCheckBox_KeyDown(sender As Object, e As KeyEventArgs) Handles NichtAusgedrucktCheckBox.KeyDown, NurOffeneCheckBox.KeyDown, TypComboBox.KeyDown, _
        NummerTextBox.KeyDown, DatumVon.KeyDown, DatumUntil.KeyDown, NummerTextBox.KeyDown, _
        StatusComboBox.KeyDown, _
        ArtikelControl1.KeyDown, _
        MitarbeiterComboBox.KeyDown, _
        AdressenControl1.KeyDown, _
        LandComboBox.KeyDown, _
        PLZVonTextBox.KeyDown, _
        PLZBisTextBox.KeyDown, _
        BezahltCheckBox.KeyDown, _
        AusgedrucktCheckBox.KeyDown, _
        AbgeschlossenCheckBox.KeyDown, _
        AbgeschlossenCheckBox.KeyDown, _
        ArtikelKategorieComboBox.KeyDown, _
        SystemComboBox.KeyDown, _
        MandantComboBox.KeyDown, _
        LieferantComboBox.KeyDown
        If e.KeyCode = Keys.Enter Then
            FilterButton_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub NurOffeneCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles NurOffeneCheckBox.CheckedChanged
        If NurOffeneCheckBox.Checked Then
            AbgeschlossenCheckBox.Checked = Not NurOffeneCheckBox.Checked
        Else
            AbgeschlossenCheckBox.CheckState = CheckState.Indeterminate
        End If

        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub NichtAusgedrucktCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles NichtAusgedrucktCheckBox.CheckedChanged
        If NichtAusgedrucktCheckBox.Checked Then
            AusgedrucktCheckBox.Checked = Not NichtAusgedrucktCheckBox.Checked
        Else
            AusgedrucktCheckBox.CheckState = CheckState.Indeterminate
        End If
        FilterButton_Click(Nothing, Nothing)

    End Sub


    Private Sub BuchVorgangArtikelVerkaufDataGridView_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles VorgangListeDataGridView.DataBindingComplete
        Try

            If VorgangListeDataGridView.Rows.Count < 0 Then Return

            Dim total1, total2, total3 As Decimal
            total1 = 0
            total2 = 0
            total3 = 0

            For Each dr In VorgangListeDataGridView.Rows
                Dim cell1 = dr.Cells(col_brutto_index).Value
                Dim cell2 = dr.Cells(col_netto_index).Value
                Dim cell3 = dr.Cells(col_mwst_index).Value
                If IsNumeric(cell1) Then
                    total1 += cell1
                End If
                If IsNumeric(cell2) Then
                    total2 += cell2
                End If
                If IsNumeric(cell3) Then
                    total3 += cell3
                End If
            Next
            If IsNumeric(total1) AndAlso IsNumeric(total2) Then
                txtTotal_Brutto.Text = FormatCurrency(total1)
                txtTotal_Netto.Text = FormatCurrency(total2)
                txtTotal_MWST.Text = FormatCurrency(total3)
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=False)
        End Try
    End Sub

    Private Sub AlleFilterCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles AlleFilterCheckBox.CheckedChanged
        SetzeSichtbarkeitDerFilter()
        SetVarValue(FILTER_VAR_NAME_ZEIGE_ALLE_FILTER, AlleFilterCheckBox.Checked)
    End Sub

    Private Sub SetzeSichtbarkeitDerFilter()
        Try
            ArtikelControl1.Visible = AlleFilterCheckBox.Checked
            LabelArtikel.Visible = AlleFilterCheckBox.Checked
            LabelUmsatz.Visible = AlleFilterCheckBox.Checked
            TableLayoutPanelUmsatz.Visible = AlleFilterCheckBox.Checked
            LabelMitarbeiter.Visible = AlleFilterCheckBox.Checked
            MitarbeiterComboBox.Visible = AlleFilterCheckBox.Checked
            'LabelKunde.Visible = AlleFilterCheckBox.Checked
            'AdressenControl1.Visible = AlleFilterCheckBox.Checked
            LabelKategorie.Visible = AlleFilterCheckBox.Checked
            ArtikelKategorieComboBox.Visible = AlleFilterCheckBox.Checked
            LabelNotiz.Visible = AlleFilterCheckBox.Checked
            NotizTextBox.Visible = AlleFilterCheckBox.Checked
            SystemLabel.Visible = AlleFilterCheckBox.Checked
            SystemComboBox.Visible = AlleFilterCheckBox.Checked
            MandantLabel.Visible = AlleFilterCheckBox.Checked
            MandantComboBox.Visible = AlleFilterCheckBox.Checked
            LabelLieferant.Visible = AlleFilterCheckBox.Checked
            LieferantComboBox.Visible = AlleFilterCheckBox.Checked
            LabelPreisliste.Visible = AlleFilterCheckBox.Checked
            PreislisteComboBox.Visible = AlleFilterCheckBox.Checked
            LabelKundnegruppe.Visible = AlleFilterCheckBox.Checked
            KundengruppeComboBox.Visible = AlleFilterCheckBox.Checked
            LabelKundNr.Visible = AlleFilterCheckBox.Checked
            TableLayoutPanelKundenNr.Visible = AlleFilterCheckBox.Checked

            Labelland.Visible = AlleFilterCheckBox.Checked
            LandComboBox.Visible = AlleFilterCheckBox.Checked
            LabelPLZ.Visible = AlleFilterCheckBox.Checked
            TableLayoutPanelpPLZ.Visible = AlleFilterCheckBox.Checked
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub BtnSpalten_Click(sender As Object, e As EventArgs) Handles BtnSpalten.Click
        Dim v As New Vars
        v.Show()
        v.Filter("VORGANGLISTE_SPALTE")
        AddHandler v.FormClosed, AddressOf Vars_FormClosed
    End Sub

    Private Sub Vars_FormClosed(sender As Object, e As FormClosedEventArgs)
        SichbtbareSpaltenConfig()
    End Sub
End Class