Imports System.Windows.Documents
Imports com.sun.org.apache.bcel.internal.generic
Imports MDM_Worker
Imports VERAG_PROG_ALLGEMEIN

Public Class frmUSTVoffeneAntraege

    Public LIEFERANT = ""
    Dim datumBis As Date = Nothing
    Dim datumVon As Date = Nothing
    Dim kdNr As Integer = -1
    Dim kdName As String
    Dim dtkeineMWST As DataTable
    Dim dtKundeMWST As DataTable
    Dim dTLANDEU As DataTable
    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        initLieferant("PLOSE", sender)
    End Sub

    Sub New(datumVon_ As Date, datumBis_ As Date)
        datumVon = datumVon_
        datumBis = datumBis_

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

        dat_Sum_Von.Value = datumVon
        dat_Sum_Bis.Value = datumBis

    End Sub

    Sub New(datumVon_ As Date, datumBis_ As Date, kdnr_ As Integer, kdName_ As String)
        datumVon = datumVon_
        datumBis = datumBis_

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

        dat_Sum_Von.Value = datumVon
        dat_Sum_Bis.Value = datumBis
        kdNr = kdnr_
        kdName = kdName_

        lblKunde.Text = kdNr & " " & kdName
    End Sub

    Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

        lblKunde.Text = " "

    End Sub

    Private Sub initLieferant(l As String, btn As Button)

        pnlLand.Visible = False
        cbxKundenMWST.Visible = False

        MyDatagridview1.DataSource = Nothing
        Me.LIEFERANT = l

        If Me.LIEFERANT = "PLOSE" Then

            Dim sqlString = "SELECT COUNT(*) FROM[VERAG].[dbo].[tblPLOSE_Inv_Data] where plInv_SupplierRechnungsNr like 'SE%' and plInv_SupplierCountry = 'DK'"
            Dim countDK_PLOSE = (New SQL).getValueTxtBySql(sqlString, "FMZOLL")
            If countDK_PLOSE <> "" AndAlso IsNumeric(countDK_PLOSE) AndAlso CInt(countDK_PLOSE) > 0 Then
                btnPLOSE_DK.Visible = True

            Else
                btnPLOSE_DK.Visible = False
            End If
        Else
            btnPLOSE_DK.Visible = False

        End If

        For Each c As Button In FlowLayoutPanel.Controls
            If c Is btn Then
                c.BackColor = Color.Wheat
            Else
                c.BackColor = Color.FloralWhite
            End If
        Next

        pnlLand.Visible = Me.LIEFERANT = "alle"
        cbxKundenMWST.Visible = Me.LIEFERANT = "alle"

        init()

    End Sub

    Private Sub setPDFICON(dgv As DataGridView, dgvCellNameMWST As String, dgvCellNameDSID As String, ByRef sumMWST As Double)

        Dim c As New DataGridViewImageColumn
        c.Name = "clmnPDF" : c.HeaderText = "RE"
        '    c.Image = Nothing
        c.DefaultCellStyle.NullValue = Nothing
        c.ImageLayout = DataGridViewImageCellLayout.Zoom
        c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
        'c.DefaultCellStyle.Tag = "Therefore anzeigen"

        If Not dgv.Columns.Contains("clmnPDF") Then dgv.Columns.Add(c)

        Dim pdfImg As Image = My.Resources.pdf

        For Each r As DataGridViewRow In dgv.Rows
            If Not r.IsNewRow Then

                ' Wert lokal zwischenspeichern (vermeidet DGV-Overhead)
                Dim mwstObj = r.Cells(dgvCellNameMWST).Value
                Dim daIdObj = r.Cells(dgvCellNameDSID).Value

                ' Summe berechnen
                Dim mwst As Double
                If Double.TryParse(Convert.ToString(mwstObj), mwst) Then
                    sumMWST += mwst
                End If

                ' PDF setzen

                If daIdObj IsNot Nothing AndAlso
                   Not IsDBNull(daIdObj) AndAlso
                   Convert.ToInt32(daIdObj) > 0 Then

                    r.Cells("clmnPDF").Value = pdfImg
                End If

            End If
        Next
    End Sub

    Sub initDgv_PLOSE(anz As Integer, Optional kdnr As Integer = -1)


        With MyDatagridview1
            .Columns.Clear()


            Dim top = ""
            If anz > 0 Then top = "TOP (" & anz & ")"

            Dim sqlwhere = ""

            If kdnr > 0 Then
                sqlwhere &= " and Adressen.AdressenNr = " & kdnr
            End If

            Dim sqlString = "Select " & top & " Adressen.AdressenNr, Adressen.[Name 1] ,[plose_Lieferant],[plose_RechnungsDatum],[plose_RechnungsNr],plp_Land, sum([plose_MWSTBetrag])[plose_MWSTBetrag], [plInv_daId] As daId FROM [tblPLOSE_Details]  
                    INNER Join Adressen on PLOSEKundenNr=plose_POLSEKundennummer
                    INNER Join [tblPLOSE_Produktbeschreibung] ON [plp_ProductCode]=[plose_ProduktCode]
                    INNER Join [tblPLOSE_Inv_Data] on tblPLOSE_Details .plose_plInvId = plInv_Id
                    WHERE UStVAn_ID Is null /* plose_Archiv <> 1 And plose_LieferantCode In (0, 1, 7) */ And  cast(plose_RechnungsDatum as date) between '" & dat_Sum_Von.Value & "' and '" & dat_Sum_Bis.Value & "' and plose_RechnungsNr is not null " & sqlwhere &
                    "group by  Adressen.AdressenNr, Adressen.[Name 1] ,[plose_RechnungsDatum],[plose_RechnungsNr],[plose_Lieferant], plp_Land, [plInv_daId]
                    having sum(plose_MWSTBetrag) <>0"

            Dim year = CDate(dat_Sum_Von.Value).Year

            If year >= 2025 Then

                sqlString = "Select " & top & "  Adressen.AdressenNr, Adressen.[Name 1] ,[plInv_Lieferant] as plose_Lieferant,[plInv_SupplierRechnungsDatum] as plose_RechnungsDatum,[plInv_SupplierRechnungsNr] as plose_RechnungsNr,[plInv_SupplierCountry] as plp_Land, sum([plInv_MWSTBetrag]) as plose_MWSTBetrag , [plInv_daId] As daId FROM [tblPLOSE_Inv_Data]  
                    INNER JOIN Adressen on PLOSEKundenNr=[plInv_PLOSEKundennummer]
                    WHERE plInv_UStVAn_ID Is null /* plose_Archiv <> 1 And plose_LieferantCode In (0, 1, 7) */ And  cast([plInv_SupplierRechnungsDatum] as date) between '" & dat_Sum_Von.Value & "' and '" & dat_Sum_Bis.Value & "' and [plInv_SupplierRechnungsNr] is not null " & sqlwhere &
                   "group by  Adressen.AdressenNr, Adressen.[Name 1] ,[plInv_SupplierRechnungsDatum],[plInv_SupplierRechnungsNr],[plInv_Lieferant], [plInv_SupplierCountry], [plInv_daId]
                    having sum([plInv_MWSTBetrag]) <>0"


            End If


            .SET_SQL(sqlString, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("AdressenNr").HeaderText = "KdNr"
                .Columns("Name 1").HeaderText = "Kunde"
                .Columns("plose_Lieferant").HeaderText = "PLOSE-Lieferant"
                .Columns("plose_RechnungsDatum").HeaderText = "RE-Datum"
                .Columns("plose_RechnungsNr").HeaderText = "RE-Nr"
                .Columns("plp_Land").HeaderText = "Land"
                .Columns("Name 1").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("plose_MWSTBetrag").HeaderText = "MWST"
                .Columns("daId").Visible = False

                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumMwSt As Double = 0

            setPDFICON(MyDatagridview1, "plose_MWSTBetrag", "daId", sumMwSt)

            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt

            .ClearSelection()

        End With

    End Sub

    Sub initDgv_RMC(anz As Integer, Optional kdnr As Integer = -1)

        Dim top = ""
        If anz > 0 Then top = "TOP (" & anz & ")"

        Dim sqlwhere = ""

        If kdnr > 0 Then
            sqlwhere &= " and Adressen.AdressenNr = " & kdnr
        End If


        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)


            Dim sqlstring = "Select " & top & " [rmc_kdNr], [rmc_kdName], [rmc_landKZ], [rmc_reDatum], [rmc_reNr], [rmc_waehrung], [rmc_betragMWST],rmc_daid as daId  FROM [tblRMCImport]
                        INNER JOIN Adressen on WölflKundenNr=[rmc_kdNr] 
                        where rmc_reDatum >= '" & dat_Sum_Von.Value & "' And rmc_reDatum <= '" & dat_Sum_Bis.Value & "'  And rmc_archiv <> 1 AND [rmc_betragMWST] <> 0 " & sqlwhere

            sqlstring &= " UNION ALL Select " & top & " [rmc_kdNr], [rmc_kdName], [rmc_landKZ], [rmc_reDatum], [rmc_reNr], [rmc_waehrung], [rmc_betragMWST],rmc_daid as daId  FROM [tblRMCImport]
                        INNER JOIN Adressen on weitereWölflKundenNr=[rmc_kdNr]
                        where rmc_reDatum >= '" & dat_Sum_Von.Value & "' And rmc_reDatum <= '" & dat_Sum_Bis.Value & "'  And rmc_archiv <> 1 AND [rmc_betragMWST] <> 0 " & sqlwhere

            .SET_SQL(sqlstring, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("rmc_kdNr").HeaderText = "KdNr"
                .Columns("rmc_kdName").HeaderText = "Kunde"
                .Columns("rmc_landKZ").HeaderText = "Land"
                .Columns("rmc_reDatum").HeaderText = "RE-Datum"
                .Columns("rmc_reNr").HeaderText = "RE-Nr"
                .Columns("rmc_betragMWST").HeaderText = "MWSt"
                .Columns("rmc_waehrung").HeaderText = "Währung"
                .Columns("daId").Visible = False
                .Columns("rmc_kdName").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumMwSt As Double = 0

            setPDFICON(MyDatagridview1, "rmc_betragMWST", "daId", sumMwSt)

            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt


        End With

    End Sub

    Sub initDgv_MSE(anz As Integer, Optional kdnr As Integer = -1)

        Dim top = ""
        If anz > 0 Then top = "TOP (" & anz & ")"
        Dim sqlwhere = ""

        If kdnr > 0 Then
            sqlwhere &= " and partner_customer_number = " & kdnr
        End If

        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)
            Dim sqlstring = "Select " & top & " customer_number, customer_name, country, invoice_date, invoice_id, sum(total_amount_euro) as total_amount_euro, sum(total_vat_amount_euro) as total_vat_amount_euro, daId  FROM [VERAG].[dbo].[tblMSEInvoices] inner join [tblMSECustomers] on [customer_number] = [customer_id]  
                        where cast(invoice_date As Date) between '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' And [UStVAn_ID] is null " & sqlwhere &
                        "group by  invoice_date, customer_number,customer_name, country, invoice_id, daId having sum(total_vat_amount_euro) <> 0"

            .SET_SQL(sqlstring, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("customer_number").HeaderText = "KdNr"
                .Columns("customer_name").HeaderText = "Kunde"
                .Columns("country").HeaderText = "Land"
                .Columns("invoice_date").HeaderText = "RE-Datum"
                .Columns("invoice_id").HeaderText = "RE-Nr"
                .Columns("total_amount_euro").HeaderText = "Gesamtsumme Euro"
                .Columns("total_vat_amount_euro").HeaderText = "MWSt Euro"
                .Columns("daId").Visible = False
                .Columns("customer_name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumMwSt As Double = 0

            Dim c As New DataGridViewImageColumn
            c.Name = "clmnPDF" : c.HeaderText = "RE"
            '    c.Image = Nothing
            c.DefaultCellStyle.NullValue = Nothing
            c.ImageLayout = DataGridViewImageCellLayout.Zoom
            c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
            'c.DefaultCellStyle.Tag = "Therefore anzeigen"

            If Not .Columns.Contains("clmnPDF") Then .Columns.Add(c)

            'For Each r As DataGridViewRow In .Rows
            '    sumMwSt += If(IsNumeric(r.Cells("total_vat_amount_euro").Value), CDbl(r.Cells("total_vat_amount_euro").Value), 0)

            '    If Not IsDBNull(r.Cells("daId").Value) AndAlso r.Cells("daId").Value > 0 Then DirectCast(r.Cells("clmnPDF"), DataGridViewImageCell).Value = My.Resources.pdf

            'Next

            setPDFICON(MyDatagridview1, "total_vat_amount_euro", "daId", sumMwSt)

            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt




        End With

    End Sub

    Sub initDgv_UTA(anz As Integer, Optional kdnr As Integer = -1)

        Dim top = ""
        If anz > 0 Then top = "TOP (" & anz & ")"

        Dim sqlwhere = ""
        If kdnr > 0 Then
            sqlwhere &= " and AdressenNr = " & kdnr
        End If


        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)
            Dim sqlstring = "Select " & top & " Adressen.AdressenNr as KdNr,Adressen.[Name 1],[Lieferland_ISO2],Abrechnungsnummer, [Rechnungsdatum] AS Rechnungsdatum, sum([Gesamtbetrag_Brutto_in_Darstellwährung]) as [Gesamtbetrag_Brutto_in_Darstellwährung], sum([Gesamtbetrag_Umsatzsteuer_in_Darstellwährung]) as [Gesamtbetrag_Umsatzsteuer_in_Darstellwährung], daId  
                        FROM [tblUTAImportNew] 
                        INNER JOIN Adressen on Adressen.UTAKundenNr = tblUTAImportNew.Kundennummer
                        where cast([Rechnungsdatum] As Date) between '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' And [tblUTAImportNew].UStVAn_ID is null " & sqlwhere &
" group by Adressen.AdressenNr,Adressen.[Name 1],Abrechnungsnummer,[Rechnungsdatum], [Lieferland_ISO2], daId having sum([Gesamtbetrag_Umsatzsteuer_in_Darstellwährung]) <> 0 "

            .SET_SQL(sqlstring, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("KdNr").HeaderText = "KdNr"
                .Columns("Name 1").HeaderText = "Kunde"
                .Columns("Lieferland_ISO2").HeaderText = "Land"
                .Columns("Rechnungsdatum").HeaderText = "RE-Datum"
                .Columns("Abrechnungsnummer").HeaderText = "RE-Nr"
                .Columns("Gesamtbetrag_Brutto_in_Darstellwährung").HeaderText = "Gesamtsumme Euro"
                .Columns("Gesamtbetrag_Umsatzsteuer_in_Darstellwährung").HeaderText = "MWSt Euro"
                .Columns("daId").Visible = False
                .Columns("Name 1").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            End If
            Dim sumMwSt As Double = 0

            setPDFICON(MyDatagridview1, "Gesamtbetrag_Umsatzsteuer_in_Darstellwährung", "daId", sumMwSt)

            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt
        End With

    End Sub
    Sub initDgv_IDS(anz As Integer, Optional kdnr As Integer = -1)
        Dim top = ""
        If anz > 0 Then top = "TOP (" & anz & ")"
        Dim sqlwhere = ""
        If kdnr > 0 Then
            sqlwhere &= " and tblIDSTransactionsNew.KdNrVERAG = " & kdnr
        End If
        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)
            Dim sqlstring = "SELECT " & top & "
                           tblIDSTransactionsNew.KdNrVERAG,
                           Adressen.[Name 1],
                           tbl_IDS_Länder.OutletCountry as Land,
                           tblIDSTransactionsNew.[YearMonthDay] AS Rechnungsdatum,
                           ISNULL(tblIDSTransactionsNew.[OBONumber],ISNULL(tblIDSTransactionsNew.[VRNumber], tblIDSTransactionsNew.[Paymentsummarynumber])) AS Rechnungsnummer,
                           SUM(tblIDSTransactionsNew.[VATAmount]) AS Steuerbetrag,
                           isNULL(tblIDSInvoicesNew.daId,0) as daId
                       FROM 
                           tblIDSTransactionsNew 
                       INNER JOIN 
                           tbl_IDS_Länder 
                           ON tblIDSTransactionsNew.[OutletCountryCode] = tbl_IDS_Länder.OutletCountryCode
                       INNER JOIN
                           Adressen on Adressen.AdressenNr = tblIDSTransactionsNew.KdNrVERAG
                       LEFT JOIN 
                       	tblIDSInvoicesNew on tblIDSInvoicesNew.CustomerCode = tblIDSTransactionsNew.CustomerCode and tblIDSInvoicesNew.Invoicenumber = Paymentsummarynumber
                       WHERE  
                           tblIDSTransactionsNew.[YearMonthDay] BETWEEN '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' " & sqlwhere & "
                            AND tblIDSTransactionsNew.[VATAmount] <> 0 
                           AND tblIDSTransactionsNew.UStVAn_ID IS NULL
                       GROUP BY 
                           tblIDSTransactionsNew.KdNrVERAG,
                           Adressen.[Name 1],
                           tbl_IDS_Länder.OutletCountry,
                           tblIDSTransactionsNew.[YearMonthDay], 
                           ISNULL(tblIDSTransactionsNew.[OBONumber], 
                           ISNULL(tblIDSTransactionsNew.[VRNumber], tblIDSTransactionsNew.[Paymentsummarynumber])),
                           tblIDSInvoicesNew.daId
                       ORDER BY 
                           tblIDSTransactionsNew.KdNrVERAG,
                           tblIDSTransactionsNew.[YearMonthDay], 
                           ISNULL(tblIDSTransactionsNew.[OBONumber], 
                           ISNULL(tblIDSTransactionsNew.[VRNumber], tblIDSTransactionsNew.[Paymentsummarynumber]));"
            .SET_SQL(sqlstring, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("KdNrVERAG").HeaderText = "KdNr"
                .Columns("Name 1").HeaderText = "Kunde"
                .Columns("Land").HeaderText = "Land"
                .Columns("Rechnungsdatum").HeaderText = "RE-Datum"
                .Columns("Rechnungsnummer").HeaderText = "RE-Nr"
                .Columns("Steuerbetrag").HeaderText = "MWSt Euro"
                .Columns("daId").Visible = False
                .Columns("Name 1").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumMwSt As Double = 0

            setPDFICON(MyDatagridview1, "Steuerbetrag", "daId", sumMwSt)

            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt


        End With

    End Sub

    Sub initDgv_VERAG(anz As Integer, Optional kdnr As Integer = -1)
        Dim top = ""
        If anz > 0 Then top = "TOP (" & anz & ")"
        Dim sqlwhere = ""
        If kdnr > 0 Then
            sqlwhere &= " AND tblTrdinInvoice.RechnungsKundenNr = " & kdnr
        End If
        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)
            Dim sqlstring = "SELECT " & top & "
                            tblTrdinInvoice.RechnungsKundenNr,
                            Adressen.[Name 1],
                            tblTrdinInvoice.Rechnungsdatum,
                            'AT' as Land,
                            tblTrdinInvoice.Rechnungsnummer, 
                            tblTrdinInvoice.SteuerbetragLokal 
                            FROM tblTrdinInvoice
                            inner join Adressen on Adressen.AdressenNr = tblTrdinInvoice.RechnungsKundenNr
                            WHERE tblTrdinInvoice.Rechnungsdatum Between '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' AND tblTrdinInvoice.SteuerbetragLokal<>0 AND tblTrdinInvoice.UStVAn_ID is null And Firma_ID = 19 AND tblTrdinInvoice.WährungLokal='EUR' " & sqlwhere & "
                            ORDER BY tblTrdinInvoice.Rechnungsdatum, tblTrdinInvoice.Rechnungsnummer"
            .SET_SQL(sqlstring, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("RechnungsKundenNr").HeaderText = "KdNr"
                .Columns("Name 1").HeaderText = "Kunde"
                .Columns("Land").HeaderText = "Land"
                .Columns("Rechnungsdatum").HeaderText = "RE-Datum"
                .Columns("Rechnungsnummer").HeaderText = "RE-Nr"
                .Columns("SteuerbetragLokal").HeaderText = "MWSt Euro"
                .Columns("Name 1").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            End If

            Dim sumMwSt As Double = 0

            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt


        End With

    End Sub

    Sub initDgv_gesamt(anz As Integer, nichtEroeffneteAntraege As Boolean, Optional kdnr As Integer = -1)

        Dim top = ""
        'If anz > 0 Then top = "TOP (" & anz & ")"

        Dim sqlwhereIDS = ""
        Dim sqlwhereVERAG = ""
        Dim sqlwhereUTA = ""
        Dim sqlwhereRMC = ""
        Dim sqlwherePLOSE = ""
        Dim sqlwhereMSE = ""
        Dim sqlwhereLand = ""
        Dim sqlwhereSteuerNr = ""
        Dim sqlwhereLieferant = ""

        Dim kundenLandISO2 As String = ""

        Dim SQLPLOSEUMSTELLUNG = ""

        Dim year = CDate(dat_Sum_Von.Value).Year

        If kdnr > 0 Then
            sqlwherePLOSE &= " and AdressenNr = " & kdnr 'sqlwherePLOSE &= " and plose_POLSEKundennummer = " & kdnr
            sqlwhereIDS &= " and AdressenNr = " & kdnr 'sqlwhereIDS &= " and tblIDSTransactionsNew.KdNrVERAG = " & kdnr
            sqlwhereUTA &= " and AdressenNr = " & kdnr
            sqlwhereVERAG &= " and AdressenNr = " & kdnr
            sqlwhereRMC &= " and Adressen.AdressenNr = " & kdnr
            sqlwhereMSE &= " and partner_customer_number = " & kdnr
        End If

        If MyComboBox1._value <> "" Then
            sqlwhereLand &= " and Einreichland = '" & MyComboBox1._value & "'"
        End If

        If cbxKundeLand._value <> "" Then
            sqlwhereLand &= " and Kundenland = '" & cbxKundeLand._value & "'"
            'LandKZ vom Kunden muss auf ISO2 konvertiert werden, weil da ein Misch-Masch in der Datenbank herrscht!
            If cbxKundeLand._value.Length = 2 Then
                kundenLandISO2 = cbxKundeLand._value
            ElseIf cbxKundeLand._value.Length = 3 Then
                kundenLandISO2 = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromISO3Land(cbxKundeLand._value)
            ElseIf cbxKundeLand._value.Length = 1 Then
                kundenLandISO2 = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2LandFromISO1Land(cbxKundeLand._value)
            End If

        End If

        If cbxLieferant._value <> "" Then
            sqlwhereLieferant &= " and Lieferant = '" & cbxLieferant._value & "'"
        End If


        If cbxUStV.Checked Then
            sqlwhereSteuerNr &= " and isnull(tblSteuernummern.UStV,0) <> 0"
        End If

        If nichtEroeffneteAntraege Then
            sqlwhereLand &= " and isnull(UStVAn_ID,0) = 0 "
        End If



        If dtkeineMWST.Rows.Count > 0 AndAlso kundenLandISO2 <> "" Then


            Dim rows = dtkeineMWST.AsEnumerable().Where(Function(res) res.Field(Of String)("Land") = kundenLandISO2 And res.Field(Of String)("Lieferant") <> "IDS")

            If (rows.Any()) Then
                Dim dtkeineMWST_ohneContraint As DataTable = rows.CopyToDataTable
                Dim counter = 0
                Dim landBez As String = ""
                For Each row As DataRow In dtkeineMWST_ohneContraint.Rows
                    landBez &= "'" & row.Item("Erstattungsland") & "'"
                    counter = counter + 1
                    If (dtkeineMWST_ohneContraint.Rows.Count <> 0 And counter <> dtkeineMWST_ohneContraint.Rows.Count) Then landBez &= ","
                Next
                sqlwhereLand &= " AND Einreichland not in (" & landBez & ")"


                'eig soll nur PLOSE Datensätze bei nicht EU-Kunden angezeigt werden (also bei NICHT EU -> IDS weg (nur IDS-AT)!!!!!!!!!!
                Dim isEU As Boolean = dTLANDEU.AsEnumerable().Where(Function(res) res.Field(Of String)("LandKz") = kundenLandISO2).Select(Function(res) res.Field(Of Boolean)("MitgliedslandEU")).FirstOrDefault()

                If Not isEU Then
                    Dim rowsIDS = dtkeineMWST.AsEnumerable().Where(Function(res) res.Field(Of String)("Land") = kundenLandISO2 And res.Field(Of String)("Lieferant") = "IDS")

                    If (rowsIDS.Any()) Then
                        Dim dtkeineMWST_ohneContraintIDS As DataTable = rowsIDS.CopyToDataTable
                        Dim counterIDS = 0
                        Dim landBezIDS As String = ""
                        If dtkeineMWST_ohneContraintIDS.Rows.Count > 0 Then
                            For Each row As DataRow In dtkeineMWST_ohneContraintIDS.Rows
                                landBezIDS &= "'" & row.Item("Erstattungsland") & "'"
                                counterIDS = counterIDS + 1
                                If (dtkeineMWST_ohneContraintIDS.Rows.Count <> 0 And counterIDS <> dtkeineMWST_ohneContraintIDS.Rows.Count) Then landBezIDS &= ","
                            Next
                            sqlwhereIDS &= " AND tbl_IDS_Länder.Lieferland_ISO2 not in (" & landBezIDS & ")"
                        End If

                    End If

                End If

            End If
        End If




        If cbxKundenMWST.Checked Then
            If dtKundeMWST.Rows.Count > 0 Then
                Dim counter = 0
                Dim landBez As String = ""
                Dim klammer = ""
                'klammer &= IIf(dtKundeMWST.Rows.Count > 0, "OR AdressenNr > -1 ", "")
                For Each t In dtKundeMWST.Rows
                    'klammer &= ")"
                Next

                If dtKundeMWST.Columns.Contains("KdNr") Then

                    'bei Einstellung "ALLE KUNDEN"

                    If dtKundeMWST.Rows.Count > 0 Then sqlwhereLand &= " AND NOT EXISTS (SELECT 1 FROM (VALUES "

                    For Each row As DataRow In dtKundeMWST.Rows
                        '    landBez = row.Item("abc").ToString.Replace(";", "'")
                        '    counter = counter + 1
                        '    sqlwhereLand &= " (" & row.Item("KdNr") & "," & landBez.ToString.Substring(0, landBez.ToString.Length - 1) & ") " & IIf(dtKundeMWST.Rows.Count <> 0 And counter <> dtKundeMWST.Rows.Count, ", ", ") AS Excluded(AdressenNr, Einreichland) WHERE Excluded.AdressenNr = temp.KdNr AND Excluded.Einreichland = temp.Einreichland)")
                        'Next

                        Dim kdNr_ As String = row("KdNr").ToString()
                        Dim landBez_ As String = row("abc").ToString()

                        ' Entferne führende/mehrfache Semikolons
                        landBez_ = landBez_.Replace(";;", ";").Trim(";"c, " "c)

                        ' Teile die Länder anhand von „;,;“
                        Dim laender() As String = landBez_.Split(New String() {",,"}, StringSplitOptions.None)

                        ' Fallback: wenn nur einfache Trennung mit „;,“
                        If laender.Length = 1 Then
                            laender = landBez_.Split(New String() {",;"}, StringSplitOptions.RemoveEmptyEntries)
                        End If

                        ' Jede gültige Länderkombination hinzufügen
                        For Each land In landBez_.Split(New String() {",;"}, StringSplitOptions.RemoveEmptyEntries)
                            land = land.Replace(";", "").Trim()
                            If land <> "" Then
                                Dim landTemp As String = land.Replace(",", "")
                                counter += 1
                                sqlwhereLand &= "(" & kdNr_ & ", '" & landTemp & "'), "
                            End If
                        Next
                    Next

                    If sqlwhereLand.EndsWith(", ") Then
                        sqlwhereLand = sqlwhereLand.Substring(0, sqlwhereLand.Length - 2)
                    End If

                    ' Abschluss der NOT EXISTS-Klausel
                    sqlwhereLand &= ") AS Excluded(AdressenNr, Einreichland) " &
                    "WHERE Excluded.AdressenNr = temp.KdNr " &
                    "AND Excluded.Einreichland = temp.Einreichland)"



                Else

                    'bei Einstellung "SPEZIFISCHER KUNDE"

                    For Each row As DataRow In dtKundeMWST.Rows
                        landBez &= "'" & row.Item("LandKz") & "'"
                        counter = counter + 1
                        If (dtKundeMWST.Rows.Count <> 0 And counter <> dtKundeMWST.Rows.Count) Then landBez &= ","
                    Next
                    sqlwhereLand &= " AND Einreichland not in (" & landBez & ")"

                End If
            End If

        End If





        If year >= 2025 Then

            SQLPLOSEUMSTELLUNG = "

                select " & top & "
					'PLOSE' as Lieferant,
					Adressen.AdressenNr as KdNr, 
					Adressen.[Name 1] as Kundenname,
                    Adressen.LandKz as Kundenland,
					[plInv_SupplierCountry] as Einreichland,
					[plInv_SupplierRechnungsDatum] AS Rechnungsdatum,
					 sum([plInv_MWSTBetrag]) as MWST
					 FROM [tblPLOSE_Inv_Data]
					 INNER JOIN Adressen on PLOSEKundenNr=plInv_PLOSEKundennummer
                    WHERE  plInv_Archiv <> 1 AND cast(plInv_SupplierRechnungsDatum as date) between '" & dat_Sum_Von.Value & "' and '" & dat_Sum_Bis.Value & "' and plInv_SupplierRechnungsNr is not null  " & sqlwherePLOSE & "
					group by  Adressen.AdressenNr, Adressen.[Name 1],Adressen.LandKz ,[plInv_SupplierRechnungsDatum],[plInv_SupplierCountry]
                    having sum(plInv_MWSTBetrag)<>0"
        Else
            SQLPLOSEUMSTELLUNG = "select " & top & "
					'PLOSE' as Lieferant,
					Adressen.AdressenNr as KdNr, 
					Adressen.[Name 1] as Kundenname,
                    Adressen.LandKz as Kundenland,
					[plp_Land] as Einreichland,
					[plose_RechnungsDatum] AS Rechnungsdatum,
					 sum([plose_MWSTBetrag]) as MWST
					 FROM [tblPLOSE_Details]  
					 INNER JOIN Adressen on PLOSEKundenNr=plose_POLSEKundennummer
                     INNER JOIN [tblPLOSE_Produktbeschreibung] ON [plp_ProductCode]=[plose_ProduktCode]
                     INNER JOIN [tblPLOSE_Inv_Data] on tblPLOSE_Details .plose_plInvId = plInv_Id
                    WHERE plose_Archiv <> 1 /*AND plose_LieferantCode IN (0,1,7) */ AND 
					cast(plose_RechnungsDatum as date) between '" & dat_Sum_Von.Value & "' and '" & dat_Sum_Bis.Value & "' and plose_RechnungsNr is not null  " & sqlwherePLOSE & "
					group by  Adressen.AdressenNr, Adressen.[Name 1],Adressen.LandKz ,[plose_RechnungsDatum],[plp_Land]
                    having sum(plose_MWSTBetrag)<>0"


        End If


        With MyDatagridview1
            .Columns.Clear()
            'Exit Sub
            'MsgBox(.sql)



            Dim sqlstring = "select isnull(UStVAn_ID,0) as antragExisitiert,cast(case when UStVAn_AntragEingereichtAm IS NULL THEN 0 else 1 end as bit) as eingereicht,isnull(tblSteuernummern.UStV,0) as UStV,Lieferant , KdNr, Kundenname, Kundenland, Einreichland from (" & SQLPLOSEUMSTELLUNG & "

					UNION ALL

					Select " & top & "
					'RMC' as Lieferant,
					Adressen.AdressenNr as KdNr, 
					Adressen.[Name 1] as Kundenname,
                    Adressen.LandKz as Kundenland,
					[rmc_landKZ] as Einreichland, 
					[rmc_reDatum] AS Rechnungsdatum,
					[rmc_betragMWST] as MWST
					FROM [tblRMCImport]
                    INNER JOIN Adressen on WölflKundenNr= [rmc_kdNr] 
                    where rmc_reDatum >= '" & dat_Sum_Von.Value & "' And rmc_reDatum <= '" & dat_Sum_Bis.Value & "' 
					And UStVAn_ID is null  " & sqlwhereRMC & "
					AND [rmc_betragMWST] <> 0

                    UNION ALL

					Select " & top & "
					'RMC' as Lieferant,
					Adressen.AdressenNr as KdNr, 
					Adressen.[Name 1] as Kundenname,
                    Adressen.LandKz as Kundenland,
					[rmc_landKZ] as Einreichland, 
					[rmc_reDatum] AS Rechnungsdatum,
					[rmc_betragMWST] as MWST
					FROM [tblRMCImport]
                    INNER JOIN Adressen on weitereWölflKundenNr=[rmc_kdNr]
                    where rmc_reDatum >= '" & dat_Sum_Von.Value & "' And rmc_reDatum <= '" & dat_Sum_Bis.Value & "' 
					And UStVAn_ID is null  " & sqlwhereRMC & "
					AND [rmc_betragMWST] <> 0
					 
					UNION ALL

					Select " & top & "
					'UTA' as Lieferant,
					Adressen.AdressenNr as KdNr,
					Adressen.[Name 1] as Kundenname, 
                    Adressen.LandKz as Kundenland,
					[Lieferland_ISO2] as Einreichland, 
					[Rechnungsdatum] AS Rechnungsdatum,
					sum([Gesamtbetrag_Umsatzsteuer_in_Darstellwährung]) as MWSt
                    FROM [tblUTAImportNew] 
                    INNER JOIN Adressen on Adressen.UTAKundenNr = tblUTAImportNew.Kundennummer
                    where cast([Rechnungsdatum] As Date) between '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' And [tblUTAImportNew].UStVAn_ID is null 
					" & sqlwhereUTA & "group by Adressen.AdressenNr,  Kundennummer,Adressen.[Name 1],Adressen.LandKz ,[Rechnungsdatum], [Lieferland_ISO2] having sum([Gesamtbetrag_Umsatzsteuer_in_Darstellwährung]) <> 0

                    UNION ALL

                    Select " & top & "
					'VERAG' as Lieferant,
					tblTrdinInvoice.RechnungsKundenNr as KdNr,
					Adressen.[Name 1] as Kundenname, 
                    Adressen.LandKz as Kundenland,
					'AT'as Einreichland, 
					tblTrdinInvoice.Rechnungsdatum,
					sum(tblTrdinInvoice.SteuerbetragLokal) as MWSt
                    FROM [tblTrdinInvoice] 
                    inner join Adressen on Adressen.AdressenNr = tblTrdinInvoice.RechnungsKundenNr
                    where tblTrdinInvoice.Rechnungsdatum Between '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' AND tblTrdinInvoice.UStVAn_ID is null And Firma_ID = 19
					" & sqlwhereVERAG & "group by Adressen.AdressenNr,  tblTrdinInvoice.RechnungsKundenNr,Adressen.[Name 1],Adressen.LandKz ,[Rechnungsdatum]  having sum(tblTrdinInvoice.SteuerbetragLokal) <> 0

					UNION ALL

					Select " & top & "
					'MSE' as Lieferant,
					partner_customer_number as KdNr,
					 customer_name as Kundenname,
					 Adressen.LandKz as Kundenland, 
					 country  as Einreichland,
					 invoice_date AS Rechnungsdatum,
					 sum(total_vat_amount_euro) as MWST
					FROM [VERAG].[dbo].[tblMSEInvoices] inner join [tblMSECustomers] on [customer_number] = [customer_id] INNER JOIN Adressen on Adressen.MSEKundenNr = [customer_number]  

                    where cast(invoice_date As Date) between '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' 
					
					And [UStVAn_ID] is null  " & sqlwhereMSE & "
					
					group by  invoice_date, partner_customer_number,customer_name,Adressen.LandKz, country having sum(total_vat_amount_euro) <> 0

					UNION ALL

					--IDS
					SELECT " & top & "
					'IDS' as Lieferant,
                        tblIDSTransactionsNew.KdNrVERAG as KdNr,
                        Adressen.[Name 1] as Kundenname,
                    Adressen.LandKz as Kundenland,
                        tbl_IDS_Länder.Lieferland_ISO2 as Einreichland,
					   cast(tblIDSTransactionsNew.[YearMonthDay] as date) AS Rechnungsdatum,
					   SUM(tblIDSTransactionsNew.[VATAmount]) AS MWST
                    FROM 
                        tblIDSTransactionsNew 
                    INNER JOIN 
                        tbl_IDS_Länder 
                        ON tblIDSTransactionsNew.[OutletCountryCode] = tbl_IDS_Länder.OutletCountryCode
                    INNER JOIN
                        Adressen on Adressen.AdressenNr = tblIDSTransactionsNew.KdNrVERAG
                    LEFT JOIN 
                    	tblIDSInvoicesNew on tblIDSInvoicesNew.CustomerCode = tblIDSTransactionsNew.CustomerCode and tblIDSInvoicesNew.Invoicenumber = Paymentsummarynumber
                    WHERE  
                        tblIDSTransactionsNew.[YearMonthDay] BETWEEN '" & dat_Sum_Von.Value & "' And '" & dat_Sum_Bis.Value & "' " & sqlwhereIDS & "
                         AND tblIDSTransactionsNew.[VATAmount] <> 0 
                        AND tblIDSTransactionsNew.UStVAn_ID IS NULL
                    GROUP BY 
                        tblIDSTransactionsNew.KdNrVERAG,
                        Adressen.[Name 1],
                        Adressen.LandKz,
                        tbl_IDS_Länder.Lieferland_ISO2,
                        tblIDSTransactionsNew.[YearMonthDay] ) as temp 
                        inner join tblKundenErweitert on  temp.kdnr = kde_KundenNr 
                        inner join [Länderverzeichnis für die Außenhandelsstatistik] on temp.Einreichland=LandKz
						left join tblUStVAntrag on UStVAn_KuNr = temp.kdnr and UStVAn_ReDatVon <= temp.Rechnungsdatum and UStVAn_ReDatBis >= temp.Rechnungsdatum and [Länderverzeichnis für die Außenhandelsstatistik].LandNr = UStVAn_LandNr and isnull(UStVAn_AntragArt,'MWST') = 'MWST'
                        left JOIN tblSteuernummern On temp.Einreichland = tblSteuernummern.LandKz and KdNr = tblSteuernummern.AdressenNr
                        where 1 = 1 and isnull(kde_keineMWSt,0) = 0  " & sqlwhereLand & sqlwhereSteuerNr & sqlwhereLieferant &
                        " group by isnull(UStVAn_ID,0) , Lieferant, KdNr, Kundenname,Kundenland, Einreichland, isnull(tblSteuernummern.UStV,0), case WHEN UStVAn_AntragEingereichtAm IS NULL THEN 0 else 1 end order by Kundenname "

            Dim SQLWhere = ""

            .SET_SQL(sqlstring, "FMZOLL")
            .LOAD()
            If .Columns.Count > 0 Then

                .Columns("KdNr").HeaderText = "KdNr"
                .Columns("UStV").HeaderText = "UStV"
                .Columns("Kundenname").HeaderText = "Kunde"
                .Columns("Kundenland").HeaderText = "Kundenland"
                .Columns("Einreichland").HeaderText = "Einreichland"
                .Columns("eingereicht").HeaderText = "einger."
                .Columns("Kundenname").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells


            End If


            If kdnr > 0 Then

                MyComboBox1.Items.Clear()
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))

            End If

            Dim sumMwSt As Double = 0
            If Not MyComboBox1._value <> "" Then
                MyComboBox1.Items.Clear()
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
                Dim list As New List(Of String)
                For Each r As DataGridViewRow In .Rows

                    If r.Cells("Einreichland").Value IsNot Nothing And r.Cells("Einreichland").Value <> "" Then

                        If Not list.Any(Function(c) c = r.Cells("Einreichland").Value) Then
                            list.Add(r.Cells("Einreichland").Value)

                        End If
                    End If
                Next

                For Each l In list
                    Dim listItem As New VERAG_PROG_ALLGEMEIN.MyListItem(l, l)
                    MyComboBox1.Items.Add(listItem)
                Next
            End If

            If Not cbxKundeLand._value <> "" Then
                cbxKundeLand.Items.Clear()
                cbxKundeLand.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
                Dim list As New List(Of String)
                For Each r As DataGridViewRow In .Rows

                    If r.Cells("Kundenland").Value IsNot Nothing And r.Cells("Kundenland").Value <> "" Then

                        If Not list.Any(Function(c) c = r.Cells("Kundenland").Value) Then
                            list.Add(r.Cells("Kundenland").Value)

                        End If
                    End If
                Next

                For Each l In list
                    Dim listItem As New VERAG_PROG_ALLGEMEIN.MyListItem(l, l)
                    cbxKundeLand.Items.Add(listItem)
                Next
            End If

            If Not cbxLieferant._value <> "" Then
                cbxLieferant.Items.Clear()
                cbxLieferant.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
                Dim list As New List(Of String)
                For Each r As DataGridViewRow In .Rows

                    If r.Cells("Lieferant").Value IsNot Nothing And r.Cells("Lieferant").Value <> "" Then

                        If Not list.Any(Function(c) c = r.Cells("Lieferant").Value) Then
                            list.Add(r.Cells("Lieferant").Value)

                        End If
                    End If
                Next

                For Each l In list
                    Dim listItem As New VERAG_PROG_ALLGEMEIN.MyListItem(l, l)
                    cbxLieferant.Items.Add(listItem)
                Next
            End If


            txtAnzahl.Text = .Rows.Count
            txtMWST.Text = sumMwSt


        End With

    End Sub

    Sub init()

        setdtKundeMWST(IIf(cbxAlleoffenen.Checked, -1, kdNr))


        MyDatagridview1.SuspendLayout()
        MyDatagridview1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None

        Select Case LIEFERANT.ToString.ToLower
            Case "plose" : initDgv_PLOSE(txtmaxAnz.Text, IIf(cbxAlleoffenen.Checked, -1, kdNr))
            Case "rmc" : initDgv_RMC(txtmaxAnz.Text, IIf(cbxAlleoffenen.Checked, -1, kdNr))
            Case "mse" : initDgv_MSE(txtmaxAnz.Text, IIf(cbxAlleoffenen.Checked, -1, kdNr))
            Case "uta" : initDgv_UTA(txtmaxAnz.Text, IIf(cbxAlleoffenen.Checked, -1, kdNr))
            Case "ids" : initDgv_IDS(txtmaxAnz.Text, IIf(cbxAlleoffenen.Checked, -1, kdNr))
            Case "verag" : initDgv_VERAG(txtmaxAnz.Text, IIf(cbxAlleoffenen.Checked, -1, kdNr))
            Case "alle" : initDgv_gesamt(txtmaxAnz.Text, cbxNichtEroeffneteAntraege.Checked, IIf(cbxAlleoffenen.Checked, -1, kdNr))
        End Select

        MyDatagridview1.ResumeLayout()
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        initLieferant("RMC", sender)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        initLieferant("UTA", sender)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        initLieferant("MSE", sender)
    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        initLieferant("IDS", sender)
    End Sub
    Private Sub btnVerag_Click(sender As Object, e As EventArgs) Handles btnVerag.Click
        initLieferant("VERAG", sender)
    End Sub

    Private Sub cbxAlleoffenen_CheckedChanged(sender As Object, e As EventArgs) Handles cbxAlleoffenen.CheckedChanged, cbxUStV.CheckedChanged, cbxNichtEroeffneteAntraege.CheckedChanged
        init()
    End Sub

    Private Sub MyDatagridview1_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles MyDatagridview1.CellContentDoubleClick


        Try

            If Not MyDatagridview1.Columns.Contains("daId") Then Exit Sub
            Dim ColInd As Integer = 8
            Select Case LIEFERANT.ToString.ToLower
                Case "ids", "verag"
                    ColInd = 7

            End Select

            If e.RowIndex >= 0 AndAlso e.ColumnIndex = ColInd Then
                Dim dsID = MyDatagridview1.Rows(e.RowIndex).Cells("daId").Value

                If dsID > 0 Then
                    Me.Cursor = Cursors.WaitCursor
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dsID)
                    DS.OPEN_SINGLE()
                End If
            End If



        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
            Me.Cursor = Cursors.Default
        End Try

        Me.Cursor = Cursors.Default



    End Sub

    Private Sub MyDatagridview1_Sorted(sender As Object, e As EventArgs) Handles MyDatagridview1.Sorted

        If Not MyDatagridview1.Columns.Contains("daId") Then Exit Sub

        For Each r As DataGridViewRow In MyDatagridview1.Rows

            If Not IsDBNull(r.Cells("daId").Value) AndAlso r.Cells("daId").Value > 0 Then DirectCast(r.Cells("clmnPDF"), DataGridViewImageCell).Value = My.Resources.pdf
        Next

    End Sub

    Private Sub btnAlle_Click(sender As Object, e As EventArgs) Handles btnAlle.Click
        initLieferant("ALLE", sender)
    End Sub

    Private Sub MyComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles MyComboBox1.SelectedIndexChanged
        initDgv_gesamt(txtmaxAnz.Text, cbxNichtEroeffneteAntraege.Checked, IIf(cbxAlleoffenen.Checked, -1, kdNr))
    End Sub

    Private Sub AntragEröffnenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AntragEröffnenToolStripMenuItem.Click

        If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub
        Dim index As Integer = -1
        If (MyDatagridview1.SelectedRows.Count > 0) Then index = MyDatagridview1.SelectedRows(0).Index

        If MyDatagridview1.SelectedRows(0).Cells("antragExisitiert").Value > 0 AndAlso Not MyDatagridview1.SelectedRows(0).Cells("eingereicht").Value Then


            Dim frm = New frmMDM_USTVAntrag(MyDatagridview1.SelectedRows(0).Cells("antragExisitiert").Value)
            frm.ShowDialog()

        Else


            Dim frm = New frmMDM_USTVAntrag(MyDatagridview1.SelectedRows(0).Cells("KdNr").Value, MyDatagridview1.SelectedRows(0).Cells("Einreichland").Value, dat_Sum_Von.Value, dat_Sum_Bis.Value)
            frm.ShowDialog()

        End If


        MyDatagridview1.GetOrder()
        initDgv_gesamt(txtmaxAnz.Text, cbxNichtEroeffneteAntraege.Checked, IIf(cbxAlleoffenen.Checked, -1, kdNr))
        MyDatagridview1.SetOrder()

    End Sub

    Private Sub MyDatagridview1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles MyDatagridview1.CellMouseClick

        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_USTVA_bearbeiten", Me.FindForm) Then Exit Sub
        If e.RowIndex < 0 Then Exit Sub

        DirectCast(sender, DataGridView).Rows(e.RowIndex).Selected = True
        If e.Button = MouseButtons.Right Then

            If sender Is MyDatagridview1 AndAlso LIEFERANT.ToString.ToLower = "alle" Then
                If MyDatagridview1.SelectedRows.Count = 0 Then Exit Sub '
                MyDatagridview1.CurrentCell = MyDatagridview1.Rows(e.RowIndex).Cells(e.ColumnIndex)
                ContextMenuStrip1.Show(Cursor.Position)
            End If

        End If

    End Sub

    Private Sub cbxKundeLand_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxKundeLand.SelectedIndexChanged, cbxLieferant.SelectedIndexChanged
        initDgv_gesamt(txtmaxAnz.Text, cbxNichtEroeffneteAntraege.Checked, IIf(cbxAlleoffenen.Checked, -1, kdNr))
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click

        Dim dtfehlendePDF As New DataTable
        Dim dtPartInvoicesIDS As New DataTable
        Dim fehlendePDFS As Integer = 0
        Dim fehlendePDFSPartInvoicesIDS As Integer = 0

        Select Case LIEFERANT.ToString.ToLower
            Case "plose"

                Dim LIEFERANT As cPLOSE_Inv_Data
                fehlendePDFS = LIEFERANT.checkPDFInvoices(dat_Sum_Von.Value, dat_Sum_Bis.Value, dtfehlendePDF)

            Case "rmc"
                Dim LIEFERANT As cRMC
                fehlendePDFS = LIEFERANT.checkPDFInvoices(dat_Sum_Von.Value, dat_Sum_Bis.Value, dtfehlendePDF)

            Case "mse"

                Dim LIEFERANT As cMSEAPI
                fehlendePDFS = LIEFERANT.checkPDFInvoices(dat_Sum_Von.Value, dat_Sum_Bis.Value, dtfehlendePDF)


            Case "uta"

                Dim LIEFERANT As cUTA
                fehlendePDFS = LIEFERANT.checkPDFInvoices(dat_Sum_Von.Value, dat_Sum_Bis.Value, dtfehlendePDF)


            Case "ids"
                Dim LIEFERANT As cIDS
                fehlendePDFS = LIEFERANT.checkPDFInvoices(dat_Sum_Von.Value, dat_Sum_Bis.Value, dtfehlendePDF)
                fehlendePDFSPartInvoicesIDS = LIEFERANT.checkPartInvoices(dat_Sum_Von.Value, dat_Sum_Bis.Value, dtPartInvoicesIDS)


            Case "verag"

                MsgBox("PDF wird zur Laufzeit aus RE-Daten generiert")
                Exit Sub

            Case Else

                MsgBox("Funktion nur pro Lieferant möglich!")
                Exit Sub

        End Select



        MsgBox("Anzahl fehlende PDFs: " & fehlendePDFS & IIf(CDate(dat_Sum_Von.Value).Year <= 2024 OrElse CDate(dat_Sum_Bis.Value).Year <= 2024, vbNewLine & "PDF-Rechnungen vor 2025 wurden tlw. nicht importiert!", ""))

        If dtfehlendePDF.Rows.Count > 0 Then
            If vbYes = MsgBox("Details der fehlenden PDF-Rechnungen anzeigen?", vbYesNo) Then
                cProgramFunctions.genExcelFromDT_NEW(dtfehlendePDF,,, "Fehlende PDF-Rechnungen: " & dat_Sum_Von.Value.ToShortDateString & " - " & dat_Sum_Bis.Value.ToShortDateString)

            End If

        End If

        'extra bei IDS ->Prüft ob es zur Gesamtrechnung Teilrechnungen gibt!!
        If LIEFERANT.ToString.ToLower = "ids" Then
            If fehlendePDFSPartInvoicesIDS > 0 Then

                If vbYes = MsgBox("Es fehlen " & fehlendePDFSPartInvoicesIDS & " Teilrechnungen" & vbNewLine & "Details der fehlenden Teilrechnungen anzeigen?", vbYesNo) Then
                    cProgramFunctions.genExcelFromDT_NEW(dtPartInvoicesIDS,,, "Fehlende PDF-Teilrechnungen inkl. Datensatz " & dat_Sum_Von.Value.ToShortDateString & " - " & dat_Sum_Bis.Value.ToShortDateString)
                End If


                If dtPartInvoicesIDS.Rows.Count <= 10 Then
                    If vbYes = MsgBox(dtPartInvoicesIDS.Rows.Count & " Gesamtrechnungen der fehlenden PDF-Teilrechnungen anzeigen?", vbYesNo) Then
                        For Each row In dtPartInvoicesIDS.Rows
                            If row.item("daId") IsNot Nothing AndAlso IsNumeric(row.item("daId")) AndAlso CInt(row.item("daId")) > 0 Then
                                Dim DS As New cDATENSERVER(row.item("daId"))
                                Dim pathPDF = DS.GET_TOP1_PATH
                                If pathPDF <> "" Then Process.Start(pathPDF)
                            End If

                        Next
                    End If
                End If

            End If

        End If



    End Sub

    Private Sub frmUSTVoffeneAntraege_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        dtkeineMWST = (New SQL).loadDgvBySql("select Land, Erstattungsland, Lieferant from tblKeineMWSTErstattung", "FMZOLL")
        setdtKundeMWST(kdNr)

        dTLANDEU = (New SQL).loadDgvBySql("select LandKz, MitgliedslandEU from Währungstabelle where LandKz is not null", "FMZOLL")

        Dim R As DataRow = dTLANDEU.NewRow
        R("LandKz") = "MK"
        R("MitgliedslandEU") = False
        dTLANDEU.Rows.Add(R)

        frmMain.EnableDoubleBuffered(MyDatagridview1)

    End Sub

    Private Sub setdtKundeMWST(kd As Integer)

        If kd > 0 Then
            dtKundeMWST = (New SQL).loadDgvBySql("select LandKz from tblKundenMWST where KdNr = " & kdNr, "FMZOLL")
        Else
            dtKundeMWST = (New SQL).loadDgvBySql("SELECT KdNr,  abc = STUFF(
                                                 (SELECT ';' + LandKz + ';' + ',' 
                                                  FROM tblKundenMWST t1
                                                  WHERE t1.KdNr = t2.KdNr
                                                  FOR XML PATH (''))
                                                 , 1, 1, ';') from tblKundenMWST t2
                                    group by KdNr order by kdNr;", "FMZOLL")
        End If


    End Sub

    Private Sub cbxEigeneMWST_CheckedChanged(sender As Object, e As EventArgs) Handles cbxKundenMWST.CheckedChanged
        init()
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles btnPLOSE_DK.Click

        Dim SQL As New SQL

        If SQL.doSQL("update [VERAG].[dbo].[tblPLOSE_Inv_Data] set plInv_SupplierCountry = 'SE' where plInv_SupplierRechnungsNr like 'SE%' and plInv_SupplierCountry = 'DK'", "FMZOLL", False) Then
            MsgBox("Wurden erfolgreich gesetzt!")
        End If

    End Sub
End Class