Imports System.IO
Imports GrapeCity.DataVisualization.Chart

Public Class usrCntlZOLLAuswertungen

    Private Sub btnza_Click(sender As Object, e As EventArgs, Optional exportPDF As String = "", Optional exportEXCEL As String = "") Handles btnNCTS.Click
        Dim sqlStr = getSQL_NCTS_ATLAS(datVon.Text, datBis.Text, txtStatVon.Text, txtStatbis.Text, DirectCast(ComboBox2.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, DirectCast(ComboBox1.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value)



        Dim frmPrintLayout As New frmPrintLayout()

        frmPrintLayout.AuswertungTKontrolle(sqlStr, datVon.Text, datBis.Text, txtStatVon.Text, txtStatbis.Text, DirectCast(ComboBox2.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, DirectCast(ComboBox1.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value)

        If exportPDF = "" And exportEXCEL = "" Then
            frmPrintLayout.Show()
        Else
            AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                                If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                                If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            End Sub
        End If

    End Sub

    Function getSQL_NCTS_ATLAS(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String)

        If brg <> "" Then
            brg = " AND veoerz_sicbsc = '" & brg & "' "
        End If


        Select Case nl
            Case "SUB", "SBG", "SUW", "WAI", "NEU" : nl = " AND basman_nl ='" & nl & "' "
            Case "ATILLA" : nl = " AND basman_nl ='SUW' AND veoant_beznr NOT LIKE 'DU%' "
            Case "DURMAZ" : nl = " AND basman_nl ='SUW' AND veoant_beznr LIKE 'DU%' "
            Case "IMEX" : nl = "  AND veoant_beznr LIKE '5501/%' "
            Case Else : nl = ""
        End Select


        Dim sqlStr As String = " SELECT  count(*) as [Anzahl Verz], max(veopos_stat) as Status, max(basman_nl) as Niederlassung, max(veoant_beznr) as Bezugsnummer,max(veoant_lfdnr) as LfdNr,max(veoant_anzpos)as Pos,max(isnull(veoadr_name1,''))as Empf,max(veoant_mrn) as MRN,min(veoant_andat) as Antragsdatum,max(veoant_sb) as Sachbearbeiter,min(veoant_wgdat) as Gestellungsdatum,sum(veoerz_sicbtg) as [Sichertheits-Betrag], max(veoerz_sicbsc) as Buergschaft  " &
                               " FROM tblZabis_Atlas_NCTS " &
                           " WHERE ( veoant_wgdat BETWEEN '" & datVon.ToShortDateString & "' AND '" & datBis.ToShortDateString & "') " &
                                " AND  veoant_stat BETWEEN '" & StatVon & "' AND '" & Statbis & "'  " &
                                " " & brg & " " &
                                " " & nl & " " &
                           " GROUP BY veoant_beznr " &
                           " ORDER BY Gestellungsdatum ASC "
        Return sqlStr

    End Function

    Sub ExportToExcel(document As GrapeCity.ActiveReports.Document.SectionDocument, path As String)
        Dim xlsExport1 As New GrapeCity.ActiveReports.Export.Excel.Section.XlsExport()
        xlsExport1.FileFormat = GrapeCity.ActiveReports.Export.Excel.Section.FileFormat.Xlsx
        xlsExport1.Export(document, path)
    End Sub

    Sub ExportToPDF(document As GrapeCity.ActiveReports.Document.SectionDocument, path As String)
        Dim pdfExport1 As New GrapeCity.ActiveReports.Export.Pdf.Section.PdfExport()
        pdfExport1.Export(frmPrintLayout.Viewer.Document, path)
    End Sub
    Private Sub usrCntlMDMAuswertungen_Load(sender As Object, e As EventArgs) Handles Me.Load

        txtJahrDurmaz.Value = Now.Year
        txtJahrATILLA.Value = Now.Year
        txtJahrIMEX.Value = Now.Year
        txtJahrAmbar.Value = Now.Year
        txtJahr_NCTSTR.Value = Now.Year
        txtJahr_NCTSTR_UNISPED.Value = Now.Year
        txtJahr_NCTSTR_AWOR.Value = Now.Year

        cboMonatDurmaz.SelectedIndex = Now.AddMonths(-1).Month
        cboMonatATILLA.SelectedIndex = Now.AddMonths(-1).Month
        cboMonatIMEX.SelectedIndex = Now.AddMonths(-1).Month
        cboMonatAmbar.SelectedIndex = Now.AddMonths(-1).Month
        cboMonat_NCTSTR.SelectedIndex = Now.AddMonths(-1).Month
        cboMonat_NCTSTR_UNISPED.SelectedIndex = Now.AddMonths(-1).Month
        cboMonat_NCTSTR_AWOR.SelectedIndex = Now.AddMonths(-1).Month

        Dim d As Date = CDate("01." & Now.Month & "." & Now.Year)
        datVon.Value = Now 'd.AddMonths(-3)
        datBis.Value = Now.AddDays(3)

        datBisDy.Value = Now.AddDays(3)
        datUnispedBis.Value = Now.AddDays(3)

        datVon_NCTSTR.Value = Now
        datBis_NCTSTR.Value = Now.AddDays(3)

        datAuswertVon_NCTSTR_UNISPED.Value = Now
        datAuswertBis_NCTSTR_UNISPED.Value = Now.AddDays(3)

        datAuswertVon_NCTSTR_AWOR.Value = Now
        datAuswertBis_NCTSTR_AWOR.Value = Now.AddDays(3)

        ComboBox1.Items.Clear()
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG SUBEN", "SUB"))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG SALZBURG", "SBG"))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG WAIDHAUS", "WAI"))
        'ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG NICKELSDORF", "NKD"))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG NEUHAUS", "NEU"))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG WEST (Atilla + Durmaz)", "SUW"))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATILLA", "ATILLA"))
        ComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DURMAZ", "DURMAZ"))
        ComboBox1.SelectedIndex = 0


        ComboBox2.Items.Clear()
        ComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
        ComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071678 - DE Brg (NEU)", "17DE0000000071678"))
        ComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05DE0000000009345 - DE Brg", "05DE0000000009345"))
        ComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg", "05AT510000G000FP7"))
        ComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
        ComboBox2.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("20AT520000G000092 - AT Brg ATILLA", "20AT520000G000092"))
        ComboBox2.SelectedIndex = 0


        cboDY_NCTS.Items.Clear()
        cboDY_NCTS.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("NCTS 5 (NEU)", "NCTS5"))
        cboDY_NCTS.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("NCTS 4", "NCTS4"))
        cboDY_NCTS.SelectedIndex = 0


        cboNCTSSystemDY.Items.Clear()
        cboNCTSSystemDY.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("NCTS 5 (NEU)", "NCTS5"))
        cboNCTSSystemDY.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("NCTS 4", "NCTS4"))
        cboNCTSSystemDY.SelectedIndex = 0

        cboDYDatumArt.Items.Clear()
        cboDYDatumArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Gestellungsdatum (Frist):", "LIMIT"))
        cboDYDatumArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Eröffnungsdatum", "OPEN"))
        cboDYDatumArt.SelectedIndex = 0

        cbxcbamQuelle.Items.Clear()
        cbxcbamQuelle.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DAKOSY", "DAKOSY"))
        cbxcbamQuelle.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DHF", "DHF"))
        cbxcbamQuelle.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DHF-UNISPED", "DHF-UNI"))
        cbxcbamQuelle.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("TELOTEC", "TELOTEC"))
        cbxcbamQuelle.SelectedIndex = 0

        Dim yearStart As Date = CDate("01.01." & Now.Year)
        von_CBAM.Value = yearStart
        bis_CBAM.Value = Now

        cboEZOLLBrg.Items.Clear()
        cboEZOLLBrg.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
        cboEZOLLBrg.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg", "05AT510000G000FP7"))
        cboEZOLLBrg.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
        cboEZOLLBrg.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("20AT520000G000092 - AT Brg ATILLA", "20AT520000G000092"))
        cboEZOLLBrg.SelectedIndex = 0


        cboBRG_Verimex.Items.Clear()
        cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
        ' cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE VERAG", "'17DE0000000071678','05DE0000000009345','05AT510000G000FP7'"))
        cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071678 - DE Brg (NEU)", "17DE0000000071678"))
        cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05DE0000000009345 - DE Brg", "05DE0000000009345"))
        cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg", "05AT510000G000FP7"))
        cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
        cboBRG_Verimex.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("20AT520000G000092 - AT Brg ATILLA", "20AT520000G000092"))
        cboBRG_Verimex.SelectedIndex = 0

        cboUnispedBrgDy.Items.Clear()
        cboUnispedBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
        cboUnispedBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT500000G000EU9  - AT Brg UNISPED", "05AT500000G000EU9 "))
        cboUnispedBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270  - DE Brg UNISPED", "17DE0000000071270 "))
        cboUnispedBrgDy.SelectedIndex = 0


        datEZOLLVon.Value = Now ' d.AddMonths(-3)
        datEZOLLBis.Value = Now.AddDays(3)


        cboEZOLLStatus.Items.Clear()
        cboEZOLLStatus.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("F", "'F'"))
        cboEZOLLStatus.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("F und FB", "'F', 'FB'"))
        cboEZOLLStatus.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("FB", "'Fb'"))
        cboEZOLLStatus.SelectedIndex = 0


        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "IMEX"
                GroupBox1.Enabled = False
                GroupBox3.Enabled = False
                grpDurmaz.Enabled = False
                GroupBox4.Enabled = False
                grpAMBAR.Enabled = False

                cboBrgDy.Items.Clear()
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
                cboBrgDy.SelectedIndex = 0

                tbcntr.TabPages.Remove(TabPage2)
                If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AUSWERTUNGEN_EV-FISKAL", "SDL") Then
                    tbcntr.TabPages.Remove(TabPage3)
                End If
            Case "UNISPED"

                'tbcntr.TabPages.Remove(TabPage1)
                tbcntr.TabPages.Remove(TabPage2)
                If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AUSWERTUNGEN_EV-FISKAL", "SDL") Then
                    tbcntr.TabPages.Remove(TabPage3)
                End If


                cboBrgDy.Items.Clear()
                '  cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270 - DE Brg (UNISPED)", "17DE0000000071270"))
                cboBrgDy.SelectedIndex = 0

                cboBrg_NCTSTR.Items.Clear()
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270 - DE Brg (UNISPED)", "17DE0000000071270"))
                cboBrg_NCTSTR.SelectedIndex = 0

                MyComboBox1.Items.Clear()
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270 - DE Brg (UNISPED)", "17DE0000000071270"))
                MyComboBox1.SelectedIndex = 0

                grpIMEX.Enabled = False
                grpDurmaz.Enabled = False
                grpVERIMEX.Enabled = False
                grpAMBAR.Enabled = False
                GroupBox8.Enabled = False
                GroupBox3.Enabled = False

                ' tbcntr.TabPages.Remove(TabPage4)
            Case Else

                cboBrgDy.Items.Clear()
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071678 - DE Brg (NEU)", "17DE0000000071678"))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05DE0000000009345 - DE Brg", "05DE0000000009345"))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg", "05AT510000G000FP7"))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("20AT520000G000092 - AT Brg ATILLA", "20AT520000G000092"))
                cboBrgDy.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270 - DE Brg (UNISPED)", "17DE0000000071270"))
                cboBrgDy.SelectedIndex = 0

                cboBrg_NCTSTR.Items.Clear()
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071678 - DE Brg (NEU)", "17DE0000000071678"))
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg", "05AT510000G000FP7"))
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("20AT520000G000092 - AT Brg ATILLA", "20AT520000G000092"))
                cboBrg_NCTSTR.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270 - DE Brg (UNISPED)", "17DE0000000071270"))
                cboBrg_NCTSTR.SelectedIndex = 0
                If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AUSWERTUNGEN_EV-FISKAL", "SDL") Then
                    tbcntr.TabPages.Remove(TabPage3)
                End If


                MyComboBox1.Items.Clear()
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071678 - DE Brg (NEU)", "17DE0000000071678"))
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05DE0000000009345 - DE Brg", "05DE0000000009345"))
                MyComboBox1.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg", "05AT510000G000FP7"))
                MyComboBox1.SelectedIndex = 0


        End Select

        cboBrgEZollTC.Items.Clear()
        cboBrgEZollTC.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ALLE", ""))
        cboBrgEZollTC.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("16AT520000G000VA6 - AT Brg IMEX", "16AT520000G000VA6"))
        cboBrgEZollTC.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("05AT510000G000FP7 - AT Brg VERAG", "05AT510000G000FP7"))
        cboBrgEZollTC.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071678 - DE Brg (NEU)", "17DE0000000071678"))
        cboBrgEZollTC.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("20AT520000G000092 - AT Brg ATILLA", "20AT520000G000092"))
        cboBrgEZollTC.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("17DE0000000071270 - DE Brg (UNISPED)", "17DE0000000071270"))
        cboBrgEZollTC.SelectedIndex = 0


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

        ''BRG übernehmen:
        'MyComboBox1.Items.AddRange(cboBrgDy.Items.Cast(Of String).ToArray())


        cboBRG_Verimex.SelectedIndex = 0



        datEZOLL_TC_Von.Value = Now ' d.AddMonths(-3)
        datEZOLL_TC_Bis.Value = Now.AddDays(3)

    End Sub


    Private Sub btnNCTSDurmaz_Click(sender As Object, e As EventArgs) Handles btnNCTSDurmaz.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW(datVonDurmaz.Text, datBisDurmaz.Text, "DURMAZ")
        frmPrintLayout.Show()
    End Sub


    Private Sub durmaz_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonatDurmaz.SelectedIndexChanged, txtJahrDurmaz.TextChanged
        If cboMonatDurmaz.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonatDurmaz.SelectedIndex) & "." & txtJahrDurmaz.Text)
        datVonDurmaz.Value = d
        datBisDurmaz.Value = d.AddMonths(1).AddDays(-1)
    End Sub


    Private Sub Atilla_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonatATILLA.SelectedIndexChanged, txtJahrATILLA.TextChanged
        If cboMonatATILLA.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonatATILLA.SelectedIndex) & "." & txtJahrATILLA.Text)
        datVonATILLA.Value = d
        datBisATILLA.Value = d.AddMonths(1).AddDays(-1)
    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs, Optional exportPDF As String = "", Optional exportEXCEL As String = "") Handles Button1.Click
        Dim operatorId As String = ""
        If cboEZOLLMandant.Text <> "" Then operatorId = cboEZOLLMandant.Text.Substring(0, 1)
        Dim sqlStr = getSQL_NCTS_EZOLL(datEZOLLVon.Text, datEZOLLBis.Text, DirectCast(cboEZOLLStatus.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, cboEZOLLBrg._value, cbxBestimmungszollstelleErreicht.CheckState, operatorId)


        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungTKontrolleEZOLL(sqlStr, datEZOLLVon.Text, datEZOLLBis.Text, DirectCast(cboEZOLLStatus.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, cboEZOLLBrg._value, cbxBestimmungszollstelleErreicht.CheckState, operatorId)
        If exportPDF = "" And exportEXCEL = "" Then
            frmPrintLayout.Show()
        Else
            AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                                If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                                If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            End Sub
        End If
    End Sub

    Function getSQL_NCTS_EZOLL(datVon As Date, datBis As Date, Stat As String, brg As String, BestimmungszollstelleErreicht As CheckState, operatorId As String, Optional Warenbezeichnung As Boolean = False, Optional Gesamtrohmasse As Boolean = False)
        If brg <> "" Then
            brg = " AND GRN = '" & brg & "' "
        End If

        Dim BestimmungErreichttxt As String = ""
        Select Case BestimmungszollstelleErreicht
            Case CheckState.Checked : BestimmungErreichttxt = " AND [DatumBestimmungErreicht] IS NOT null "
            Case CheckState.Unchecked : BestimmungErreichttxt = " AND [DatumBestimmungErreicht] IS null "
            Case CheckState.Indeterminate : BestimmungErreichttxt = " "
        End Select

        'GEHT HIER NICHTTTTTTT
        Dim EZOLL_SRV = "EZOLL"
        If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "UNISPED" Then
            EZOLL_SRV = "EZOLL_UNISPED"
        End If

        If operatorId <> "" Then
            operatorId = " AND OperatorId = '" & operatorId & "' "
        End If
        Dim sqlStr As String = " SELECT [ErledigungsTypID],[LRN],[CRN],[AnmeldungsDatum],[Gestellungsfrist],[Abgangszollstelle],[Bestimmungszollstelle],[DatumBestimmungErreicht]," & If(Warenbezeichnung, "[Warenbezeichnung], ", "") & If(Gesamtrohmasse, "[Gesamtrohmasse], ", "") & " [AnmID],[GRN],[GarantieWert] " &
                               " FROM [tblZolaris_EZoll_NCTS] " &
                               "       where [ErledigungsTypID] IN (" & Stat & ") " &
                                       BestimmungErreichttxt &
                                       brg &
                                        " AND CAST(Gestellungsfrist as Date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "'  " &
                                       operatorId &
                               "  ORDER BY /*convert(datetime, [DatumBestimmungErreicht], 103) ASC,*/convert(datetime, [Gestellungsfrist], 103) ASC,convert(datetime, [AnmeldungsDatum], 103) ASC "

        Return sqlStr

    End Function

    Function getSQL_NCTS_EZOLL_TELOTEC(datVon As Date, datBis As Date, StatVon As String, StatBis As String, brg As String) ', Optional Warenbezeichnung As Boolean = False, Optional Gesamtrohmasse As Boolean = False
        If brg <> "" Then
            brg = " AND GRN = '" & brg & "' "
        End If

        Dim sqlStr As String = "SELECT dec_CreateDate as Datum, Refs_LRN,telanm_CRN as CRN,telanm_Status as Status,([GVal]) as Betrag, telanm_ID as ID, telanm_ART as Art,GRN,ConeeTra_TIN as EORI,ConeeTra_Na as Empfänger,Represent_Na as Bearbeiter  , convert(date,CtrlRslt_DLimit ,104) as Gestellungsfrist,GVal as Garantiewert
                                FROM  tblTelotec_Sicherheit inner join [tblTelotec_Anmeldung] on telanm_id = telgrt_telanmId
                                WHERE [tblTelotec_Anmeldung].[CtrlRslt_DLimit] BETWEEN '" & datVon.ToShortDateString & " 00:00:00' AND '" & datBis.ToShortDateString & " 23:23:59' AND telanm_Status BETWEEN '" & StatVon & "' and '" & StatBis & "' AND [telnam_aktuellsteNachricht]=1  " & brg & " 
                                ORDER BY  convert(datetime, [CtrlRslt_DLimit], 103) ASC,convert(datetime, [dec_CreateDate], 103) ASC "
        Return sqlStr

    End Function


    Public Function genDocAndExport_TKontrolleEZOLL(datvon As Date, datbis As Date, stat As String, brg As String, bestimmungszollstelleErreicht As Boolean, operatorId As String, Optional exportPDF As String = "", Optional exportEXCEL As String = "") As Boolean

        Dim sqlStr = getSQL_NCTS_EZOLL(datEZOLLVon.Text, datEZOLLBis.Text, DirectCast(cboEZOLLStatus.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, cboEZOLLBrg._value, cbxBestimmungszollstelleErreicht.CheckState, operatorId)
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungTKontrolleEZOLL(sqlStr, datvon, datbis, stat, brg, bestimmungszollstelleErreicht, operatorId)
        Dim test As Boolean = False
        AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                            If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                            If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            test = True
                                                        End Sub
        Return True

        Dim c As Integer = 0
        While test = False 'Or c < 1000000
            '  c += 1
        End While
        ' MsgBox(test)
        Return test
    End Function


    Private Sub Button2_Click(sender As Object, e As EventArgs)
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW(datVonATILLA.Text, datBisATILLA.Text, "ATILLA")
        frmPrintLayout.Show()
    End Sub


    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        ' MsgBox("Diese Auswertung ist noch nicht verfügbar!")
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWZOLARIS(datVonATILLA.Text, datBisATILLA.Text, "ATILLA", MyComboBox1._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs)
        genDocAndExport_TKontrolleEZOLL(CDate("01.08.2016"), CDate("27.11.2016"), "'F', 'FB'", "05AT510000G000FP7", True, "1", "C:\Users\DEVELOPER1\Desktop\t.pdf")
    End Sub



    Sub doDY_NCTS4(Optional exportPDF As String = "", Optional exportEXCEL As String = "")
        Dim sqlStr = ""

        If cbxSplittungNachPos.Checked Then
            sqlStr = getSQL_NCTS_ATLAS_DY_POS(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False)
        Else
            sqlStr = getSQL_NCTS_ATLAS_DY(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False)
        End If



        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungTKontrolleDY(sqlStr, datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "")

        If exportPDF = "" And exportEXCEL = "" Then
            frmPrintLayout.Show()
        Else
            AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                                If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                                If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            End Sub
        End If
    End Sub


    Sub doDY_NCTS5(Optional exportPDF As String = "", Optional exportEXCEL As String = "")
        Dim sqlStr = ""



        If cbxSplittungNachPos.Checked Then
            sqlStr = getSQL_NCTS004_ATLAS_DY_POS(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False)
        Else
            sqlStr = getSQL_NCTS004_ATLAS_DY(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False)
        End If

        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungTKontrolleDY(sqlStr, datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "")




        If exportPDF = "" And exportEXCEL = "" Then
            frmPrintLayout.Show()
        Else
            AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                                If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                                If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            End Sub
        End If
    End Sub

    Private Sub Button17_Click(sender As Object, e As EventArgs, Optional exportPDF As String = "", Optional exportEXCEL As String = "") Handles Button17.Click
        Dim sqlStr = ""

        If cbxSplittungNachPos_NCTSTR.Checked Then
            sqlStr = getSQL_NCTS_ATLAS_NCTS_TR_POS(datVon_NCTSTR.Text, datBis_NCTSTR.Text, txtStatVon_NCTSTR.Text, txtStatBis_NCTSTR.Text, DirectCast(cboBrg_NCTSTR.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag_NCTSTR.Checked, False)
        Else
            sqlStr = getSQL_NCTS_ATLAS_NCTS_TR(datVon_NCTSTR.Text, datBis_NCTSTR.Text, txtStatVon_NCTSTR.Text, txtStatBis_NCTSTR.Text, DirectCast(cboBrg_NCTSTR.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag_NCTSTR.Checked, False)
        End If


        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungTKontrolleDY(sqlStr, datVon_NCTSTR.Text, datBis_NCTSTR.Text, txtStatVon_NCTSTR.Text, txtStatBis_NCTSTR.Text, DirectCast(cboBrg_NCTSTR.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "")

        If exportPDF = "" And exportEXCEL = "" Then
            frmPrintLayout.Show()
        Else
            AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                                If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                                If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            End Sub
        End If
    End Sub

    Function getSQL_NCTS_ATLAS_DY(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String, Optional anrechnungsZP As Boolean = False, Optional showANR As Boolean = True)

        If brg <> "" Then
            brg = " AND nctsSA_GRN = '" & brg & "' "
        Else

            Dim brg_AT As String = "05AT510000G000FP7"
            Dim brg_AT_IMEX As String = "16AT520000G000VA6"
            Dim brg_DE As String = "05DE0000000009345"
            Dim brg_DE_NEU As String = "17DE0000000071678"
            Dim brg_AT_ATILLA As String = "20AT520000G000092"

            brg = " AND nctsSA_GRN IN ( '" & brg_AT & "' , '" & brg_AT_IMEX & "' , '" & brg_DE & "' , '" & brg_DE_NEU & "', '" & brg_AT_ATILLA & "' ) "

        End If




        ' Dim sql As String = "SELECT ncts_MRN,ncts_Status,(nctsSA_AbgabenBetrag), ncts_dyaAnmID, ncts_ArtAnmeldung,nctsSA_GRN,ncts_Empfaenger_eori,ncts_Empfaenger_NLNR,ncts_Empfaenger_Name,ncts_Bearbeiter"
        Dim sqlStr = " SELECT  '' as [Anzahl Verz], isnull(ncts_Status,'') as Status, '' as Niederlassung, isnull(ncts_ObjectName,'') as Bezugsnummer,'' as LfdNr,"
        If showANR Then sqlStr &= " isnull(ncts_ANR,'') as ArbNr,"
        sqlStr &= " isnull(ncts_Empfaenger_Name,'') as Empfaenger,isnull(ncts_MRN,'') as MRN,ncts_Trans_DatumZeit as Antragsdatum,isnull(ncts_Bearbeiter,'') as Sachbearbeiter,[ncts_Wiedergestellungsdatum] as Gestellungsdatum,isnull(nctsSA_AbgabenBetrag,0) as [Sichertheits-Betrag], isnull(nctsSA_GRN,'') as Buergschaft  "
        'sql &= "  ,[ncts_ObjectName],[ncts_Trans_DatumZeit] as Transaktionsdatum,[ncts_dyaArt],[ncts_ANR],[ncts_MRN],[ncts_ObjectAlias],[ncts_GesamtRohmasse],[ncts_GesamtAnzahlPackstuecke] "
        sqlStr &= ",(SELECT COUNT(*) FROM tblDakosy_NCTSOut_Warenposition where nctsWP_NctsId=ncts_Id) as POS"
        If anrechnungsZP Then sqlStr &= ",(SELECT TOP (1)  convert(date,[dySt_ergZeitpunkt] ,104) FROM [tblDakosy_Statusmeldungen]  where dySt_dyId=[ncts_dyaAnmID] and [dySt_status] IN (53,60)  order by dySt_status) as AnrechnungRef"
        sqlStr &= " from tblDakosy_NCTSOut_Sicherheitsangaben inner join  [tblDakosy_NCTSOut] on ncts_Id = nctsSA_NctsId"
        sqlStr &= " WHERE ncts_Status between '" & StatVon & "' and '" & Statbis & "' "
        sqlStr &= " " & brg & " "
        sqlStr &= " AND CAST(ncts_Wiedergestellungsdatum as date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "' "
        sqlStr &= " ORDER BY [ncts_Wiedergestellungsdatum] ASC "

        Return sqlStr

    End Function


    Function getSQL_NCTS004_ATLAS_DY(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String, Optional anrechnungsZP As Boolean = False, Optional showANR As Boolean = True, Optional DYDatumArt As String = "LIMIT")

        If brg <> "" Then
            brg = " AND nctsGRT_GRN = '" & brg & "' "
        Else

            Dim brg_AT As String = "05AT510000G000FP7"
            Dim brg_AT_IMEX As String = "16AT520000G000VA6"
            Dim brg_DE As String = "05DE0000000009345"
            Dim brg_DE_NEU As String = "17DE0000000071678"
            Dim brg_AT_ATILLA As String = "20AT520000G000092"

            brg = " AND nctsGRT_GRN IN ( '" & brg_AT & "' , '" & brg_AT_IMEX & "' , '" & brg_DE & "' , '" & brg_DE_NEU & "', '" & brg_AT_ATILLA & "' ) "

        End If

        Dim datARt = ""
        Select Case DYDatumArt
            Case "LIMIT" : datARt = "ncts_LimitDate"
            Case "OPEN" : datARt = "ncts_Eroeffnung"
        End Select


        '*XXXXXXXXXXXXXXXXXXXXXXXX

        ' Dim sql As String = "SELECT ncts_MRN,ncts_Status,(nctsSA_AbgabenBetrag), ncts_dyaAnmID, ncts_ArtAnmeldung,nctsSA_GRN,ncts_Empfaenger_eori,ncts_Empfaenger_NLNR,ncts_Empfaenger_Name,ncts_Bearbeiter"
        Dim sqlStr = " SELECT  '' as [Anzahl Verz], isnull(ncts_Status,'') as Status, '' as Niederlassung, isnull(ncts_ObjectName,'') as Bezugsnummer,'' as LfdNr, "
        If showANR Then sqlStr &= " isnull(ncts_ANR,'') as ArbNr,"
        sqlStr &= " isnull(ncts_Consignee_Name,isnull(ncts_Consignee_IdentificationNumber,'')) as Empfaenger,isnull(ncts_MRN,'') as MRN,ncts_Trans_DatumZeit as Antragsdatum,isnull(ncts_Bearbeiter,'') as Sachbearbeiter,isnull(ncts_LimitDate,'') as Gestellungsdatum,[ncts_GestelltAm] as GestelltAm,isnull(nctsGRT_AmountToBeCovered,0) as [Sichertheits-Betrag], isnull(nctsGRT_GRN,'') as Buergschaft    "
        'sql &= "  ,[ncts_ObjectName],[ncts_Trans_DatumZeit] as Transaktionsdatum,[ncts_dyaArt],[ncts_ANR],[ncts_MRN],[ncts_ObjectAlias],[ncts_GesamtRohmasse],[ncts_GesamtAnzahlPackstuecke] "
        sqlStr &= ",( SELECT COUNT(*) FROM tblDakosy_NCTSOut004_HouseConsignment_ConsignmentItem where ncts_Id = [nctsHCCI_NctsId]) as POS"
        If anrechnungsZP Then sqlStr &= ",isnull(ncts_Ankunft,ncts_Erledigung) as AnrechnungRef"
        sqlStr &= " from tblDakosy_NCTSOut004_Guarantee inner join [tblDakosy_NCTSOut004] on ncts_Id = nctsGRT_NctsId "
        sqlStr &= " WHERE ncts_Status between '" & StatVon & "' and '" & Statbis & "' "
        sqlStr &= " " & brg & " "
        sqlStr &= " AND CAST(" & datARt & " as date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "' "
        sqlStr &= " ORDER BY " & datARt & "  ASC "

        Return sqlStr

    End Function


    Function getSQL_NCTS_ATLAS_NCTS_TR(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String, Optional anrechnungsZP As Boolean = False, Optional showANR As Boolean = True)

        If brg <> "" Then
            brg = " AND nctsSA_GRN = '" & brg & "' "
        Else

            Dim brg_AT As String = "05AT510000G000FP7"
            Dim brg_AT_IMEX As String = "16AT520000G000VA6"
            Dim brg_DE As String = "05DE0000000009345"
            Dim brg_DE_NEU As String = "17DE0000000071678"
            Dim brg_AT_ATILLA As String = "20AT520000G000092"

            brg = " AND nctsSA_GRN IN ( '" & brg_AT & "' , '" & brg_AT_IMEX & "' , '" & brg_DE & "' , '" & brg_DE_NEU & "', '" & brg_AT_ATILLA & "' ) "

        End If




        ' Dim sql As String = "SELECT ncts_MRN,ncts_Status,(nctsSA_AbgabenBetrag), ncts_dyaAnmID, ncts_ArtAnmeldung,nctsSA_GRN,ncts_Empfaenger_eori,ncts_Empfaenger_NLNR,ncts_Empfaenger_Name,ncts_Bearbeiter"
        Dim sqlStr = " SELECT  '' as [Anzahl Verz], isnull(ncts_Status,'') as Status, '' as Niederlassung, isnull(ncts_ObjectName,'') as Bezugsnummer,'' as LfdNr,"
        If showANR Then sqlStr &= " isnull(ncts_ANR,'') as ArbNr,"
        sqlStr &= " isnull(ncts_Empfaenger_Name,'') as Empfaenger,isnull(ncts_MRN,'') as MRN,ncts_Eroeffnung as Antragsdatum,isnull(ncts_Bearbeiter,'') as Sachbearbeiter,[ncts_Wiedergestellungsdatum] as Gestellungsdatum,isnull(nctsSA_AbgabenBetrag,0) as [Sichertheits-Betrag], isnull(nctsSA_GRN,'') as Buergschaft  "
        'sql &= "  ,[ncts_ObjectName],[ncts_Trans_DatumZeit] as Transaktionsdatum,[ncts_dyaArt],[ncts_ANR],[ncts_MRN],[ncts_ObjectAlias],[ncts_GesamtRohmasse],[ncts_GesamtAnzahlPackstuecke] "
        sqlStr &= ",(SELECT COUNT(*) FROM tblNCTS_TR_Warenposition where nctsWP_NctsId=ncts_Id) as POS"
        If anrechnungsZP Then sqlStr &= ", ncts_Ankunft as  AnrechnungRef"
        sqlStr &= " from tblNCTS_TR_Sicherheitsangaben inner join [tblNCTS_TR] on ncts_Id = nctsSA_NctsId"
        sqlStr &= " WHERE ncts_Status between '" & StatVon & "' and '" & Statbis & "' "
        sqlStr &= " " & brg & " "
        sqlStr &= " AND CAST(ncts_Wiedergestellungsdatum as date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "' "
        sqlStr &= " ORDER BY [ncts_Wiedergestellungsdatum] ASC "

        Return sqlStr

    End Function

    Function getSQL_NCTS_ATLAS_DY_POS(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String, Optional anrechnungsZP As Boolean = False, Optional showANR As Boolean = True)

        If brg <> "" Then
            brg = " AND nctsSA_GRN = '" & brg & "' "
        Else

            Dim brg_AT As String = "05AT510000G000FP7"
            Dim brg_AT_IMEX As String = "16AT520000G000VA6"
            Dim brg_DE As String = "05DE0000000009345"
            Dim brg_DE_NEU As String = "17DE0000000071678"
            Dim brg_AT_ATILLA As String = "20AT520000G000092"

            brg = " AND nctsSA_GRN IN ( '" & brg_AT & "' , '" & brg_AT_IMEX & "' , '" & brg_DE & "' , '" & brg_DE_NEU & "', '" & brg_AT_ATILLA & "' ) "

        End If





        ' Dim sql As String = "SELECT ncts_MRN,ncts_Status,(nctsSA_AbgabenBetrag), ncts_dyaAnmID, ncts_ArtAnmeldung,nctsSA_GRN,ncts_Empfaenger_eori,ncts_Empfaenger_NLNR,ncts_Empfaenger_Name,ncts_Bearbeiter"
        Dim sqlStr = " SELECT  '' as [Anzahl Verz], isnull(ncts_Status,'') as Status, '' as Niederlassung, isnull(ncts_ObjectName,'') as Bezugsnummer,'' as LfdNr,"
        If showANR Then sqlStr &= " isnull(ncts_ANR,'') as ArbNr,"
        sqlStr &= " isnull(ncts_Empfaenger_Name,'') as Empfaenger,isnull(ncts_MRN,'') as MRN,ncts_Trans_DatumZeit as Antragsdatum,isnull(ncts_Bearbeiter,'') as Sachbearbeiter,[ncts_Wiedergestellungsdatum] as GestellungsFrist,[ncts_GestelltAm] as GestelltAm,isnull(nctsSA_AbgabenBetrag,0) as [Sichertheits-Betrag], isnull(nctsSA_GRN,'') as Buergschaft  "
        'sql &= "  ,[ncts_ObjectName],[ncts_Trans_DatumZeit] as Transaktionsdatum,[ncts_dyaArt],[ncts_ANR],[ncts_MRN],[ncts_ObjectAlias],[ncts_GesamtRohmasse],[ncts_GesamtAnzahlPackstuecke] "
        sqlStr &= ", [nctsWP_PositionsNummer] as POS, [nctsWP_Warenbezeichnung] as Warenbezeichnung"
        If anrechnungsZP Then sqlStr &= ",(SELECT TOP (1)  convert(date,[dySt_ergZeitpunkt] ,104) FROM [tblDakosy_Statusmeldungen]  where dySt_dyId=[ncts_dyaAnmID] and [dySt_status] IN (53,60)  order by dySt_status) as AnrechnungRef"
        sqlStr &= ", ncts_AbgangsDienststellennummer as BesAbgZA, ncts_BestimmungsstelleDienststellennummer as BestZA, [nctsWP_Rohmasse] as Rohmasse"
        sqlStr &= " from tblDakosy_NCTSOut_Sicherheitsangaben inner join [VERAG].[dbo].[tblDakosy_NCTSOut] on ncts_Id = nctsSA_NctsId inner join [VERAG].[dbo].[tblDakosy_NCTSOut_Warenposition] on ncts_Id = [nctsWP_NctsId]"
        sqlStr &= " WHERE ncts_Status between '" & StatVon & "' and '" & Statbis & "' "
        sqlStr &= " " & brg & " "
        sqlStr &= " AND CAST(ncts_Wiedergestellungsdatum as date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "' "
        sqlStr &= " ORDER BY [ncts_Wiedergestellungsdatum] ASC "

        Return sqlStr

    End Function

    Function getSQL_NCTS004_ATLAS_DY_POS(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String, Optional anrechnungsZP As Boolean = False, Optional showANR As Boolean = True, Optional DYDatumArt As String = "LIMIT")

        If brg <> "" Then
            brg = " AND nctsGRT_GRN = '" & brg & "' "
        Else

            Dim brg_AT As String = "05AT510000G000FP7"
            Dim brg_AT_IMEX As String = "16AT520000G000VA6"
            Dim brg_DE As String = "05DE0000000009345"
            Dim brg_DE_NEU As String = "17DE0000000071678"
            Dim brg_AT_ATILLA As String = "20AT520000G000092"

            brg = " AND nctsGRT_GRN IN ( '" & brg_AT & "' , '" & brg_AT_IMEX & "' , '" & brg_DE & "' , '" & brg_DE_NEU & "', '" & brg_AT_ATILLA & "' ) "

        End If

        Dim datARt = ""
        Select Case DYDatumArt
            Case "LIMIT" : datARt = "ncts_LimitDate"
            Case "OPEN" : datARt = "ncts_Eroeffnung"
        End Select


        '*XXXXXXXXXXXXXXXXXXXXXXXX

        ' Dim sql As String = "SELECT ncts_MRN,ncts_Status,(nctsSA_AbgabenBetrag), ncts_dyaAnmID, ncts_ArtAnmeldung,nctsGRT_GRN,ncts_Empfaenger_eori,ncts_Empfaenger_NLNR,ncts_Empfaenger_Name,ncts_Bearbeiter"
        Dim sqlStr = " SELECT  '' as [Anzahl Verz], isnull(ncts_Status,'') as Status, '' as Niederlassung, isnull(ncts_ObjectName,'') as Bezugsnummer,'' as LfdNr,"
        If showANR Then sqlStr &= " isnull(ncts_ANR,'') as ArbNr,"
        sqlStr &= "  isnull(ncts_Consignee_Name,isnull(ncts_Consignee_IdentificationNumber,'')) as Empfaenger,isnull(ncts_MRN,'') as MRN,ncts_Trans_DatumZeit as Antragsdatum,isnull(ncts_Bearbeiter,'') as Sachbearbeiter,ncts_LimitDate as GestellungsFrist,[ncts_GestelltAm] as GestelltAm,isnull(nctsGRT_AmountToBeCovered,0) as [Sichertheits-Betrag], isnull(nctsGRT_GRN,'') as Buergschaft   "
        'sql &= "  ,[ncts_ObjectName],[ncts_Trans_DatumZeit] as Transaktionsdatum,[ncts_dyaArt],[ncts_ANR],[ncts_MRN],[ncts_ObjectAlias],ncts_GrossMass [ncts_GesamtRohmasse],'0' [ncts_GesamtAnzahlPackstuecke]  "
        sqlStr &= ",[nctsHCCI_DeclarationGoodsItemNumber] as POS, nctsHCCI_DescriptionOfGoods as Warenbezeichnung"
        If anrechnungsZP Then sqlStr &= ",isnull(ncts_Ankunft,ncts_Erledigung) as AnrechnungRef"
        sqlStr &= ", [ncts_CustomsOfficeOfDeparture] as BesAbgZA, [ncts_CustomsOfficeOfDestinationDeclared]  as BestZA, ncts_GrossMass as Rohmasse"
        sqlStr &= " from tblDakosy_NCTSOut004_Guarantee inner join [tblDakosy_NCTSOut004] on ncts_Id = nctsGRT_NctsId inner join [VERAG].[dbo].tblDakosy_NCTSOut004_HouseConsignment_ConsignmentItem on ncts_Id = [nctsHCCI_NctsId]"
        sqlStr &= " WHERE ncts_Status between '" & StatVon & "' and '" & Statbis & "' "
        sqlStr &= " " & brg & " "
        sqlStr &= " AND CAST(" & datARt & " as date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "' "
        sqlStr &= " ORDER BY " & datARt & "  ASC "

        Return sqlStr

    End Function


    Function getSQL_NCTS_ATLAS_NCTS_TR_POS(datVon As Date, datBis As Date, StatVon As String, Statbis As String, brg As String, nl As String, Optional anrechnungsZP As Boolean = False, Optional showANR As Boolean = True)

        If brg <> "" Then
            brg = " AND nctsSA_GRN = '" & brg & "' "
        Else

            Dim brg_AT As String = "05AT510000G000FP7"
            Dim brg_AT_IMEX As String = "16AT520000G000VA6"
            Dim brg_DE As String = "05DE0000000009345"
            Dim brg_DE_NEU As String = "17DE0000000071678"
            Dim brg_AT_ATILLA As String = "20AT520000G000092"

            brg = " AND nctsSA_GRN IN ( '" & brg_AT & "' , '" & brg_AT_IMEX & "' , '" & brg_DE & "' , '" & brg_DE_NEU & "' , '" & brg_AT_ATILLA & "' ) "

        End If


        ' Dim sql As String = "SELECT ncts_MRN,ncts_Status,(nctsSA_AbgabenBetrag), ncts_dyaAnmID, ncts_ArtAnmeldung,nctsSA_GRN,ncts_Empfaenger_eori,ncts_Empfaenger_NLNR,ncts_Empfaenger_Name,ncts_Bearbeiter"
        Dim sqlStr = " SELECT  '' as [Anzahl Verz], isnull(ncts_Status,'') as Status, '' as Niederlassung, isnull(ncts_ObjectName,'') as Bezugsnummer,'' as LfdNr,"
        If showANR Then sqlStr &= " isnull(ncts_ANR,'') as ArbNr,"
        sqlStr &= " isnull(ncts_Empfaenger_Name,'') as Empfaenger,isnull(ncts_MRN,'') as MRN,ncts_Eroeffnung  as Antragsdatum,isnull(ncts_Bearbeiter,'') as Sachbearbeiter,[ncts_Wiedergestellungsdatum] as GestellungsFrist,[ncts_GestelltAm] as GestelltAm,isnull(nctsSA_AbgabenBetrag,0) as [Sichertheits-Betrag], isnull(nctsSA_GRN,'') as Buergschaft  "
        'sql &= "  ,[ncts_ObjectName],[ncts_Trans_DatumZeit] as Transaktionsdatum,[ncts_dyaArt],[ncts_ANR],[ncts_MRN],[ncts_ObjectAlias],[ncts_GesamtRohmasse],[ncts_GesamtAnzahlPackstuecke] "
        sqlStr &= ", [nctsWP_PositionsNummer] as POS, [nctsWP_Warenbezeichnung] as Warenbezeichnung"
        If anrechnungsZP Then sqlStr &= ", ncts_Ankunft as  AnrechnungRef"
        sqlStr &= ", ncts_AbgangsDienststellennummer as BesAbgZA, ncts_BestimmungsstelleDienststellennummer as BestZA, [nctsWP_Rohmasse] as Rohmasse"
        sqlStr &= " from tblNCTS_TR_Sicherheitsangaben inner join [tblNCTS_TR] on ncts_Id = nctsSA_NctsId inner join tblNCTS_TR_Warenposition on ncts_Id = [nctsWP_NctsId]"
        sqlStr &= " WHERE ncts_Status between '" & StatVon & "' and '" & Statbis & "' "
        sqlStr &= " " & brg & " "
        sqlStr &= " AND CAST(ncts_Wiedergestellungsdatum as date) BETWEEN '" & datVon.ToShortDateString & "' AND  '" & datBis.ToShortDateString & "' "
        sqlStr &= " ORDER BY [ncts_Wiedergestellungsdatum] ASC "

        Return sqlStr

    End Function

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWDAKOSY(datVonDurmaz.Text, datBisDurmaz.Text, "DURMAZ", cboNCTSSystemDY._value, "")
        frmPrintLayout.Show()
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWDAKOSY(datVonATILLA.Text, datBisATILLA.Text, "ATILLA", cboNCTSSystemDY._value, MyComboBox1._value)
        frmPrintLayout.Show()
    End Sub

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click
        Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS(datVon.Text, datBis.Text, txtStatVon.Text, txtStatbis.Text, DirectCast(ComboBox2.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, DirectCast(ComboBox1.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value), "FMZOLL")
        If dt IsNot Nothing Then
            cProgramFunctions.genExcelFromDT_NEW(dt)
        End If
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click

        Select Case cboDY_NCTS._value
            Case "NCTS4" : doDY_NCTS4_XLS()
            Case "NCTS5" : doDY_NCTS5_XLS()
        End Select

    End Sub


    Sub doDY_NCTS4_XLS()

        If cbxSplittungNachPos.Checked Then
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS_DY_POS(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(clearDTPosSiBetrag(dt))
            End If
        Else
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS_DY(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(dt)
            End If
        End If
    End Sub

    Sub doDY_NCTS5_XLS()

        If cbxSplittungNachPos.Checked Then
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS004_ATLAS_DY_POS(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False, cboDYDatumArt._value), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(clearDTPosSiBetrag(dt))
            End If
        Else
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS004_ATLAS_DY(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False, cboDYDatumArt._value), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(dt)
            End If
        End If



    End Sub

    Function clearDTPosSiBetrag(dt2 As DataTable) As DataTable
        Dim dt As DataTable = dt2.Clone
        'Es muss die Pos-nr neu generiert werden, da die Daten nciht vollständig sind
        'Der Si-Betrag wird nur in der ersten Pos angezeigt

        Try

            dt = dt2.Clone()

            If dt2.Rows.Count > 0 Then
                For c As Integer = 0 To dt2.Rows.Count - 1
                    dt.ImportRow(dt2.Rows(c))
                Next
            End If

            'For Each r As DataRow In dt2.Rows
            '    dt.ImportRow(r)
            'Next
            Dim mrn = ""
            Dim cnt = 1
            dt.Columns("Sichertheits-Betrag").ReadOnly = False
            For Each r As DataRow In dt.Rows
                If mrn = r("MRN") Then
                    r("Sichertheits-Betrag") = "0"
                    cnt += 1
                Else
                    cnt = 1
                End If
                r("POS") = cnt
                mrn = r("MRN")
            Next
        Catch ex As Exception
            MsgBox("Fehler bei der Bereinigung der Positionen." & vbNewLine & ex.Message & ex.StackTrace)
        End Try
        Return dt
    End Function
    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        Dim operatorId As String = ""
        If cboEZOLLMandant.Text <> "" Then operatorId = cboEZOLLMandant.Text.Substring(0, 1)
        Dim sqlStr = getSQL_NCTS_EZOLL(datEZOLLVon.Text, datEZOLLBis.Text, DirectCast(cboEZOLLStatus.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, cboEZOLLBrg._value, cbxBestimmungszollstelleErreicht.CheckState, operatorId, cbxWarenbezeichnung.Checked, cbxWarenbezeichnung.Checked)
        Dim dt As DataTable = SQL.loadDgvBySql(sqlStr, "FMZOLL")
        If dt IsNot Nothing Then
            cProgramFunctions.genExcelFromDT_NEW(dt)
        End If
    End Sub

    Private Sub UsrCntlAuswertungenFiskalvertretung_42001_Load(sender As Object, e As EventArgs) Handles UsrCntlAuswertungenFiskalvertretung_42001.Load

    End Sub

    Private Sub cboMonatIMEX_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonatIMEX.SelectedIndexChanged, txtJahrIMEX.ValueChanged
        If cboMonatIMEX.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonatIMEX.SelectedIndex) & "." & txtJahrIMEX.Text)
        datVonImex.Value = d
        datBisImex.Value = d.AddMonths(1).AddDays(-1)
    End Sub


    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWDAKOSY(datVonImex.Text, datBisImex.Text, "IMEX", cboNCTSSystemDY._value, "")
        frmPrintLayout.Show()
    End Sub

    Private Sub UsrCntlAuswertungenUIDPruefung1_Load(sender As Object, e As EventArgs) Handles UsrCntlAuswertungenUIDPruefung1.Load

    End Sub

    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWDAKOSY(datVonAmbar.Text, datBisAmbar.Text, "AMBAR", cboNCTSSystemDY._value, "")
        frmPrintLayout.Show()
    End Sub

    Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonatAmbar.SelectedIndexChanged, txtJahrAmbar.ValueChanged
        If cboMonatAmbar.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonatAmbar.SelectedIndex) & "." & txtJahrAmbar.Text)
        datVonAmbar.Value = d
        datBisAmbar.Value = d.AddMonths(1).AddDays(-1)
    End Sub

    Private Sub Nctstr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonat_NCTSTR.SelectedIndexChanged, txtJahr_NCTSTR.ValueChanged
        If cboMonat_NCTSTR.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonat_NCTSTR.SelectedIndex) & "." & txtJahr_NCTSTR.Text)
        datAuswertVon_NCTSTR.Value = d
        datAuswertBis_NCTSTR.Value = d.AddMonths(1).AddDays(-1)
    End Sub


    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        Dim sqlStr = getSQL_NCTS_EZOLL_TELOTEC(datEZOLL_TC_Von.Value, datEZOLL_TC_Bis.Value, txtStatEZoll_TC_Von.Text, txtStatEZoll_TC_Bis.Text, cboBrgEZollTC._value)
        Dim dt As DataTable = SQL.loadDgvBySql(sqlStr, "FMZOLL")
        If dt IsNot Nothing Then
            cProgramFunctions.genExcelFromDT_NEW(dt)
        End If
    End Sub



    Private Sub UsrCntlAuswertungenFiskal_IntrastatMeldung1_Load(sender As Object, e As EventArgs) Handles UsrCntlAuswertungenFiskal_IntrastatMeldung1.Load

    End Sub

    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        If cbxSplittungNachPos.Checked Then
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS_DY_POS(datUnispedVon.Text, datUnispedBis.Text, txtUnispedStatVon.Text, txtUnispedStatBis.Text, DirectCast(cboUnispedBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxUnispedAnrechnungRefBetrag.Checked, False), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(clearDTPosSiBetrag(dt))
            End If
        Else
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS_DY(datUnispedVon.Text, datUnispedBis.Text, txtUnispedStatVon.Text, txtUnispedStatBis.Text, DirectCast(cboUnispedBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxUnispedAnrechnungRefBetrag.Checked, False), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(dt)
            End If
        End If
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs, Optional exportPDF As String = "", Optional exportEXCEL As String = "") Handles Button14.Click

        Dim sqlStr = ""

        If cbxSplittungNachPos.Checked Then
            sqlStr = getSQL_NCTS_ATLAS_DY_POS(datUnispedVon.Text, datUnispedBis.Text, txtUnispedStatVon.Text, txtUnispedStatBis.Text, DirectCast(cboUnispedBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxUnispedAnrechnungRefBetrag.Checked, False)
        Else
            sqlStr = getSQL_NCTS_ATLAS_DY(datUnispedVon.Text, datUnispedBis.Text, txtUnispedStatVon.Text, txtUnispedStatBis.Text, DirectCast(cboUnispedBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxUnispedAnrechnungRefBetrag.Checked, False)
        End If


        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungTKontrolleDY(sqlStr, datUnispedVon.Text, datUnispedBis.Text, txtUnispedStatVon.Text, txtUnispedStatBis.Text, DirectCast(cboUnispedBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "")

        If exportPDF = "" And exportEXCEL = "" Then
            frmPrintLayout.Show()
        Else
            AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
                                                                If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
                                                                If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
                                                            End Sub
        End If
    End Sub

    Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
        ' MsgBox("Diese Auswertung ist noch nicht verfügbar!")
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWZOLARIS(datVonDurmaz.Text, datBisDurmaz.Text, "DURMAZ", "")
        frmPrintLayout.Show()
    End Sub


    Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
        If cbxSplittungNachPos_NCTSTR.Checked Then
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS_NCTS_TR_POS(datVon_NCTSTR.Text, datBis_NCTSTR.Text, txtStatVon_NCTSTR.Text, txtStatBis_NCTSTR.Text, DirectCast(cboBrg_NCTSTR.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag_NCTSTR.Checked, False), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(clearDTPosSiBetrag(dt))
            End If
        Else
            Dim dt As DataTable = SQL.loadDgvBySql(getSQL_NCTS_ATLAS_NCTS_TR(datVon_NCTSTR.Text, datBis_NCTSTR.Text, txtStatVon_NCTSTR.Text, txtStatBis_NCTSTR.Text, DirectCast(cboBrg_NCTSTR.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag_NCTSTR.Checked, False), "FMZOLL")
            If dt IsNot Nothing Then
                cProgramFunctions.genExcelFromDT_NEW(dt)
            End If
        End If
    End Sub

    Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW_NCTSTR(datAuswertVon_NCTSTR.Text, datAuswertBis_NCTSTR.Text, "VERIMEX_OREGON", cboBRG_Verimex._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button19_Click(sender As Object, e As EventArgs) Handles Button19.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW_NCTSTR(datAuswertVon_NCTSTR.Text, datAuswertBis_NCTSTR.Text, "VERIMEX_MAVI", cboBRG_Verimex._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWTELOTEC(datVonATILLA.Text, datBisATILLA.Text, "ATILLA", MyComboBox1._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button21_Click(sender As Object, e As EventArgs) Handles Button21.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWTELOTEC(datVonATILLA.Text, datBisATILLA.Text, "IMEX", "")
        frmPrintLayout.Show()
    End Sub

    Private Sub cboMonat_NCTSTR_AWOR_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonat_NCTSTR_AWOR.SelectedIndexChanged, txtJahr_NCTSTR_AWOR.TextChanged
        If cboMonat_NCTSTR_AWOR.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonat_NCTSTR_AWOR.SelectedIndex) & "." & txtJahr_NCTSTR_AWOR.Text)
        datAuswertVon_NCTSTR_AWOR.Value = d
        datAuswertBis_NCTSTR_AWOR.Value = d.AddMonths(1).AddDays(-1)
    End Sub


    Private Sub cboMonat_NCTSTR_UNISPED_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMonat_NCTSTR_UNISPED.SelectedIndexChanged, txtJahr_NCTSTR_UNISPED.TextChanged
        If cboMonat_NCTSTR_UNISPED.SelectedIndex <= 0 Then Exit Sub
        Dim d As Date = CDate("01." & (cboMonat_NCTSTR_UNISPED.SelectedIndex) & "." & txtJahr_NCTSTR_UNISPED.Text)
        datAuswertVon_NCTSTR_UNISPED.Value = d
        datAuswertBis_NCTSTR_UNISPED.Value = d.AddMonths(1).AddDays(-1)
    End Sub

    Private Sub Button25_Click(sender As Object, e As EventArgs) Handles Button25.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW_NCTSTR(datAuswertVon_NCTSTR_AWOR.Text, datAuswertBis_NCTSTR_AWOR.Text, "MIC_AWOR", cboBRG_Verimex._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button23_Click(sender As Object, e As EventArgs) Handles Button23.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW_NCTSTR(datAuswertVon_NCTSTR_UNISPED.Text, datAuswertBis_NCTSTR_UNISPED.Text, "MIC_UNISPED", cboBRG_Verimex._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button22_Click(sender As Object, e As EventArgs) Handles Button22.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKW_NCTSTR(datAuswertVon_NCTSTR.Text, datAuswertBis_NCTSTR.Text, "VERIMEX_ATEZ", cboBRG_Verimex._value)
        frmPrintLayout.Show()
    End Sub

    Private Sub Button24_Click(sender As Object, e As EventArgs) Handles Button24.Click
        Dim frmPrintLayout As New frmPrintLayout()
        frmPrintLayout.AuswertungKontrolleLKWTELOTEC(datVonDurmaz.Text, datBisDurmaz.Text, "DURMAZ", "")
        frmPrintLayout.Show()
    End Sub


    'Private Sub Button32_Click(sender As Object, e As EventArgs) Handles Button32.Click
    '    doDY_NCTS5(True, False, "UNISPED")
    'End Sub
    'Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    '    doDY_NCTS5(True, False, "")
    'End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Select Case cboDY_NCTS._value
            Case "NCTS4" : doDY_NCTS4()
            Case "NCTS5" : doDY_NCTS5()
        End Select
    End Sub

    Private Sub UsrCntlAuswertungenAufschub_AbgabenKontrolleTRIER1_Load(sender As Object, e As EventArgs) Handles UsrCntlAuswertungenAufschub_AbgabenKontrolleTRIER1.Load

    End Sub

    Private Sub UsrCntlAuswertungenEV_Veranlagungen1_Load(sender As Object, e As EventArgs) Handles UsrCntlAuswertungenEV_Veranlagungen1.Load

    End Sub

    Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles excelCbam.Click

        If cbxcbamQuelle.SelectedIndex = 0 Then
            cbxcbamQuelle.Focus()
        End If

        Dim SQLString As String = ""
        Dim Quelle As String = "FMZOLL"

        Select Case cbxcbamQuelle._value
            Case "DAKOSY" : SQLString = getDAkosySQL(von_CBAM.Value, bis_CBAM.Value, cbxCBAM_Detaildaten.Checked) : Quelle = "FMZOLL"
            Case "DHF" : SQLString = getDHFSQL(von_CBAM.Value, bis_CBAM.Value, cbxCBAM_Detaildaten.Checked) : Quelle = "EZOLL"
            Case "DHF-UNI" : SQLString = getDHFSQL(von_CBAM.Value, bis_CBAM.Value, cbxCBAM_Detaildaten.Checked) : Quelle = "EZOLL_UNISPED"
            Case "TELOTEC" : SQLString = getTELOTECSQL(von_CBAM.Value, bis_CBAM.Value, cbxCBAM_Detaildaten.Checked) : Quelle = "FMZOLL"

        End Select


        Dim dt As DataTable = SQL.loadDgvBySql(SQLString, Quelle, 700)
        If dt IsNot Nothing Then
            cProgramFunctions.genExcelFromDT_NEW(dt)
        End If

    End Sub

    Private Function getDAkosySQL(von As Date, bis As Date, mitDetaildatensaetze As Boolean)

        Return "SELECT  
      Empfaenger.ezaAd_TeilnehmerEORI  AS EmpfängerEORI,
      Adressen.AdressenNr as KundenNr,
      Adressen.[Name 1] as Kunde," & IIf(mitDetaildatensaetze, " COUNT(DISTINCT eza_ANR) As Anzahl_Anmeldungen,COUNT(*) As Anzahl_Positionen,SUM(ezaWP_Eigenmasse) As Summe_Eigenmasse,SUM(ezaWP_Artikelpreis) As Summe_Rechnungspreis, MAX(eza_Anmeldedatum) As Letzte_Anmeldung,MIN(eza_Anmeldedatum)  As Erste_Anmeldung, ", "") & "kkd_Email as Email,
      Adressen.[E-Mail] as EMailKunde1,
	  Adressen.[E-Mail2] as EMailKunde2,
      isnull(Offerten.OffertenNr, '-') as Offert,
      Kunden.FilialenNr as FilialenNr


        From [VERAG].[dbo].[tblDakosy_EZA]
INNER Join tblDakosy_EZA_Warenposition ON ezaWP_EzaId = eza_Id
Left Join tblDakosy_EZA_Adressen AS Empfaenger ON Empfaenger.ezaAd_EZAId = eza_Id And Empfaenger.ezaAd_AdressTyp = 'CN'
        Left Join Kunden on Kunden.EORITIN = Empfaenger.ezaAd_TeilnehmerEORI 
Left Join Adressen on Adressen.AdressenNr = Kunden.KundenNr
Left Join Offerten on Offerten.KundenNr = Kunden.KundenNr And OffertenNr = 65 
Left Join tblKundenKontakt on Kunden.KundenNr = kkd_KundenNr And kkd_kkaBez  = 'Allgemein'

        WHERE
        ISNULL(eza_anmeldedatum, eza_Trans_DatumZeit)
        BETWEEN '" & von & "' AND '" & bis & "'
    And eza_status BETWEEN 41 And 60
    And (
           /* Eisen & Stahl */
           ezaWP_WarennummerEZT Like '72%' 
        Or ezaWP_WarennummerEZT Like '7301%'  -- Schienen, Profile etc.
        Or ezaWP_WarennummerEZT Like '7302%'
        Or ezaWP_WarennummerEZT Like '7303%'
        Or ezaWP_WarennummerEZT Like '7304%'
        Or ezaWP_WarennummerEZT Like '7305%'
        Or ezaWP_WarennummerEZT Like '7306%'

           /* Zement */
        Or ezaWP_WarennummerEZT Like '2523%'

           /* Aluminium */
        Or ezaWP_WarennummerEZT Like '76%'

           /* Düngemittel */
        Or ezaWP_WarennummerEZT Like '3102%'
        Or ezaWP_WarennummerEZT Like '3103%'
        Or ezaWP_WarennummerEZT Like '3104%'
        Or ezaWP_WarennummerEZT Like '3105%'

           /* Elektrizität */
        Or ezaWP_WarennummerEZT Like '2716%'

           /* Wasserstoff */
        Or ezaWP_WarennummerEZT Like '280410%'
    )

    GROUP BY 
      Empfaenger.ezaAd_TeilnehmerEORI,Adressen.AdressenNr, Adressen.[Name 1],Adressen.[E-Mail],Adressen.[E-Mail2], kkd_Email, Offerten.OffertenNr, Kunden.FilialenNr"


    End Function

    Private Function getDHFSQL(von As Date, bis As Date, mitDetaildatensaetze As Boolean)

        Return "				 select
    (SELECT TIN FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID ))EORI_Empfänger,
    Adressen.AdressenNr as KundenNr,
    Adressen.[Name 1] as Kunde, " & IIf(mitDetaildatensaetze, "COUNT(DISTINCT CRN) As Anzahl_Anmeldungen, COUNT(*) As Anzahl_Positionen,MAX(DecDT)  As Letzte_Anmeldung,MIN(DecDT) As Erste_Anmeldung,SUM(Net) As Summe_Eigenmasse,SUM(ItVal) As Summe_Rechnungspreis, ", "") &
    "kkd_Email as Email,
Adressen.[E-Mail] as EMailKunde1,
	  Adressen.[E-Mail2] as EMailKunde2,
    isnull(Offerten.OffertenNr, '-') as Offert,
    Kunden.FilialenNr as FilialenNr


				 --, (SELECT TIN FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID ))EORI_Empfänger
				 --, (SELECT Na FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID ))Empfänger
				   from zsAnmRefs 
				 inner join zsAnmGdsitem  on zsAnmRefs.LizenzNr=zsAnmGdsitem.LizenzNr and zsAnmRefs.AnmID=zsAnmGdsitem.AnmID and zsAnmRefs.VorgangID=zsAnmGdsitem.VorgangID and zsAnmRefs.OperatorID=zsAnmGdsitem.OperatorID
				 inner join zsAnmHea on zsAnmHea.LizenzNr=zsAnmGdsitem.LizenzNr and zsAnmHea.AnmID=zsAnmGdsitem.AnmID and zsAnmHea.VorgangID=zsAnmGdsitem.VorgangID and zsAnmHea.OperatorID=zsAnmGdsitem.OperatorID
				 inner join zsAnmDeclarant on zsAnmHea.LizenzNr=zsAnmDeclarant.LizenzNr and zsAnmHea.AnmID=zsAnmDeclarant.AnmID and zsAnmHea.VorgangID=zsAnmDeclarant.VorgangID and zsAnmHea.OperatorID=zsAnmDeclarant.OperatorID
				 inner join zsAnmTransp on zsAnmHea.LizenzNr=zsAnmTransp.LizenzNr and zsAnmHea.AnmID=zsAnmTransp.AnmID and zsAnmHea.VorgangID=zsAnmTransp.VorgangID and zsAnmHea.OperatorID=zsAnmTransp.OperatorID
				 Left Join " & VERAG_PROG_ALLGEMEIN.cAllgemein.FMZOLL_SERVER & ".[VERAG].[dbo].[Kunden] on Kunden.EORITIN = (SELECT TIN FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID ))
			     Left Join " & VERAG_PROG_ALLGEMEIN.cAllgemein.FMZOLL_SERVER & ".[VERAG].[dbo].Adressen on Adressen.AdressenNr = Kunden.KundenNr
                 Left Join " & VERAG_PROG_ALLGEMEIN.cAllgemein.FMZOLL_SERVER & ".[VERAG].[dbo].Offerten on Offerten.KundenNr = Kunden.KundenNr And OffertenNr = 65 
                 Left Join " & VERAG_PROG_ALLGEMEIN.cAllgemein.FMZOLL_SERVER & ".[VERAG].[dbo].tblKundenKontakt on Kunden.KundenNr = kkd_KundenNr And kkd_kkaBez  = 'Allgemein'
				where DecDT between '" & von & "' AND '" & bis & "'
						 
                 and 
                 (
                 left(ComCd,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
                 OR   left(ComCd,4)  between 7301 and 7311
                 OR   left(ComCd,4)  between 7205 and 7229
                 OR   left(ComCd,4)  between 7603 and 7614
                 OR   ComCd like '25070080%'
                 OR   ComCd like '283421%'
                 OR   ComCd like '260112%'
                 OR   ComCd like '720211%'
                 OR   ComCd like '720219%'
                 OR   ComCd like '720241%'
                 OR   ComCd like '720249%'
                 OR   ComCd like '720260%'
                 OR   ComCd like '280410%'  
                 ) 
                 and ComCd not like '310560%' 
                and crn is not null

                
                group by TIN, Adressen.AdressenNr ,Adressen.[Name 1],Adressen.[E-Mail],Adressen.[E-Mail2], kkd_Email, Offerten.OffertenNr, Kunden.FilialenNr, zsAnmHea.LizenzNr, zsAnmHea.OperatorID, zsAnmHea.VorgangID, zsAnmHea.AnmID"


    End Function

    Private Function getTELOTECSQL(von As Date, bis As Date, mitDetaildatensaetze As Boolean)

        Return "  SELECT  
      ConeeTra_TIN as EmpfängerEORI,
      Adressen.AdressenNr as KundenNr,
      Adressen.[Name 1] as Kunde," & IIf(mitDetaildatensaetze, " COUNT(DISTINCT telanm_CRN) As Anzahl_Anmeldungen,COUNT(*) As Anzahl_Positionen,MAX(dec_CreateDate)  As Letzte_Anmeldung,MIN(dec_CreateDate) As Erste_Anmeldung,SUM(dec_TotNet) As Summe_Eigenmasse,SUM(ValData_InvVal) As Summe_Rechnungspreis, ", "") &
     "kkd_Email as Email,
Adressen.[E-Mail] as EMailKunde1,
	  Adressen.[E-Mail2] as EMailKunde2,
      isnull(Offerten.OffertenNr, '-') as Offert,
     Kunden.FilialenNr as FilialenNr

	  
  FROM [VERAG].[dbo].[tblTelotec_Anmeldung]
  inner join tblTelotec_Positionsdaten on telpos_telanmId=telanm_id
Left Join Kunden on Kunden.EORITIN = ConeeTra_TIN
Left Join Adressen on Adressen.AdressenNr = Kunden.KundenNr
Left Join Offerten on Offerten.KundenNr = Kunden.KundenNr And OffertenNr = 65 
Left Join tblKundenKontakt on Kunden.KundenNr = kkd_KundenNr And kkd_kkaBez  = 'Allgemein'

  where 1=1  
  
and 
  (
  left(Item_ComCd,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
  OR   left(Item_ComCd,4)  between 7301 and 7311
  OR   left(Item_ComCd,4)  between 7205 and 7229
  OR   left(Item_ComCd,4)  between 7603 and 7614
  OR   Item_ComCd like '25070080%'
  OR   Item_ComCd like '283421%'
  OR   Item_ComCd like '260112%'
  OR   Item_ComCd like '720211%'
  OR   Item_ComCd like '720219%'
  OR   Item_ComCd like '720241%'
  OR   Item_ComCd like '720249%'
  OR   Item_ComCd like '720260%'
  OR   Item_ComCd like '280410%' 
  )
  and Item_ComCd not like '310560%' 

 and  telnam_aktuellsteNachricht=1

  and telanm_ART ='EUA'
  and dec_CreateDate  between '" & von & "' AND '" & bis & "'

  group by ConeeTra_TIN, Adressen.AdressenNr,Adressen.[Name 1],Adressen.[E-Mail],Adressen.[E-Mail2], kkd_Email, Offerten.OffertenNr, Kunden.FilialenNr"


    End Function




    'Private Sub Button5_Click(sender As Object, e As EventArgs, Optional exportPDF As String = "", Optional exportEXCEL As String = "") Handles Button5.Click
    '    Dim sqlStr = ""

    '    If cbxSplittungNachPos.Checked Then
    '        sqlStr = getSQL_NCTS_ATLAS_DY_POS(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False)
    '    Else
    '        sqlStr = getSQL_NCTS_ATLAS_DY(datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "", cbxAnrechnungRefBetrag.Checked, False)
    '    End If


    '    Dim frmPrintLayout As New frmPrintLayout()
    '    frmPrintLayout.AuswertungTKontrolleDY(sqlStr, datVonDy.Text, datBisDy.Text, txtStatVonDy.Text, txtStatBisDy.Text, DirectCast(cboBrgDy.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value, "")

    '    If exportPDF = "" And exportEXCEL = "" Then
    '        frmPrintLayout.Show()
    '    Else
    '        AddHandler frmPrintLayout.Viewer.LoadCompleted, Sub()
    '                                                            If exportPDF <> "" Then ExportToPDF(frmPrintLayout.Viewer.Document, exportPDF)
    '                                                            If exportEXCEL <> "" Then ExportToExcel(frmPrintLayout.Viewer.Document, exportEXCEL)
    '                                                        End Sub
    '    End If
    'End Sub


    'Private Sub Button5_Click(sender As Object, e As EventArgs, Optional exportPDF As String = "", Optional exportEXCEL As String = "") Handles Button5.Click

    '    Select Case cboDY_NCTS._value
    '        Case "NCTS4" : doDY_NCTS4(exportPDF, exportEXCEL)
    '        Case "NCTS5" : doDY_NCTS5(exportPDF, exportEXCEL)
    '    End Select

    'End Sub


    'Private Sub Button31_Click(sender As Object, e As EventArgs) Handles Button31.Click
    '    Select Case cboDY_NCTS._value
    '       ' Case "NCTS4" : doDY_NCTS4_XLS()
    '        Case "NCTS5" : doDY_NCTS5_XLS("UNISPED")
    '    End Select
    'End Sub
End Class
