Public Class frmFaktAufschubSuche
    Dim BezugsNr = ""

    Public suche = True
    Dim loaded = False

    Public Zkteing_Index As New List(Of Integer) '= ""

    Sub New(Optional suche As Boolean = True)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.suche = suche
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Sub New(BezugsNr As String, suche As Boolean, Optional DY_BezugsNr As String = "")

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.BezugsNr = BezugsNr
        If DY_BezugsNr <> "" Then Me.BezugsNr = DY_BezugsNr
        Me.suche = suche
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Private Sub frmFaktAufschubSuche_Load(sender As Object, e As EventArgs) Handles Me.Load
        btnMonat.Text = "Monat"
        btnJahr.Text = Now.Year

        Dim FirmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL") Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("FAKTURIERUNG_VERAGIMEX", "SDL") Then
            FirmaTmp = "VERAGIMEX"
        End If

        Select Case FirmaTmp
            Case "IMEX"
                cboKonto.Items.Clear()
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("alle", "'002719','002718'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("EUST (002719)", "'002719'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ZOLL (002718)", "'002718'"))
                cboKonto.SelectedIndex = 0
            Case "UNISPED"
                cboKonto.Items.Clear()
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("alle", "'006145','006146','006077'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("EUST (006146)", "'006146'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ZOLL (006145)", "'006145'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("EUST AT (006077)", "'006077'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ZOLL AT (006078)", "'006078'"))
                cboKonto.SelectedIndex = 0
            Case "VERAGIMEX"
                cboKonto.Items.Clear()
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("alle", "'006136','006128','3517233','002719','002718'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG DE EUST (006136)", "'006136'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG DE ZOLL (006128)", "'006128'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG AT ZOLL/EUST (3517233)", "'3517233'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("IMEX EUST (002719)", "'002719'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("IMEX ZOLL (002718)", "'002718'"))
                cboKonto.SelectedIndex = 0
            Case Else
                cboKonto.Items.Clear()
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("alle", "'006136','006128','3517233'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DE EUST (006136)", "'006136'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DE ZOLL (006128)", "'006128'"))
                cboKonto.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("AT ZOLL/EUST (3517233)", "'3517233'"))
                cboKonto.SelectedIndex = 0
        End Select

        If Not suche Then
            MyDatagridview1.MultiSelect = False
            Panel2.Visible = False
            Me.Height = Screen.FromRectangle(Me.Bounds).WorkingArea.Size.Height
            Me.Top = 0

            If Now.Day <= 15 Then
                txtAbfertDat._value = Now.AddMonths(-1).ToString("01.MM.yyyy")
                txtAbfertDatBis._value = Now.ToString("15.MM.yyyy")
            Else
                txtAbfertDat._value = Now.ToString("01.MM.yyyy")
                txtAbfertDatBis._value = Now.AddMonths(1).ToString("15.MM.yyyy")
            End If
            cbxVerbuchteAnzeigen.CheckState = CheckState.Indeterminate
        Else
            cbxVerbuchteAnzeigen.CheckState = CheckState.Unchecked
            txtAbfertDat._value = Now.AddMonths(-6).ToString("01.MM.yyyy")
            txtAbfertDatBis._value = Now.ToString("dd.MM.yyyy")
        End If

        loaded = True
        If BezugsNr <> "" Then
            txtBezugsNr.Text = BezugsNr
        Else
            initDGV()
        End If
    End Sub
    Sub initDGV()
        If Not loaded Then Exit Sub
        If suche Then
            initDGVUebernahem()
        End If
        Dim SQLStr = "SELECT  " & If(suche, " Top 200 ", "") & " Zkteing.[Index], "
        SQLStr &= " isnull(Zkteing.Status,'') as Status, Zkteing.Bezugsnummer, Zkteing.Registriernummer, Zkteing.Eingabedatum, Zkteing.LeistungsNr, Leistungen.LeistungsBez, Zkteing.Betrag, Zkteing.AOFD, Zkteing.AKTO, Zkteing.Fälligkeitsdatum, RK_ID "
        SQLStr &= " FROM (Zkteing LEFT JOIN Leistungen ON Zkteing.LeistungsNr = Leistungen.LeistungsNr)  LEFT JOIN RechnungsausgangPositionen ON Zkteing.[Index] = IndexZkteing "

        Select Case cbxVerbuchteAnzeigen.CheckState
            Case CheckState.Checked
                SQLStr &= " WHERE (Zkteing.Status='F') "
            Case CheckState.Unchecked
                SQLStr &= " WHERE (Zkteing.Status Is Null Or ( Zkteing.Status='X' Or Zkteing.Status='A' Or Zkteing.Status='')) "
            Case Else
                SQLStr &= " WHERE 1=1 "
        End Select


        If txtBezugsNr.Text <> "" Then SQLStr &= "And Bezugsnummer Like '" & txtBezugsNr.Text.Replace("*", "%") & "%' "
        If txtRegNr.Text <> "" Then SQLStr &= "And Registriernummer Like '" & txtRegNr.Text.Replace("*", "%") & "%' "

        SQLStr &= " And convert(date,Abfertigungsdatum ,104) between '" & (txtAbfertDat.Text) & "' and '" & (txtAbfertDatBis.Text) & "' "
        If cbxKontoNull.Checked Then
            SQLStr &= " And [AKTO] is null "
        Else
            SQLStr &= " And [AKTO] IN(" & cboKonto._value & ") "
        End If




        SQLStr &= " ORDER BY Zkteing.Bezugsnummer, Zkteing.LeistungsNr; "

        With MyDatagridview1
            .SET_SQL(SQLStr, "FMZOLL")
            .LOAD()

            If .Columns.Count = 0 Then Exit Sub
            .Columns("Index").Visible = False

            .Columns("Betrag").DefaultCellStyle.Format = "N2"
            .Columns("LeistungsNr").HeaderText = "Pos."

            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            ' .DefaultCellStyle.
            '.Columns("Index").

        End With

    End Sub

    Private Sub MyTextBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBezugsNr.TextChanged, txtRegNr.TextChanged, cbxVerbuchteAnzeigen.CheckStateChanged, cboKonto.SelectedIndexChanged, cbxKontoNull.CheckedChanged
        initDGV()
    End Sub

    Sub initDGVUebernahem()
        If Zkteing_Index.Count = 0 Then
            MyDatagridview2.DataSource = Nothing
        Else
            Dim SQLStr = "SELECT  TOP 200 Zkteing.[Index], "
            SQLStr &= " Zkteing.Bezugsnummer,Zkteing.LeistungsNr, Leistungen.LeistungsBez, Zkteing.Betrag "
            SQLStr &= " FROM (Zkteing LEFT JOIN Leistungen ON Zkteing.LeistungsNr = Leistungen.LeistungsNr)  LEFT JOIN RechnungsausgangPositionen ON Zkteing.[Index] = IndexZkteing "
            Dim StrId = ""
            For Each i In Zkteing_Index
                StrId &= "'" & i & "',"
            Next
            StrId = StrId.Substring(0, StrId.Length - 1)
            SQLStr &= " WHERE  Zkteing.[Index] IN ( " & StrId & " ) "
            SQLStr &= " ORDER BY Zkteing.Bezugsnummer, Zkteing.LeistungsNr; "

            With MyDatagridview2
                .SET_SQL(SQLStr, "FMZOLL")
                .LOAD()

                If .Columns.Count = 0 Then Exit Sub
                .Columns("Index").Visible = False

                .Columns("Betrag").DefaultCellStyle.Format = "N2"
                .Columns("LeistungsNr").HeaderText = "Pos."

                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
                ' .DefaultCellStyle.
                '.Columns("Index").

            End With
        End If
    End Sub
    Private Sub gridAviso_DoubleClick(sender As Object, e As System.EventArgs) Handles MyDatagridview1.DoubleClick
        If suche Then
            btn.PerformClick()
        Else
            Button3.PerformClick()
        End If

        'If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub
        'Zkteing_Index = MyDatagridview1.SelectedRows(0).Cells("Index").Value
        'If MyDatagridview1.SelectedRows(0).Cells("Status").Value = "X" Then
        '    VERAG_PROG_ALLGEMEIN.cZkteing.UPDATE_Status("", Zkteing_Index)
        'Else
        '    VERAG_PROG_ALLGEMEIN.cZkteing.UPDATE_Status("X", Zkteing_Index)
        'End If
        '' If VERAG_PROG_ALLGEMEIN.cZkteing.UPDATE_Status("X", Zkteing_Index) Then Me.DialogResult = DialogResult.OK
    End Sub

    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub

        If suche Then
            If ZollEustMarked() Then
                For Each r As DataGridViewRow In MyDatagridview1.SelectedRows
                    If r.Cells("Status").Value = "X" Then
                        VERAG_PROG_ALLGEMEIN.cZkteing.UPDATE_Status(DBNull.Value, MyDatagridview1.SelectedRows(0).Cells("Index").Value)
                        Zkteing_Index.Remove(MyDatagridview1.SelectedRows(0).Cells("Index").Value)
                    Else
                        VERAG_PROG_ALLGEMEIN.cZkteing.UPDATE_Status("X", MyDatagridview1.SelectedRows(0).Cells("Index").Value)
                        'For Each i In Zkteing_Index
                        '    If 
                        'Next
                        Zkteing_Index.Add(MyDatagridview1.SelectedRows(0).Cells("Index").Value)
                    End If
                Next
            Else
                MsgBox("Es darf nur je ein Zoll/Eust-Betrag pro Rechnung gewählt werden!")
            End If
        Else
            For Each r As DataGridViewRow In MyDatagridview1.SelectedRows
                If r.Cells("Status").Value = "X" Then

                End If
            Next
        End If
        MyDatagridview1.RELOAD()
        initDGVUebernahem()
        ' If VERAG_PROG_ALLGEMEIN.cZkteing.UPDATE_Status("X", Zkteing_Index) Then Me.DialogResult = DialogResult.OK
    End Sub

    Function ZollEustMarked()
        Dim zollCnt = 0
        Dim eustCnt = 0
        Dim sonstigeAbgabenCnt = 0
        Dim Zkteing_IndexTMP As New List(Of Integer) '= Zkteing_Index
        For Each i In Zkteing_Index
            Zkteing_IndexTMP.Add(i)
        Next
        'In Zkteing_IndexTMP reinladen
        Dim ATCTMP = ""
        For Each r As DataGridViewRow In MyDatagridview1.SelectedRows
            Zkteing_IndexTMP.Add(r.Cells("Index").Value)
        Next

        'dann alle prüfen
        For Each i In Zkteing_IndexTMP
            Dim LeistungsNr = (New VERAG_PROG_ALLGEMEIN.SQL).getValueTxtBySql("SELECT isnull(LeistungsNr,-1) FROM Zkteing WHERE Zkteing.[Index]='" & i & "'", "FMZOLL")
            Select Case LeistungsNr
                Case 20, 77
                    zollCnt += 1
                Case 10, 76, 60
                    eustCnt += 1
                Case 482
                    sonstigeAbgabenCnt += 1
            End Select
        Next

        'For Each r As DataGridViewRow In MyDatagridview1.SelectedRows
        '    Dim LeistungsNr = If(r.Cells("LeistungsNr").Value Is DBNull.Value, -1, r.Cells("LeistungsNr").Value)
        '    Select Case LeistungsNr
        '        Case 20, 77
        '            zollCnt += 1
        '        Case 10, 76, 60, 482
        '            eustCnt += 1
        '    End Select
        'Next

        'wenn zu viel, dann fehler!
        ' If zollCnt > 1 Or eustCnt > 1 Then Return False --> WEGEN AT ZOLL KEINE EINSCHRÄNKUNG MEHR!!!
        Return True
    End Function

    Private Sub txtBezugsNr_KeyDown(sender As Object, e As KeyEventArgs) Handles txtBezugsNr.KeyDown, txtRegNr.KeyDown, MyDatagridview1.KeyDown
        If e.KeyCode = Keys.Up Then
            If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub
            Dim index = MyDatagridview1.SelectedRows(0).Index
            If index > 0 Then
                MyDatagridview1.ClearSelection()
                MyDatagridview1.Rows(index - 1).Selected = True
            End If
            e.Handled = True
        End If
        If e.KeyCode = Keys.Down Then
            If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub
            Dim index = MyDatagridview1.SelectedRows(0).Index
            If (index + 1) < MyDatagridview1.Rows.Count - 1 Then
                MyDatagridview1.ClearSelection()
                MyDatagridview1.Rows(index + 1).Selected = True
            End If
            e.Handled = True
        End If
        If e.KeyCode = Keys.Return Then
            If e.Modifiers = Keys.Control Then
                Button2.PerformClick()
                e.Handled = True
            Else
                If MyDatagridview1.SelectedRows.Count <> 1 Then Exit Sub
                gridAviso_DoubleClick(MyDatagridview1, New EventArgs)
                e.Handled = True
            End If
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.DialogResult = DialogResult.OK
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim f As New frmFaktAufschubHinzufügen
        f.ShowDialog(Me)
        initDGV()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub
        Dim f As New frmFaktAufschubHinzufügen(MyDatagridview1.SelectedRows(0).Cells("Index").Value)
        f.ShowDialog(Me)
        initDGV()
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        cProgramFunctions.genExcelFromDGV_NEW(MyDatagridview1, True)
    End Sub


    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        txtAbfertDat._value = CDate(sender.value).ToShortDateString
        initDGV()
    End Sub

    Private Sub DateTimePicker2_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker2.ValueChanged
        txtAbfertDatBis._value = CDate(sender.value).ToShortDateString
        initDGV()
    End Sub

    Private Sub btnMonat_Click(sender As Object, e As EventArgs) Handles btnMonat.Click
        initBtns("Monat")
    End Sub

    Dim MONAT As Date = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-6)
    Dim srcTAG As Date = CDate(Now.ToShortDateString)

    Dim JAHR As Date = CDate("01.01." & Now.Year)

    Sub initBtns(MonatJahr)
        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year
        Select Case MonatJahr
            Case "Monat"
                DateTimePicker1.Value = MONAT
                DateTimePicker2.Value = MONAT.AddMonths(1).AddDays(-1)
            Case "Jahr"
                '  If cbxGeschaftsjahr.Checked Then
                'DateTimePicker1.Value = JAHR.AddMonths(1)
                ' DateTimePicker2.Value = JAHR.AddYears(1).AddMonths(1).AddDays(-1)
                ' Else
                DateTimePicker1.Value = JAHR
                DateTimePicker2.Value = JAHR.AddYears(1).AddDays(-1)
                'End If
            Case "Tag"
                '  If cbxGeschaftsjahr.Checked Then
                'DateTimePicker1.Value = JAHR.AddMonths(1)
                ' DateTimePicker2.Value = JAHR.AddYears(1).AddMonths(1).AddDays(-1)
                ' Else
                DateTimePicker1.Value = srcTAG
                DateTimePicker2.Value = srcTAG
                If srcTAG = Now.ToShortDateString Then
                    Button5.Text = "Heute"
                ElseIf srcTAG = Now.AddDays(-1).ToShortDateString Then
                    Button5.Text = "Gestern"
                ElseIf srcTAG = Now.AddDays(-2).ToShortDateString Then
                    Button5.Text = "Vorgestern"
                Else
                    Button5.Text = srcTAG.ToString("dd.MM")
                End If

                'End If
            Case ""
                DateTimePicker1.Value = ("01." & Now.Month & "." & Now.Year)
                DateTimePicker2.Value = Now
        End Select

    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        srcTAG = srcTAG.AddDays(-1)
        initBtns("Tag")
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        srcTAG = srcTAG.AddDays(1)
        initBtns("Tag")
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        initBtns("Tag")
    End Sub

    Private Sub btnJahr_Click(sender As Object, e As EventArgs) Handles btnJahr.Click
        initBtns("Jahr")
    End Sub

    Private Sub btnBisMonat_Click(sender As Object, e As EventArgs) Handles btnBisMonat.Click
        MONAT = MONAT.AddMonths(1)
        initBtns("Monat")
    End Sub

    Private Sub btnVonMonat_Click(sender As Object, e As EventArgs) Handles btnVonMonat.Click
        MONAT = MONAT.AddMonths(-1)
        initBtns("Monat")
    End Sub

    Private Sub btnBisJahr_Click(sender As Object, e As EventArgs) Handles btnBisJahr.Click
        JAHR = JAHR.AddYears(1)
        initBtns("Jahr")
    End Sub

    Private Sub btnVonJahr_Click(sender As Object, e As EventArgs) Handles btnVonJahr.Click
        JAHR = JAHR.AddYears(-1)
        initBtns("Jahr")
    End Sub

    Private Sub txtAbfertDat_TextChanged(sender As Object, e As EventArgs) Handles txtAbfertDat.Leave
        If sender.Text <> "" AndAlso IsDate(sender.Text) Then
            DateTimePicker1.Value = CDate(sender.text)
        End If
    End Sub
    Private Sub txtAbfertDatbis_TextChanged(sender As Object, e As EventArgs) Handles txtAbfertDatBis.Leave
        If sender.Text <> "" AndAlso IsDate(sender.Text) Then
            DateTimePicker2.Value = CDate(sender.text)
        End If
    End Sub


End Class