Imports System.ComponentModel
Imports System.Data.SqlClient
Imports Microsoft.Office.Interop
Imports VERAG_PROG_ALLGEMEIN


Public Class usrCntlUSTV


    Dim kundenSQL As New kundenSQL
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Dim FUNC As New cProgramFunctions
    Dim aktbtn As String = ""
    Dim dgvInitWait As Boolean = False
    Public kdNr As Integer = -1
    Dim loaded As Boolean = False

    Sub init(Optional kdNr = -1)
        pnlFilter.AutoScroll = False
        '  MsgBox(kdNr)
        If kdNr > 0 Then
            Me.kdNr = kdNr
            KdSearchBox1.KdNr = kdNr
            KdSearchBox1.Enabled = False
        End If

        btnPLOSEAlle.Enabled = KdSearchBox1.KdNr > 0
        btnRMCalle.Enabled = KdSearchBox1.KdNr > 0

        With dgvUSTV
            .ClearSelection()

            Dim topMax = ""
            If cbxTopMax.Checked Then
                If IsNumeric(txtMaxSrch.Text) Then
                    topMax = " TOP (" & txtMaxSrch.Text.Trim & ")"
                Else
                    topMax = " TOP (200)"
                End If
            End If

            .SET_SQL("SELECT " & topMax & " [UStVAn_ID],UStVAn_AntragArt,[UStVAn_KuNr],[UStVAn_Name],LandKz, UStVAn_BezugsNr, [UStVAn_ReDatVon], [UStVAn_ReDatBis] ,UStVAn_AntragEingereichtAm,[UStVAn_3470] ,[UStVAn_Währungscode],[UStVAn_USteuerbetrag],[UStVAn_Erstattungsbetrag],([UStVAn_USteuerbetrag] - [UStVAn_Erstattungsbetrag]) as UStVAn_Differenzbetrag,[UStVAn_USteuerbetragEUR],[UStVAn_ErstattungsbetragEUR],([UStVAn_USteuerbetragEUR] - [UStVAn_ErstattungsbetragEUR]) as UStVAn_DifferenzbetragEUR,[UStVAn_VZBetrag],[UStVAn_VZDatum],[UStVAn_Sachbearbeiter]
                  FROM [tblUStVAntrag] inner join [Länderverzeichnis für die Außenhandelsstatistik] on UStVAn_LandNr=Landnr
                  where 1=1 " & getWhere() & "
                  order by UStVAn_KuNr,UStVAn_Name,datepart(year,[UStVAn_ReDatVon] ) desc,LandKz,[UStVAn_ReDatVon] desc", "FMZOLL")
            .LOAD()

            loaded = True

            .RowTemplate.Height = 20
            .AllowUserToOrderColumns = False
            .AllowUserToResizeRows = False

            If .Columns.Count > 0 Then

                Dim DataGridViewCellStyleDate = New DataGridViewCellStyle()
                DataGridViewCellStyleDate.Format = "MM/yyyy"


                .Columns("UStVAn_ID").Visible = False
                .Columns("UStVAn_AntragArt").HeaderText = "Art"
                .Columns("UStVAn_AntragArt").MinimumWidth = 50

                .Columns("UStVAn_KuNr").HeaderText = "KundenNr"
                .Columns("UStVAn_Name").MinimumWidth = 70


                .Columns("UStVAn_Name").HeaderText = "Firma"
                .Columns("UStVAn_Name").Width = 200
                ' .Columns("UStVAn_Name").MinimumWidth = 150
                ' .Columns("UStVAn_Name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

                .Columns("LandKz").Width = 60

                .Columns("UStVAn_ReDatVon").HeaderText = "Von"
                '.Columns("UStVAn_ReDatVon").DefaultCellStyle = DataGridViewCellStyleDate
                .Columns("UStVAn_ReDatVon").Width = 100

                .Columns("UStVAn_ReDatBis").HeaderText = "Bis"
                '.Columns("UStVAn_ReDatBis").DefaultCellStyle = DataGridViewCellStyleDate
                .Columns("UStVAn_ReDatBis").Width = 100

                .Columns("UStVAn_BezugsNr").HeaderText = "BezugsNr"
                .Columns("UStVAn_BezugsNr").Width = 100

                .Columns("UStVAn_AntragEingereichtAm").HeaderText = "EingereichtAm"
                .Columns("UStVAn_AntragEingereichtAm").Width = 100

                .Columns("UStVAn_3470").HeaderText = "3470"
                .Columns("UStVAn_3470").Width = 150
                .Columns("UStVAn_3470").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_3470").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_Währungscode").HeaderText = "Währung"
                .Columns("UStVAn_Währungscode").Width = 80

                .Columns("UStVAn_USteuerbetrag").HeaderText = "USt-Betrag"
                .Columns("UStVAn_USteuerbetrag").Width = 150
                .Columns("UStVAn_USteuerbetrag").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_USteuerbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_Erstattungsbetrag").HeaderText = "Erstattung-Betrag"
                .Columns("UStVAn_Erstattungsbetrag").Width = 150
                .Columns("UStVAn_Erstattungsbetrag").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_Erstattungsbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight


                .Columns("UStVAn_Differenzbetrag").HeaderText = "Differenz-Betrag"
                .Columns("UStVAn_Differenzbetrag").Width = 150
                .Columns("UStVAn_Differenzbetrag").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_Differenzbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_ErstattungsbetragEUR").HeaderText = "Erstattung-Betrag  EUR"
                .Columns("UStVAn_ErstattungsbetragEUR").Width = 150
                .Columns("UStVAn_ErstattungsbetragEUR").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_ErstattungsbetragEUR").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_USteuerbetragEUR").HeaderText = "USt-Betrag EUR"
                .Columns("UStVAn_USteuerbetragEUR").Width = 150
                .Columns("UStVAn_USteuerbetragEUR").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_USteuerbetragEUR").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_DifferenzbetragEUR").HeaderText = "Differenz-Betrag EUR"
                .Columns("UStVAn_DifferenzbetragEUR").Width = 150
                .Columns("UStVAn_DifferenzbetragEUR").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_DifferenzbetragEUR").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_VZDatum").HeaderText = "Vorauszahlung Am"
                .Columns("UStVAn_VZDatum").Width = 100

                .Columns("UStVAn_VZBetrag").HeaderText = "Vorauszahlung-Betrag"
                .Columns("UStVAn_VZBetrag").Width = 150
                .Columns("UStVAn_VZBetrag").DefaultCellStyle.Format = "N2"
                .Columns("UStVAn_VZBetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                .Columns("UStVAn_Sachbearbeiter").HeaderText = "Sachbearbeiter"
                .Columns("UStVAn_Sachbearbeiter").MinimumWidth = 150
                .Columns("UStVAn_Sachbearbeiter").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            End If

            Dim GesamtUSteuer As Double
            Dim GesamtErstattung As Double
            Dim Differnezbetrag As Double

            If KdSearchBox1.KdNr > 0 Then
                GesamtUSteuer = SQL.DLookup("isnull(sum(UStVAn_USteuerbetragEUR),0)", "tblUStVAntrag", "UStVAn_KuNr='" & KdSearchBox1.KdNr & "'", "FMZOLL", "0")
                GesamtErstattung = SQL.DLookup("isnull(sum(UStVAn_ErstattungsbetragEUR),0)", "tblUStVAntrag", "UStVAn_KuNr='" & KdSearchBox1.KdNr & "'", "FMZOLL", "0")
            Else
                For Each rows As DataGridViewRow In .Rows
                    If IsNumeric(rows.Cells("UStVAn_USteuerbetragEUR").Value) Then GesamtUSteuer += rows.Cells("UStVAn_USteuerbetragEUR").Value
                    If IsNumeric(rows.Cells("UStVAn_ErstattungsbetragEUR").Value) Then GesamtErstattung += rows.Cells("UStVAn_ErstattungsbetragEUR").Value
                Next
            End If


            Differnezbetrag = GesamtUSteuer - GesamtErstattung

            txtSumUst.Text = GesamtUSteuer.ToString("C2")
            txtSumErst.Text = GesamtErstattung.ToString("C2")
            txtSumDiff.Text = Differnezbetrag.ToString("C2")


        End With

    End Sub


    Function getWhere(Optional useJahr = True) As String
        Dim whereStr = ""
        'If KdSearchBox1.KdNr <= 0 Then Exit Sub

        If useJahr Then
            If cboJahr._value <> "" Then
                If cboJahrBis._value <> "" Then
                    whereStr &= " AND UStVAn_ReDatVon>='01.01." & cboJahr._value & "' AND UStVAn_ReDatBis<='31.12." & cboJahrBis._value & "'  "
                Else
                    whereStr &= " AND UStVAn_ReDatVon>='01.01." & cboJahr._value & "' AND UStVAn_ReDatBis<='31.12." & cboJahr._value & "'  "
                End If
            End If
        End If

        Select Case cbxEingereicht.CheckState
            Case CheckState.Checked
                whereStr &= " AND UStVAn_AntragEingereichtAm is not null "
            Case CheckState.Unchecked
                whereStr &= " AND UStVAn_AntragEingereichtAm is null "
            Case CheckState.Indeterminate
        End Select

        Select Case cbxDifferenzbetrag.CheckState
            Case CheckState.Checked
                whereStr &= " AND ([UStVAn_USteuerbetrag]-[UStVAn_Erstattungsbetrag]) <> 0"
            Case CheckState.Unchecked
                whereStr &= " AND ([UStVAn_USteuerbetrag]-[UStVAn_Erstattungsbetrag]) = 0 "
            Case CheckState.Indeterminate
        End Select

        If KdSearchBox1.KdNr > 0 Then whereStr &= " AND UStVAn_KuNr=" & KdSearchBox1.KdNr & " "
        Return whereStr
    End Function

    Private Sub usrCntlVERAGCard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' btnFilter.Left = Panel4.Width - btnFilter.Width
        KdSearchBox1.initKdBox(Me.FindForm)
        If kdNr > 0 Then
            KdSearchBox1.KdNr = kdNr
            KdSearchBox1.Enabled = False
        End If
        init()
        cboJahr.Items.Clear()
        cboJahr.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        For i = 0 To 10
            cboJahr.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(Now.Year - i, Now.Year - i))
        Next
        cboJahr.changeItem(Now.Year - 2)

        cboJahrBis.Items.Clear()
        cboJahrBis.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        For i = 0 To 10
            cboJahrBis.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(Now.Year - i, Now.Year - i))
        Next
        cboJahrBis.changeItem(Now.Year)


        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            'FlatButton1.Enabled = False#

            FlatButton2.Enabled = False
            Button14.Enabled = False

        Else
            If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                FlatButton2.Enabled = True
                Button14.Enabled = True
            End If
        End If
        '   Panel3.Height = Me.Height / 2 + 300
    End Sub


    Private Sub dgvUSTV_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvUSTV.CellDoubleClick
        If dgvUSTV.SelectedRows.Count > 0 Then

            Dim f As New frmMDM_USTVAntrag(dgvUSTV.SelectedRows(0).Cells("UStVAn_ID").Value)
            f.ShowDialog(Me)
            dgvUSTV.RELOAD()
        End If
    End Sub

    Private Sub cboJahr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboJahr.SelectedIndexChanged, cboJahrBis.SelectedIndexChanged
        If loaded = False Then Exit Sub
        init()
    End Sub

    Private Sub KdSearchBox1_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles KdSearchBox1.PropertyChanged
        If loaded = False Then Exit Sub
        init()
    End Sub


    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button1.Click
        cProgramFunctions.genExcelFromDGV_NEW(dgvUSTV, True)
    End Sub

    Private Sub Button8_Click_1(sender As Object, e As EventArgs) Handles Button8.Click
        'Dim sqlStr = "SELECT   [UStVAn_ID],[UStVAn_KuNr],[UStVAn_Name],LandKz,[UStVAn_ReDatVon],[UStVAn_ReDatBis] ,UStVAn_AntragEingereichtAm,[UStVAn_3470] ,[UStVAn_Währungscode],[UStVAn_USteuerbetrag],[UStVAn_Erstattungsbetrag],[UStVAn_USteuerbetragEUR],[UStVAn_ErstattungsbetragEUR],[UStVAn_Sachbearbeiter]
        '          FROM [tblUStVAntrag] inner join [Länderverzeichnis für die Außenhandelsstatistik] on UStVAn_LandNr=Landnr
        '            where 1=1 " & getWhere(False) & "
        '              AND cast( [UStVAn_USteuerbetragEUR] as decimal(17,2))-cast( [UStVAn_ErstattungsbetragEUR]  as decimal(17,2))<>0
        '              AND UStVAn_AntragEingereichtAm is not null
        '          order by UStVAn_KuNr,UStVAn_Name,datepart(year,[UStVAn_ReDatVon] ) desc,LandKz,[UStVAn_ReDatVon] desc"
        Dim sqlStr = "SELECT   [UStVAn_ID],[UStVAn_KuNr],[UStVAn_Name],Adressen.LandKz as Land_Kunde, case when UstIdKz is not null and UstIdNr is not null THEN UstIdKz +'' + UstIdNr ELSE isnull(Steuernummer,'') END as SteuerUIDNr,  LfdA .LandKz Land_Antrag,[UStVAn_ReDatVon],[UStVAn_ReDatBis] ,UStVAn_AntragEingereichtAm,[UStVAn_3470] ,[UStVAn_Währungscode],[UStVAn_USteuerbetrag],[UStVAn_Erstattungsbetrag],[UStVAn_USteuerbetragEUR],[UStVAn_ErstattungsbetragEUR],(cast([UStVAn_USteuerbetragEUR] as decimal(17,2)) - cast( [UStVAn_ErstattungsbetragEUR]  as decimal(17,2))) as Differenzbetrag, [UStVAn_Sachbearbeiter]
                  FROM [tblUStVAntrag] inner join [Länderverzeichnis für die Außenhandelsstatistik] as LfdA on UStVAn_LandNr=Landnr
				  inner join Adressen on AdressenNr=UStVAn_KuNr
                    where 1=1  
                      AND cast( [UStVAn_USteuerbetragEUR] as decimal(17,2))-cast( [UStVAn_ErstattungsbetragEUR]  as decimal(17,2))<>0
                      AND UStVAn_AntragEingereichtAm is not null
                  order by UStVAn_KuNr,UStVAn_Name,datepart(year,[UStVAn_ReDatVon] ) desc,LfdA .LandKz,[UStVAn_ReDatVon] desc"

        Dim dt = SQL.loadDgvBySql(sqlStr, "FMZOLL")
        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
            cProgramFunctions.genExcelFromDT_NEW(dt, {"J1:N" & (dt.Rows.Count + 1)})
        Else
            MsgBox("Keine Daten!")
        End If

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        ' If Not kdNr_filter Then
        If dgvUSTV.SelectedCells.Count > 0 Then
            If IsNumeric(dgvUSTV.CurrentRow.Cells("UStVAn_KuNr").Value) Then
                cProgramFunctions.openKundenblatt(dgvUSTV.CurrentRow.Cells("UStVAn_KuNr").Value, Me.FindForm, True)
                'Dim pf As New cProgramFunctions
                'pf.openKundenblatt(dgvSDL.CurrentRow.Cells("KundenNr").Value)
            End If
        End If
        ' End If
    End Sub

    Private Sub btnPLOSEAlle_Click(sender As Object, e As EventArgs) Handles btnPLOSEAlle.Click, btnRMCalle.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            If KdSearchBox1.KdNr <= 0 Then Exit Sub
            If cboJahr._value = "" Then Exit Sub
            If cboJahrBis._value = "" Then Exit Sub

            Dim cnt = SQL.getValueTxtBySql(" SELECT  COUNT(*)   FROM [tblUStVAntrag] where UStVAn_AntragEingereichtAm is null AND UStVAn_KuNr=" & KdSearchBox1.KdNr & "  AND UStVAn_ReDatVon>='01.01." & cboJahr._value & "' AND UStVAn_ReDatBis<='31.12." & cboJahrBis._value & "'", "FMZOLL")
            If cnt = 0 Then MsgBox("Keine einreichbaren Anträge gefunden!") : Exit Sub

            Select Case sender.name
                Case "btnPLOSEAlle"
                    If vbYes = MsgBox("Es werden PLOSE Daten für " & cnt & " USTV-Anträge eingearbeitet. Möchten Sie fortfahren?", vbYesNoCancel) Then
                        For Each r As DataGridViewRow In dgvUSTV.Rows
                            If r.Cells("UStVAn_AntragEingereichtAm").Value Is DBNull.Value Then ' OrElse r.Cells("UStVAn_AntragEingereichtAm").Value = "" Then
                                'Dim Antrag_LandKz = SQL.DLookup("LandKz", "[Länderverzeichnis für die Außenhandelsstatistik]", "Landnr='" & r.Cells("UStVAn_LandNr").Value & "'", "FMZOLL")
                                frmMDM_USTVAntrag.loadUSTVFrom_PLOSE(r.Cells("UStVAn_ID").Value, r.Cells("LandKz").Value, False)
                            End If
                        Next
                        init()
                        MsgBox("Fertig!")
                    End If


                Case "btnRMCalle"

                    If vbYes = MsgBox("Es werden RMC Daten für " & cnt & " USTV-Anträge eingearbeitet. Möchten Sie fortfahren?", vbYesNoCancel) Then
                        For Each r As DataGridViewRow In dgvUSTV.Rows
                            If r.Cells("UStVAn_AntragEingereichtAm").Value Is DBNull.Value Then
                                frmMDM_USTVAntrag.loadUSTVFrom_RMC(r.Cells("UStVAn_ID").Value, r.Cells("LandKz").Value, False)
                            End If
                        Next
                        init()
                        MsgBox("Fertig!")
                    End If


                Case Else
                    MsgBox("Funktion nicht definiert")
            End Select




        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub btnMail_Click(sender As Object, e As EventArgs) Handles btnMail.Click

        If Not ContextMenuStrip1.Items.ContainsKey("excel") Then
            Dim excel = New ToolStripMenuItem() With {.Text = "Excelauswertung starten", .Name = "excel", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            ContextMenuStrip1.Items.Add(excel)
            AddHandler excel.Click, AddressOf mnuItem_Clicked
        End If


        If Not ContextMenuStrip1.Items.ContainsKey("mail") Then
            Dim mail = New ToolStripMenuItem() With {.Text = "Email generieren", .Name = "mail", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            AddHandler mail.Click, AddressOf mnuItem_Clicked
            ContextMenuStrip1.Items.Add(mail)
        End If

        If Not ContextMenuStrip1.Items.ContainsKey("offeneAntraege") Then
            Dim oa = New ToolStripMenuItem() With {.Text = "offene Anträge", .Name = "offeneAntraege", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            AddHandler oa.Click, AddressOf mnuItem_Clicked
            ContextMenuStrip1.Items.Add(oa)
        End If

        ContextMenuStrip1.Show(Cursor.Position)


    End Sub

    Private Sub mnuItem_Clicked(sender As Object, e As EventArgs)

        If dgvUSTV.SelectedRows.Count > 0 Then

            ContextMenuStrip1.Hide()
            Dim item As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)

            If item IsNot Nothing Then
                If item.Name = "excel" Then
                    excelAuswertung()

                ElseIf item.Name = "mail" Then
                    mailmitExcelauswertung()

                ElseIf item.Name = "offeneAntraege" Then
                    If dgvUSTV.SelectedRows(0) IsNot Nothing AndAlso IsDate(dgvUSTV.SelectedRows(0).Cells("UStVAn_ReDatVon").Value) AndAlso IsDate(dgvUSTV.SelectedRows(0).Cells("UStVAn_ReDatBis").Value) Then
                        Dim frm As New frmUSTVoffeneAntraege(CDate(dgvUSTV.SelectedRows(0).Cells("UStVAn_ReDatVon").Value), CDate(dgvUSTV.SelectedRows(0).Cells("UStVAn_ReDatBis").Value))
                        frm.Show()
                    Else
                        Dim frm As New frmUSTVoffeneAntraege()
                        frm.Show()
                    End If

                Else
                    MsgBox("Funktion nicht implementiert!")
                End If

            End If
        End If

    End Sub


    Private Function excelAuswertung(Optional ByRef filepath As String = "", Optional feedback As Boolean = False, Optional openExcel As Boolean = True) As Boolean

        Dim sqlStr = "SELECT [UStVPo_ReDat] as InvoiceDate , [UStVPo_ReNr] As InvoiceNumber, antr.UStVAn_Name as Company, 'FR' as CountryOfRefund ,'EUR' as Currency ,[UStVPo_Leistender] as SupplierName, leist.[UstV_Leistender_Strasse] AS SupplierStreet, leist.[UstV_Leistender_StrasseNr] as SupplierStreetNumber, leist.[UstV_Leistender_PLZ] as SupplierPostalCode, leist.[UstV_Leistender_Stadt] as SupplierCity, leist.[UstV_Leistender_Land] as SupplierCountry, leist.[UstV_Leistender_UstNr] as SupplierVAT_TaxNumber, [UStVPo_Leistungsbezeichnung] as ExpenseCategory ,Round((1119/19*[UStVPo_USteuerbetragEUR]),2) as ExpenseGrossAmount, [UStVPo_USteuerbetragEUR] as ExpenseVATAmount,Round((100/19*[UStVPo_USteuerbetragEUR]),2) as ExpenseNetAmount
                      FROM [tblUStVPositionen]
					  inner Join [tblUStVLeistender] as leist on leist.UStV_Leistender = [tblUStVPositionen].[UStVPo_Leistender]
                      inner join [tblUStVAntrag] as antr on antr.UStVAn_ID = [tblUStVPositionen].UStVAn_ID
                      where [tblUStVPositionen].UStVAn_ID ='" & dgvUSTV.SelectedRows(0).Cells("UStVAn_ID").Value & "' ORDER BY UStVPo_ID"

        Dim dt = SQL.loadDgvBySql(sqlStr, "FMZOLL")

        'filepath = ""
        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
            filepath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt, {"N1:N" & (dt.Rows.Count + 1), "O1:O" & (dt.Rows.Count + 1), "P1:P" & (dt.Rows.Count + 1)},,,, openExcel)
            Return True
        Else
            MsgBox("Keine Daten!")
            Return False
        End If

    End Function

    Private Sub mailmitExcelauswertung()

        Try


            If dgvUSTV.Columns.Count > 0 Then

                Dim subject As String = ""
                subject &= IIf(dgvUSTV.CurrentRow.Cells("UStVAn_Name").Value <> "", dgvUSTV.CurrentRow.Cells("UStVAn_Name").Value & "_", "")
                'subject &= If(dgvUSTV.CurrentRow.Cells("UStVAn_LandKz").Value <> "", dgvUSTV.CurrentRow.Cells("UStVAn_LandKz").Value & "_")
                If (dgvUSTV.CurrentRow.Cells("UStVAn_ReDatVon").Value IsNot Nothing AndAlso dgvUSTV.CurrentRow.Cells("UStVAn_ReDatBis").Value IsNot Nothing) Then
                    subject &= CDate(dgvUSTV.CurrentRow.Cells("UStVAn_ReDatVon").Value).ToShortDateString & "-" & CDate(dgvUSTV.CurrentRow.Cells("UStVAn_ReDatBis").Value).ToShortDateString
                End If

                Dim outl As New Outlook.Application
                Dim Mail As Microsoft.Office.Interop.Outlook.MailItem
                Mail = outl.CreateItem(0)


                Dim filepath = ""
                If excelAuswertung(filepath, False, False) Then

                    Mail.Attachments.Add(filepath, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue)

                End If


                Mail.Subject = subject


                Dim TextHTML = ""
                TextHTML &= "Ladies and Gentlemen,<br>"
                TextHTML &= "<br>"
                TextHTML &= "In the attachment we will send you the Excel list and the corresponding invoices for the VAT refund.<br>"
                TextHTML &= "Please submit these invoices to the tax office.<br>"
                TextHTML &= "We are always available to answer more questions.<br>"

                TextHTML &= "Mit freundlichen Grüßen<br>"
                TextHTML &= VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME & "<br>"
                TextHTML &= "<br>"
                Mail.HTMLBody = "<div style=""font-family:Calibri, Arial;font-size:15px;"">" & TextHTML & SDL.cFakturierung.getSignature("DE") & "</div>"


                Mail.Display()
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Fehler beim Öffnen der Mail!")
        End Try

    End Sub

    Private Sub cbxTopMax_CheckedChanged(sender As Object, e As EventArgs) Handles cbxTopMax.CheckedChanged
        If loaded = False Then Exit Sub
        init()
    End Sub

    Private Sub txtMaxSrch_TextChanged(sender As Object, e As EventArgs) Handles txtMaxSrch.Leave
        If loaded = False Then Exit Sub
        init()
    End Sub

    Private Sub cbxEingereicht_CheckedChanged(sender As Object, e As EventArgs) Handles cbxEingereicht.CheckStateChanged, cbxDifferenzbetrag.CheckStateChanged
        If loaded = False Then Exit Sub
        init()
    End Sub

End Class
