Imports com.sun.org.apache.bcel.internal.generic
Imports DAKOSY_Worker
Imports DocumentFormat.OpenXml.Spreadsheet
Imports GrapeCity.DataVisualization.TypeScript
Imports Org.BouncyCastle.Crypto.Agreement
Imports VERAG_PROG_ALLGEMEIN
Imports VERAG_PROG_ALLGEMEIN.agsCustomsExchange

Public Class usrCntlCBAM

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Public kdnr As Integer = -1
    Dim AD As VERAG_PROG_ALLGEMEIN.cAdressen = Nothing
    Dim KD As VERAG_PROG_ALLGEMEIN.cKunde = Nothing
    Dim ERW As VERAG_PROG_ALLGEMEIN.cKundenErweitert = Nothing

    Sub New()
        InitializeComponent()
    End Sub

    Sub New(kdNr)
        InitializeComponent()
        Me.kdnr = kdNr
    End Sub

    Public Function CountCBAMTariffNumbersBySystemAndEORI(systemName As String, eori As String, dateFrom As Date, dateTo As Date) As Integer

        ' ------------------------------------------------------------
        ' CBAM-Pattern WHERE-Clause (HSCode)
        ' ------------------------------------------------------------
        Dim cbamWhere As String =
      VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("i.zaItem_HSCode")

        ' ------------------------------------------------------------
        ' SQL
        ' ------------------------------------------------------------
        Dim sql As String =
        "SELECT COUNT(distinct(z.Za_MRN)) AS Cnt " &
        "FROM VERAG.dbo.tblVERAG_CustomsDeclarations z " &
        "INNER JOIN VERAG.dbo.tblVERAG_CustomsDeclarations_Items i " &
        "   ON z.za_Id = i.zaItem_zaId " &
        "INNER JOIN VERAG.dbo.tblVERAG_CustomsDeclarations_Parties p " &
        "   ON z.za_Id = p.zaParty_zaId " &
        "WHERE z.za_System = @sys " &
        "  AND z.za_REGIME = 'IMPORT' " &
        "  AND z.za_IsFinalDeclaration = 1 " &
        "  AND z.if(ra_releaseDate,za_DeclarationDate) >= @dateFrom " &
        "  AND z.if(ra_releaseDate,za_DeclarationDate) <= @dateTo " &
        "  AND p.zaParty_EORI = @eori " &
        "  AND " & cbamWhere

        ' ------------------------------------------------------------
        ' Parameter
        ' ------------------------------------------------------------
        Dim p As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) From {
        New VERAG_PROG_ALLGEMEIN.SQLVariable("sys", systemName),
        New VERAG_PROG_ALLGEMEIN.SQLVariable("eori", eori),
        New VERAG_PROG_ALLGEMEIN.SQLVariable("dateFrom", dateFrom),
        New VERAG_PROG_ALLGEMEIN.SQLVariable("dateTo", dateTo)
    }

        ' ------------------------------------------------------------
        ' Execute
        ' ------------------------------------------------------------
        Dim dt As DataTable =
        New VERAG_PROG_ALLGEMEIN.SQL().
            loadDgvBySql_Param(sql, "VERAG", , p)

        If dt Is Nothing OrElse dt.Rows.Count = 0 OrElse IsDBNull(dt.Rows(0)("Cnt")) Then
            Return 0
        End If

        Return Convert.ToInt32(dt.Rows(0)("Cnt"))

    End Function


    Private Sub btnCBAMPruef_DAKOSY_Click(sender As Object, e As EventArgs) Handles btnCBAMPruef_DAKOSY.Click
        txtCBAMPruef_DAKOSY.Text = "-"
        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor
            Dim SQLSTR_WHERE_FIRMEN = ""
            If cbxVERAG.Checked Then SQLSTR_WHERE_FIRMEN &= "'SUB','WAI','SBG','NKD','NEU','AMBWO','AMB','IRU','EXP','SUW','DUR'"
            If cbxIMEX.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'IME'"
            If cbxUNISPED.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'ATSPED'" '???
            'isnull( eza_anmeldedatum, eza_Trans_DatumZeit)
            Dim SQLSTR = "
                SELECT  COUNT(distinct(Registriernummer_MRN)) FROM [tbl_DY_Zollmeldungen_Import]
                  where  Überlassungsdatum between '" & txtVon._value & "' and '" & txtBis._value & "'
                  and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("Warentarifnummer") & "   
                  
            "

            If SQLSTR_WHERE_FIRMEN <> "" Then
                SQLSTR &= " and Teilnehmer in ( " & SQLSTR_WHERE_FIRMEN & ")"
                SQLSTR &= " 
                            and left(Art_der_Vertretung,1) IN (2)
                            "
            Else
                'Die Unterabfrage hat mehr als einen Wert zurückgegeben. Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.
                'SQLSTR &= " 
                '            and (select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
                '          "
                'korrigierte Query:
                SQLSTR &= " 
                            and Empfänger_CN_EORI ='" & EORI & "'
                          "
            End If

            Dim dt = SQL.loadDgvBySql(SQLSTR, "AVISO", 600)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                txtCBAMPruef_DAKOSY.Text = dt.Rows(0)(0) & " Einträge"
                Me.Cursor = Cursors.Default
                Exit Sub
            End If

            txtCBAMPruef_DAKOSY.Text = "0"


        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 btnCBAMPruef_DAKOSY_Click(sender As Object, e As EventArgs) Handles btnCBAMPruef_DAKOSY.Click
    '    txtCBAMPruef_DAKOSY.Text = "-"
    '    Try
    '        Dim EORI = txtEori.Text
    '        If cbxVERAG.Checked Then EORI = "VERAG"
    '        If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
    '        If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
    '        If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
    '        Me.Cursor = Cursors.WaitCursor

    '        'isnull( eza_anmeldedatum, eza_Trans_DatumZeit)
    '        Dim SQLSTR = "
    '            SELECT  COUNT(*) FROM [tblDakosy_EZA] inner join tblDakosy_EZA_Warenposition on ezaWP_EzaId=eza_Id
    '              where  eza_anmeldedatum between '" & txtVon._value & "' and '" & txtBis._value & "'
    '              and 
    '              (
    '              left(ezaWP_WarennummerEZT,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7301 and 7311
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7205 and 7229
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7603 and 7614
    '              OR   ezaWP_WarennummerEZT like '25070080%'
    '              OR   ezaWP_WarennummerEZT like '283421%'
    '              OR   ezaWP_WarennummerEZT like '260112%'
    '              OR   ezaWP_WarennummerEZT like '720211%'
    '              OR   ezaWP_WarennummerEZT like '720219%'
    '              OR   ezaWP_WarennummerEZT like '720241%'
    '              OR   ezaWP_WarennummerEZT like '720249%'
    '              OR   ezaWP_WarennummerEZT like '720260%'
    '              OR   ezaWP_WarennummerEZT like '280410%'
    '                 )
    '              and ezaWP_WarennummerEZT not like '310560%'
    '                and (eza_status between 50  and 60 or [eza_ANR] LIKE 'ATC%')
    '        "

    '        If cbxVERAG.Checked Then
    '            SQLSTR &= " 
    '                        and eza_VertretungsVerhaeltnisCode=2
    '                      "
    '        Else
    '            'Die Unterabfrage hat mehr als einen Wert zurückgegeben. Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.
    '            'SQLSTR &= " 
    '            '            and (select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
    '            '          "
    '            'korrigierte Query:
    '            SQLSTR &= " 
    '                        and EXISTS (SELECT 1 FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId = eza_Id  AND [ezaAd_AdressTyp] = 'CN' AND isnull([ezaAd_NameFirma1], [ezaAd_TeilnehmerEORI]) ='" & EORI & "') 
    '                      "



    '        End If

    '        Dim dt = SQL.loadDgvBySql(SQLSTR, "FMZOLL", 600)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            txtCBAMPruef_DAKOSY.Text = dt.Rows(0)(0) & " Einträge"
    '            Me.Cursor = Cursors.Default
    '            Exit Sub
    '        End If

    '        txtCBAMPruef_DAKOSY.Text = "0"


    '    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 btnCBAMPruef_ALLE_Click(sender As Object, e As EventArgs) Handles btnCBAMPruef_ALLE.Click
        btnCBAMPruef_DAKOSY.PerformClick()
        btnCBAMPruef_DHF_VERAG.PerformClick()
        btnCBAMPruef_DHF_UNISPED.PerformClick()
        btnCBAMPruef_TELOTEC.PerformClick()
    End Sub

    Private Sub btnCBAMPruef_DHF_VERAG_Click(sender As Object, e As EventArgs) Handles btnCBAMPruef_DHF_VERAG.Click
        txtCBAMPruef_DHF_VERAG.Text = "-"
        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Or cbxUNISPED.Checked Or cbxIMEX.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQLSTR = "
                 select COUNT(*) from zsAnmRefs 
				 inner join zsAnmDHFRefs on zsAnmRefs.LizenzNr=zsAnmDHFRefs.LizenzNr and zsAnmRefs.AnmID=zsAnmDHFRefs.AnmID and zsAnmRefs.VorgangID=zsAnmDHFRefs.VorgangID and zsAnmRefs.OperatorID=zsAnmDHFRefs.OperatorID
			     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
					 	where DecDT between '" & txtVon._value & "' and '" & txtBis._value & "'
                  and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("ComCd") & "   
                 /* (
                  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 
                  and zsAnmDHFRefs.ErledigungsTypID like 'F%'
                   "

            If cbxVERAG.Checked Then
                SQLSTR &= " 
                                and DecRep IN(3)
                              
                          "
            Else
                SQLSTR &= " 
                          and (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 & "' 
                            "
            End If

            Dim dt = SQL.loadDgvBySql(SQLSTR, "EZOLL", 600)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                txtCBAMPruef_DHF_VERAG.Text = dt.Rows(0)(0) & " Einträge"
                Me.Cursor = Cursors.Default
                Exit Sub
            End If

            txtCBAMPruef_DHF_VERAG.Text = "0"

        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 btnCBAMPruef_DHF_UNISPED_Click(sender As Object, e As EventArgs) Handles btnCBAMPruef_DHF_UNISPED.Click
        txtCBAMPruef_DHF_UNISPED.Text = "-"
        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Or cbxUNISPED.Checked Or cbxIMEX.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQLSTR = "
                 select COUNT(*) from zsAnmRefs 
				  inner join zsAnmDHFRefs on zsAnmRefs.LizenzNr=zsAnmDHFRefs.LizenzNr and zsAnmRefs.AnmID=zsAnmDHFRefs.AnmID and zsAnmRefs.VorgangID=zsAnmDHFRefs.VorgangID and zsAnmRefs.OperatorID=zsAnmDHFRefs.OperatorID
			       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
					 	where DecDT between '" & txtVon._value & "' and '" & txtBis._value & "'
                    and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("ComCd") & "    
                  /*(
                  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 
                 and zsAnmDHFRefs.ErledigungsTypID like 'F%'
            "


            If cbxUNISPED.Checked Then
                SQLSTR &= " 
                                and DecRep IN(3)
                                    "
            Else
                SQLSTR &= " 
                          and (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 & "' 
                            "
            End If


            Dim dt = SQL.loadDgvBySql(SQLSTR, "EZOLL_UNISPED", 600)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                txtCBAMPruef_DHF_UNISPED.Text = dt.Rows(0)(0) & " Einträge"
                Me.Cursor = Cursors.Default
                Exit Sub
            End If

            txtCBAMPruef_DHF_UNISPED.Text = "0"

        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 btnCBAMPruef_TELOTEC_Click(sender As Object, e As EventArgs) Handles btnCBAMPruef_TELOTEC.Click
        txtCBAMPruef_TELOTEC.Text = "-"

        Dim SQLSTR_WHERE_FIRMEN = ""
        If cbxVERAG.Checked Then SQLSTR_WHERE_FIRMEN &= "'VERAG'"
        If cbxIMEX.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'IMEX'"
        If cbxUNISPED.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'UNISPED'"

        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Or cbxUNISPED.Checked Or cbxIMEX.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor
            Dim SQLSTR = "
                
             SELECT  count (*)
	  
            FROM [VERAG].[dbo].[tblTelotec_Anmeldung]
            inner join tblTelotec_Positionsdaten on telpos_telanmId=telanm_id

            where 1=1  
  
            and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("Item_ComCd") & "     
            /*  (
              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 '" & txtVon._value & "' and '" & txtBis._value & "'"

            If SQLSTR_WHERE_FIRMEN <> "" Then
                SQLSTR &= " and telanm_firma in ( " & SQLSTR_WHERE_FIRMEN & ")" 'nur IMEX????
            Else
                SQLSTR &= " and ConeeTra_TIN IN ( '" & EORI & "')"
            End If


            Dim dt = SQL.loadDgvBySql(SQLSTR, "FMZOLL", 600)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                txtCBAMPruef_TELOTEC.Text = dt.Rows(0)(0) & " Einträge"
                Me.Cursor = Cursors.Default
                Exit Sub
            End If

            txtCBAMPruef_TELOTEC.Text = "0"

        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 usrCntlCBAM_Load(sender As Object, e As EventArgs) Handles Me.Load
        cboJahr.Items.Clear()
        For yearCnt = 2023 To Now.Year
            cboJahr.Items.Add(yearCnt)
        Next

        cboJahr.Text = Now.Year
        txtCalcJahr.Text = Now.Year
        txtCalc_Defaut_Year.Text = Now.Year

        Dim ZertPreis As Double = 100
        txtCalc_Defaut_CertPrice._value = ZertPreis
        txtVERA_ZertPreis._value = ZertPreis
        Button8.Visible = True

        If Now.Month < 3 Then
            cboJahr.Text = Now.Year - 1
            cboQuartal.Text = "Q4"
        ElseIf Now.Month < 6 Then : cboQuartal.Text = "Q1"
        ElseIf Now.Month < 9 Then : cboQuartal.Text = "Q2"
        ElseIf Now.Month < 12 Then : cboQuartal.Text = "Q3"
        End If

        If kdnr > 0 Then
            AD = New VERAG_PROG_ALLGEMEIN.cAdressen(kdnr)
            KD = New VERAG_PROG_ALLGEMEIN.cKunde(kdnr)
            ERW = New VERAG_PROG_ALLGEMEIN.cKundenErweitert(kdnr)
        End If
        If KD IsNot Nothing Then
            txtEori.Text = KD.EORITIN
        End If

        cboIndirekt.Items.Clear()
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Spedition GmbH - DE4824105", "DE4824105"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Customs Service GmbH - ATEOS1000059121", "DE4ATEOS1000059121824105"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Zollservice GmbH - ATEOS1000000200", "ATEOS1000000200"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG Spedition AG - ATEOS1000000199", "ATEOS1000000199"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("IMEX Customs Service GmbH - ATEOS1000059735", "ATEOS1000059735"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Speditions GmbH - ATEOS1000000088", "ATEOS1000000088"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Zollservice GmbH - ATEOS1000040508", "ATEOS1000040508"))
        cboIndirekt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED Deutschland GmbH - DE7467540", "DE7467540"))


        UsCntlCBAM_Status1.Init(kdnr)

    End Sub

    Private Sub cboQuartal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboQuartal.SelectedIndexChanged, cboJahr.TextChanged
        If cboQuartal.Text <> "" And IsNumeric(cboJahr.Text) AndAlso cboJahr.Text.Length = 4 Then

            Select Case cboQuartal.Text
                Case "Q1" : txtVon._value = CDate("01.01." & cboJahr.Text) : txtBis._value = CDate(txtVon._value).AddMonths(3).AddDays(-1)
                Case "Q2" : txtVon._value = CDate("01.04." & cboJahr.Text) : txtBis._value = CDate(txtVon._value).AddMonths(3).AddDays(-1)
                Case "Q3" : txtVon._value = CDate("01.07." & cboJahr.Text) : txtBis._value = CDate(txtVon._value).AddMonths(3).AddDays(-1)
                Case "Q4" : txtVon._value = CDate("01.10." & cboJahr.Text) : txtBis._value = CDate(txtVon._value).AddMonths(3).AddDays(-1)
                Case "JAHR" : txtVon._value = CDate("01.01." & cboJahr.Text) : txtBis._value = CDate("31.12." & cboJahr.Text)

            End Select

        End If
    End Sub

    Private Sub btnCBAM_DS_DAKOSY_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DAKOSY.Click
        btnCBAM_DS_DAKOSY_Detail.Enabled = False
        btnCBAM_DS_DAKOSY_Copy.Enabled = False
        btnCBAM_DS_DAKOSY_Spedb.Enabled = False
        btnCBAM_DS_DAKOSY_GP.Enabled = False
        btnCBAM_DS_DAKOSY_Detail.Tag = ""
        btnCBAM_DS_DAKOSY_Spedb.Tag = ""
        btnCBAM_DS_DAKOSY_GP.Tag = ""


        Dim SQLSTR_WHERE_FIRMEN = ""
        If cbxVERAG.Checked Then SQLSTR_WHERE_FIRMEN &= "'SUB','WAI','SBG','NKD','NEU','AMBWO','AMB','IRU','EXP','SUW','DUR'"
        If cbxIMEX.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'IME'"
        If cbxUNISPED.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'ATSPED'" '???

        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQL_DAKOSY = ""
            Dim SQL_GP = ""
            getDY_Detail_SQL_DK(SQLSTR_WHERE_FIRMEN, EORI, SQL_DAKOSY, SQL_GP) '--> Aufbau SQL String

            Dim dt = SQL.loadDgvBySql(SQL_DAKOSY, "AVISO", 600)

            Dim dtGP = SQL.loadDgvBySql(SQL_GP, "AVISO", 600)



            Dim MRNNr As String = ""
            Dim SQLWhereMRN As String = ""
            Dim counter = 0


            Dim displayView = New DataView(dt, "", "RegistriernummerATLAS", DataViewRowState.CurrentRows)
            Dim distinctDT_MRN As DataTable = displayView.ToTable(True, "RegistriernummerATLAS")

            For Each r As DataRow In distinctDT_MRN.Rows
                MRNNr &= "'" & r.Item("RegistriernummerATLAS") & "'"
                counter += 1
                If (distinctDT_MRN.Rows.Count <> 0 And counter <> distinctDT_MRN.Rows.Count) Then MRNNr &= ","
            Next
            SQLWhereMRN &= " AND BelegNr not in (" & MRNNr & ")"


            Dim sqlNew = "select Speditionsbuch.[FilialenNr],[AbfertigungsNr],[UnterNr],[Abfertigungsdatum],[Bar],[Fakturiert],[BelegNr],[ErfassungsNr],[LKW Kennzeichen],[AbsenderKundenNr],[Absender],[AbsenderOffertenNr],[EmpfängerKundenNr],[Empfänger],[EmpfängerOffertenNr],[VermittlerKundenNr],[Vermittler],[VermittlerOffertenNr],[FrachtführerKundenNr],[Frachtführer],[AnzahlZA],[AnzahlZAFremd],[AnzahlZnV],[AnzahlZnVFremd],[AnzahlT1],[AnzahlT2],[AnzahlAE] from Speditionsbuch 
                           inner join Kunden on Speditionsbuch.[VermittlerKundenNr] = Kunden.KundenNr OR  Speditionsbuch.[EmpfängerKundenNr]= Kunden.KundenNr OR Speditionsbuch.[VermittlerKundenNr] = Kunden.KundenNr OR Speditionsbuch.[EmpfängerKundenNr] = Kunden.KundenNr 
                            where 1 = 1 AND Kunden.EORITIN = '" & EORI & "' AND BelegNr <> '' AND (Speditionsbuch.[Abfertigungsdatum] BETWEEN '" & txtVon._value & "' and '" & txtBis._value & "' )" & IIf(MRNNr <> "", SQLWhereMRN, "")

            Dim ReDaten As New DataTable

            If MRNNr <> "" Then
                ReDaten = SQL.loadDgvBySql("SELECT Positionsunterlagenart, Positionsunterlagennummer, Positionsunterlagendatum,Registriernummer_MRN  FROM [tbl_DY_Zollmeldungen_Import] WHERE [Positionsunterlagenart] in ('N380','N325') and Registriernummer_MRN IN (" & MRNNr & ")", "AVISO", 600)
            End If

            If ReDaten.Rows.Count > 0 Then
                dt.Columns("Rechnungsdatum").ReadOnly = False
                dt.Columns("Rechnungsnummer").ReadOnly = False
                dt.Columns("Rechnungsdatum").MaxLength = -1
                dt.Columns("Rechnungsnummer").MaxLength = -1
            End If

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then

                For Each r As DataRow In dt.Rows
                    Dim MDN_NR As String = r("RegistriernummerATLAS")

                    ' Look for matching row in dt2
                    Dim found() As DataRow = ReDaten.Select("Registriernummer_MRN = '" & MDN_NR & "'")

                    If found.Length > 0 Then
                        Dim rechnugnsdatum As String = found(0)("Positionsunterlagendatum")
                        If rechnugnsdatum <> "" Then rechnugnsdatum.Replace("00:00:00", "")
                        r("Rechnungsdatum") = rechnugnsdatum
                        r("Rechnungsnummer") = found(0)("Positionsunterlagennummer")
                    Else
                        r("Rechnungsdatum") = "-"
                        r("Rechnungsnummer") = "-"
                    End If

                Next

                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Detailbericht_" & txtVon._value & "-" & txtBis._value,, True)
                btnCBAM_DS_DAKOSY_Detail.Tag = path
                btnCBAM_DS_DAKOSY_Detail.Enabled = True
                btnCBAM_DS_DAKOSY_Copy.Enabled = True

            End If



            If dtGP IsNot Nothing AndAlso dtGP.Rows.Count > 0 Then

                If ReDaten.Rows.Count > 0 Then
                    dtGP.Columns("invoice date").ReadOnly = False
                    dtGP.Columns("invoice numbers").ReadOnly = False
                    dtGP.Columns("invoice date").MaxLength = -1
                    dtGP.Columns("invoice numbers").MaxLength = -1
                End If

                For Each r As DataRow In dtGP.Rows
                    Dim MDN_NR As String = r("declaration no")

                    ' Look for matching row in dt2
                    Dim found() As DataRow = ReDaten.Select("Registriernummer_MRN = '" & MDN_NR & "'")

                    If found.Length > 0 Then

                        Dim rechnugnsdatum As String = found(0)("Positionsunterlagendatum")
                        If rechnugnsdatum <> "" Then rechnugnsdatum.Replace("00:00:00", "")

                        r("invoice date") = rechnugnsdatum
                        r("invoice numbers") = found(0)("Positionsunterlagennummer")
                    Else
                        r("invoice date") = "-"
                        r("invoice numbers") = "-"
                    End If

                Next

                btnCBAM_DS_DAKOSY_GP.Tag = ""
                btnCBAM_DS_DAKOSY_GP.Tag = createExcelForGreenPulse(dtGP, EORI, IIf(AD.Ort <> "", AD.Ort, ""))
                btnCBAM_DS_DAKOSY_GP.Enabled = True

            End If


            Dim dtNew = SQL.loadDgvBySql(sqlNew, "FMZOLL", 600)
            If dtNew IsNot Nothing AndAlso dtNew.Rows.Count > 0 Then
                If dtNew.Columns.Contains("Packstücke") Then dtNew.Columns.Remove("Packstücke")
                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dtNew,,,,, False, EORI & "_Unterschiede zum Sped-Buch_" & txtVon._value & "-" & txtBis._value,, True)
                btnCBAM_DS_DAKOSY_Spedb.Enabled = True
                btnCBAM_DS_DAKOSY_Spedb.Tag = path
                Me.Cursor = Cursors.Default
            End If



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


        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


        btnCBAM_DS_DAKOSY_Summe.Enabled = False
        btnCBAM_DS_DAKOSY_Summe.Tag = ""

        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQLSTR = "
                 SELECT  
                      left(Tarifnummer,8) Tarifnummer,sum(Eigenmasse)Eigenmasse,sum(Rohmasse)Rohmasse,sum(Rechnungspreis)Rechnungspreis,VersendungsLand VersendungsLand ,isnull(LEFT(Verfahren2,2),'') Verfahren,isnull(right(left(Verfahren2,4),2),'') VorangegangenesVerfahren
                          FROM (
                      SELECT  
                               [Registriernummer_MRN] RegistriernummerATLAS 
                             ,PositionNo PositionsNummer
                             ,max(Überlassungsdatum) Anmeldedatum 
                             ,max([Bezugsnummer_LRN]) BezugsNr 
                             ,max([Art_der_Vertretung]) VertretungsVerhaeltnis 
                             ,max(Warentarifnummer) Tarifnummer
                             ,max(Eigenmasse) Eigenmasse 
                             ,max([VersendungsLand]) VersendungsLand
                             ,'DE' Bestimmungsland
                             ,max([Rechnungsbetrag])Rechnungspreis
                             ,max([Rechnungswährung]) Rechnungswaehrung
                             ,isnull(max(Empfänger_CN_EORI),'') as EmpfängerEORI
                             ,isnull(max(CZ_Name), '') as Empfänger
                             ,isnull(max(Versender_CZ_EORI),'') as AbsenderEORI
                             ,isnull(max(CN_Name), '') as Absender
                             ,max(Rohmasse)Rohmasse
                             ,max(Verfahren2)Verfahren2
	  
                         FROM [tbl_DY_Zollmeldungen_Import]
                                       where  
                                        Überlassungsdatum between '" & txtVon._value & "' and '" & txtBis._value & "'
                                      and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("Warentarifnummer") & "     
                                    /*  (
                                      left(Warentarifnummer,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
                                      OR   left(Warentarifnummer,4)  between 7301 and 7311
                                      OR   left(Warentarifnummer,4)  between 7205 and 7229
                                      OR   left(Warentarifnummer,4)  between 7603 and 7614
                                      OR   Warentarifnummer like '25070080%'
                                      OR   Warentarifnummer like '283421%'
                                      OR   Warentarifnummer like '260112%'
                                      OR   Warentarifnummer like '720211%'
                                      OR   Warentarifnummer like '720219%'
                                      OR   Warentarifnummer like '720241%'
                                      OR   Warentarifnummer like '720249%'
                                      OR   Warentarifnummer like '720260%'
                                      OR   Warentarifnummer like '280410%'
                                         )
                                      and Warentarifnummer not like '310560%' */
                    
            "


            If SQLSTR_WHERE_FIRMEN <> "" Then
                SQLSTR &= " and Teilnehmer in ( " & SQLSTR_WHERE_FIRMEN & ")"
                SQLSTR &= " 
                            and left(Art_der_Vertretung,1) IN (2)
                          "

            Else
                'Die Unterabfrage hat mehr als einen Wert zurückgegeben. Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.
                'SQLSTR &= " 
                '            and (select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
                '          "

                SQLSTR &= " 
                             and Empfänger_CN_EORI='" & EORI & "'
                          "

            End If

            SQLSTR &= "    group by Registriernummer_MRN,PositionNo
					                         ) as T1 group by VersendungsLand,left(Tarifnummer,8),Verfahren2 "



            Dim dt = SQL.loadDgvBySql(SQLSTR, "AVISO", 600)

            If cbxKosten.Checked Then
                ' =========================================================
                ' Spalten ergänzen (falls noch nicht vorhanden)
                ' =========================================================
                If Not dt.Columns.Contains("Def_benchmark") Then
                    dt.Columns.Add("Def_benchmark", GetType(Decimal))
                End If

                If Not dt.Columns.Contains("Def_Emission") Then
                    dt.Columns.Add("Def_Emission", GetType(Decimal))
                End If

                If Not dt.Columns.Contains("EstimatedCost") Then
                    dt.Columns.Add("EstimatedCost", GetType(Decimal))
                End If


                ' =========================================================
                ' Berechnung pro Zeile
                ' =========================================================
                For Each r As DataRow In dt.Rows

                    Dim benchmark As Object = Nothing
                    Dim emission As Object = Nothing
                    Dim weight = If(r("Rohmasse") Is DBNull.Value, r("Eigenmasse"), Convert.ToDecimal(r("Rohmasse")))
                    Dim year = If(txtBis._value <> "", CDate(txtBis._value).Year, Now.Year)

                    Dim cost As String = "0"
                    If IsNumeric(txtVERA_ZertPreis._value) Then
                        cost = cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(
                                cn_code:=Convert.ToString(r("Tarifnummer")),
                                weight / 1000,
                                country_code:=Convert.ToString(r("VersendungsLand")),
                                CDbl(txtVERA_ZertPreis._value),
                                year
                            )
                    Else
                        cost = cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM(
                                cn_code:=Convert.ToString(r("Tarifnummer")),
                                weight / 1000,
                                country_code:=Convert.ToString(r("VersendungsLand")),
                                see_total:=emission,
                                year,
                                benchmark_value:=benchmark
                            )
                    End If

                    r("Def_benchmark") = If(benchmark Is Nothing, DBNull.Value, benchmark)
                    r("Def_Emission") = If(emission Is Nothing, DBNull.Value, emission)
                    r("EstimatedCost") = If(String.IsNullOrWhiteSpace(cost), DBNull.Value, Convert.ToDecimal(cost))
                Next
            End If


            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Summenbericht_" & txtVon._value & "-" & txtBis._value)
                btnCBAM_DS_DAKOSY_Summe.Tag = path
                btnCBAM_DS_DAKOSY_Summe.Enabled = True
                btnCBAM_DS_DAKOSY_Copy.Enabled = True

                Me.Cursor = Cursors.Default

            End If



            ''----- XML ----------------------------------------------------------------------------------------------------------------------------------------

            'btnCBAM_DS_DAKOSY_XML.Enabled = False
            'btnCBAM_DS_DAKOSY_XML.Tag = ""

            'If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
            '    '---------------------------------------------------------------------------------------------------------------------------------------------
            '    doCBAM_XML(dt, EORI)
            '    '---------------------------------------------------------------------------------------------------------------------------------------------

            'End If


            ''---------------------------------------------------------------------------------------------------------------------------------------------

        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

    Sub getDY_Detail_SQL_DK(SQLSTR_WHERE_FIRMEN, EORI, ByRef SQL_DAKOSY, ByRef SQL_GP)

        SQL_GP = "SELECT  [Registriernummer_MRN] as 'declaration no' 
	                  ,max(Überlassungsdatum) as 'declaration date'
					  ,isnull(max(Empfänger_CN_EORI),'') as 'importer identification number'
					 ,'' as 'exporter identification number' 
					 , max(Warentarifnummer)  as 'commodity code'
					 ,max(Ursprungsland_ISO2)  as 'origin country code'
					 ,Left(max(Verfahren2),2) as 'requested procedure'
					 ,'' as 'previous procedure'
					 ,(max(Eigenmasse) / 1000) as 'net mass'
					 ,'TONNES' as 'type of measurement unit'
					 ,'' as 'invoice numbers'
					 ,'' as 'invoice date'
					 ,'' as 'member state auth'
					 ,'' as 'discharge bill waiver'
					 ,'' as 'authorisation'
					 ,'' as 'start time'
					 ,'' as 'end time'
					 ,'' as 'deadline'
					 ,isnull(max(Empfänger_CN_EORI),'')  as 'reporting declarant EORI number'
					 ,'' as 'type of representation'
					 ,isnull(max(CN_Name), '')  as 'importer title'
					 ,'' as 'importer email'
					 ,'' as 'importer phone'
					 ,isnull(max(CN_Ländercode), '')  as 'importer country code or member state'
					 ,'' as 'importer subdivision'
					 ,'' as 'importer city'
					 ,'' as 'importer street'
					 ,'' as 'importer street additional'
					 ,'' as 'importer address number'
					 ,'' as 'importer post code'
					 ,'' as 'importer po box'
					 ,'' as 'importer coordinate longitude (x)'
					 ,'' as 'importer coordinate latitude (y)'
			         ,isnull(max(CZ_Name), '')  as 'exporter title'
					 ,isnull(max(CZ_Ländercode), '')  as 'exporter country code or member state' 
					 ,'' as 'exporter street'
					 ,'' as 'exporter street additional'"

        SQL_DAKOSY = "SELECT  
                       [Registriernummer_MRN] RegistriernummerATLAS 
	                  ,PositionNo PositionsNummer
                      ,max(Überlassungsdatum) Anmeldedatum 
                     ,max([Bezugsnummer_LRN]) BezugsNr 
                     ,max([Art_der_Vertretung]) VertretungsVerhaeltnis 
                     ,max(Warentarifnummer) Tarifnummer
                     ,max(Eigenmasse) Eigenmasse 
                     ,max([VersendungsLand]) VersendungsLand
                     ,max(Ursprungsland_ISO2)  as 'Ursprungsland'
                     ,'DE' Bestimmungsland
                     ,max([DV1Rechnungsbetrag])Rechnungspreis
                     ,max([Rechnungswährung]) Rechnungswaehrung
                     ,isnull(max(Empfänger_CN_EORI),'') as EmpfängerEORI
                     ,isnull(max(CN_Name), '') as Empfänger
                     ,isnull(max(Versender_CZ_EORI),'') as AbsenderEORI
                     ,isnull(max(CZ_Name), '') as Absender
                     ,'' as 'Rechnungsnummer'
					 ,'' as 'Rechnungsdatum'
                    ,isnull(max(Anmelder_DT_EORI),'') as 'AnmelderEORI' "

        Dim SQLSTR = " FROM [tbl_DY_Zollmeldungen_Import]
                  where  
                  Überlassungsdatum between '" & txtVon._value & "' and '" & txtBis._value & "'
                    and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("Warentarifnummer") & "    
                 /* AND (
                    LEFT(Warentarifnummer,4) IN (2523,2716,2808,2814,2803,2818,3102,3103,3104,3105,
                                                 7201,7202,7203,7204,7325,7318,7326,7601,7602)
                    OR LEFT(Warentarifnummer,4) BETWEEN 7205 AND 7229
                    OR LEFT(Warentarifnummer,4) BETWEEN 7301 AND 7311
                    OR LEFT(Warentarifnummer,4) BETWEEN 7603 AND 7614
                    OR Warentarifnummer LIKE '25070080%'
                    OR Warentarifnummer LIKE '260112%'
                    OR Warentarifnummer LIKE '260300%'
                    OR Warentarifnummer LIKE '260600%'
                    OR Warentarifnummer LIKE '283421%'
                    OR Warentarifnummer LIKE '720211%'
                    OR Warentarifnummer LIKE '720219%'
                    OR Warentarifnummer LIKE '720241%'
                    OR Warentarifnummer LIKE '720249%'
                    OR Warentarifnummer LIKE '720260%'
                    OR Warentarifnummer LIKE '280410%'
                )
                AND Warentarifnummer NOT LIKE '310560%'*/
                  
            "

        If SQLSTR_WHERE_FIRMEN <> "" Then
            SQLSTR &= " and Teilnehmer in ( " & SQLSTR_WHERE_FIRMEN & ")"
            SQLSTR &= " 
                            and left(Art_der_Vertretung,1) IN (2)
                          "

        Else
            'Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.
            'SQLSTR &= " 
            '            and (select isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
            '          "

            SQLSTR &= " 
                            and Empfänger_CN_EORI='" & EORI & "' 
                          "
        End If

        SQLSTR &= "   group by Registriernummer_MRN,PositionNo"

        SQLSTR &= "  order by isnull(max(CZ_Name), ''), Registriernummer_MRN, PositionNo"

        SQL_GP &= SQLSTR
        SQL_DAKOSY &= SQLSTR


    End Sub

    Sub getDY_Detail_SQL_DHF(EORI, ByRef SQL_DHF, ByRef SQL_GP)


        'Conee = Importeur
        'Conor = Exportuer

        SQL_GP = "SELECT CRN as 'declaration no' 
	                  ,cast(DecDT as date) as 'declaration date'
					  ,isnull((SELECT TIN FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )),'') as 'importer identification number'
					  ,isnull((SELECT TIN FROM zsAnmConorTra WHERE (zsAnmConorTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConorTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConorTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConorTra.AnmID = zsAnmHea.AnmID )),'') as 'exporter identification number' 
					 , zsAnmGdsitem.ComCd  as 'commodity code'
					 ,Orig as 'origin country code'
					 ,Left(isnull(ProcCd, '00'),2) as 'requested procedure'
					 ,'' as 'previous procedure'
					 ,(Net / 1000) as 'net mass'
					 ,'TONNES' as 'type of measurement unit'
					 ,'' as 'invoice numbers'
					 ,'' as 'invoice date'
					 ,'' as 'member state auth'
					 ,'' as 'discharge bill waiver'
					 ,'' as 'authorisation'
					 ,'' as 'start time'
					 ,'' as 'end time'
					 ,'' as 'deadline'
					 ,''  as 'reporting declarant EORI number'
					 ,'' as 'type of representation'
					 ,isnull((SELECT Na FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )),'') as 'importer title'
					 ,'' as 'importer email'
					 ,'' as 'importer phone'
					 ,isnull((SELECT Ctry FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )),'')  as 'importer country code or member state'
					 ,'' as 'importer subdivision'
					 ,isnull((SELECT Cty FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )),'') as 'importer city'
					 ,isnull((SELECT Strt FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )),'')  as 'importer street'
					 ,'' as 'importer street additional'
					 ,'' as 'importer address number'
					 ,isnull((SELECT Pst FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )),'') as 'importer post code'
					 ,'' as 'importer po box'
					 ,'' as 'importer coordinate longitude (x)'
					 ,'' as 'importer coordinate latitude (y)'
			         ,isnull((SELECT Na FROM zsAnmConorTra WHERE (zsAnmConorTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConorTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConorTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConorTra.AnmID = zsAnmHea.AnmID )),'') as 'exporter title'
					 ,isnull((SELECT Ctry FROM zsAnmConorTra WHERE (zsAnmConorTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConorTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConorTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConorTra.AnmID = zsAnmHea.AnmID )),'') as 'exporter country code or member state' 
					 ,isnull((SELECT Strt FROM zsAnmConorTra WHERE (zsAnmConorTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConorTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConorTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConorTra.AnmID = zsAnmHea.AnmID )),'') as 'exporter street'
					 ,'' as 'exporter street additional'"

        SQL_DHF = "select  CRN Zollbelegnummer,cast(DecDT as date) Anmeldedatum,LRN,zsAnmGdsitem.ComCd Tarifnummer,Net Eigenmasse,ItVal Rechnungspreis
		                 , Orig Ursprungsland

		                 , isnull((SELECT TIN FROM zsAnmConorTra WHERE (zsAnmConorTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConorTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConorTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConorTra.AnmID = zsAnmHea.AnmID )),'') EORI_Absender 
		                 , isnull((SELECT Na FROM zsAnmConorTra WHERE (zsAnmConorTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConorTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConorTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConorTra.AnmID = zsAnmHea.AnmID )),'') Absender
		                 , isnull((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
		                 , isnull((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"

        Dim SQLSTR = " from  				 zsAnmRefs 
		                 inner join zsAnmDHFRefs on zsAnmRefs.LizenzNr=zsAnmDHFRefs.LizenzNr and zsAnmRefs.AnmID=zsAnmDHFRefs.AnmID and zsAnmRefs.VorgangID=zsAnmDHFRefs.VorgangID and zsAnmRefs.OperatorID=zsAnmDHFRefs.OperatorID
                   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
			 	                where DecDT between '" & txtVon._value & "' and '" & txtBis._value & "'
			                  and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("ComCd") & "
                           /* (
                            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
                            and zsAnmDHFRefs.ErledigungsTypID like 'F%'"

        If cbxVERAG.Checked Or cbxIMEX.Checked Or cbxUNISPED.Checked Then
            SQLSTR &= " 
                                and DecRep IN(3)
                             "
        Else
            SQLSTR &= " 
                             and (SELECT TIN FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )) LIKE '" & EORI & "' 
                 "
        End If

        SQL_GP &= SQLSTR
        SQL_GP &= " order by 'importer identification number'"

        SQL_DHF &= SQLSTR
        SQL_DHF &= " order by  Absender"


    End Sub


    Sub getDY_Detail_SQL_TT(EORI, ByRef SQL_TT, ByRef SQL_GP)

        'Conee = Importeur
        'Conor = Exportuer

        SQL_GP = "SELECT  telanm_CRN as 'declaration no' 
	                  ,cast(dec_CreateDate as Date) 'declaration date'
					  ,isnull(ConeeTra_TIN,'') as 'importer identification number'
					 ,isnull(ConorTra_TIN,'')  as 'exporter identification number' 
					 , Item_ComCd  as 'commodity code'
					 , isnull(Item_orig,'') as 'origin country code'
					 ,Left(Item_ProcCd,2) as 'requested procedure'
					 ,'' as 'previous procedure'
					 ,(isnull(Item_net,0) / 1000) as 'net mass'
					 ,'TONNES' as 'type of measurement unit'
					 ,'' as 'invoice numbers'
					 ,'' as 'invoice date'
					 ,'' as 'member state auth'
					 ,'' as 'discharge bill waiver'
					 ,'' as 'authorisation'
					 ,'' as 'start time'
					 ,'' as 'end time'
					 ,'' as 'deadline'
					 ,isnull(Declarant_TIN,'')  as 'reporting declarant EORI number'
					 ,isnull(Declarant_Na,'') as 'type of representation'
					 ,isnull(ConeeTra_Na,'')  as 'importer title'
					 ,'' as 'importer email'
					 ,'' as 'importer phone'
					 ,isnull(ConeeTra_Ctry,'')  as 'importer country code or member state'
					 ,'' as 'importer subdivision'
					 ,isnull(ConeeTra_Cty,'') as 'importer city'
					 ,isnull(ConeeTra_Strt,'')  as 'importer street'
					 ,'' as 'importer street additional'
					 ,'' as 'importer address number'
					 ,isnull(ConeeTra_Pst,'')  as 'importer post code'
					 ,'' as 'importer po box'
					 ,'' as 'importer coordinate longitude (x)'
					 ,'' as 'importer coordinate latitude (y)'
			         ,isnull(ConorTra_Na,'')  as 'exporter title'
					 ,isnull(ConorTra_Ctry,'')  as 'exporter country code or member state' 
					 ,isnull(ConorTra_Strt,'') as 'exporter street'
					 ,'' as 'exporter street additional'"

        SQL_TT = "SELECT  
                                  telanm_CRN Registriernummer  
	                              ,Pos_ID PositionsNummer
                                  ,dec_CreateDate Anmeldedatum 
                                  ,telanm_BezugsNr BezugsNr 
                                  ,Declarant_DecRep VertretungsVerhaeltnis 
                                  ,Item_ComCd Tarifnummer
	                              ,dec_TotNet Eigenmasse 
                                  ,Locs_Disp VersendungsLand
                                  , Locs_Dest Bestimmungsland
                                  ,Item_ItVal Rechnungspreis
                                  ,ValData_InvCurr Rechnungswaehrung
	                              ,ConeeTra_TIN as Empfänger
	                              ,ConeeTra_Na as Empfänger_
	                              ,ConorTra_TIN as Absender
	                              ,ConorTra_Na as Absender_ "

        Dim SQLSTR = "FROM [VERAG].[dbo].[tblTelotec_Anmeldung]
                              inner join tblTelotec_Positionsdaten on telpos_telanmId=telanm_id

                              where 1=1  
  
                                   and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("Item_ComCd") & "
                         /*
                              (
                              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 '" & txtVon._value & "' and '" & txtBis._value & "'"





        If cbxVERAG.Checked Or cbxIMEX.Checked Or cbxUNISPED.Checked Then
            SQLSTR &= " 
                            and Declarant_DecRep IN(1,3,5,7)
                          "
        Else
            SQLSTR &= " 
                            and ConeeTra_TIN='" & EORI & "'  /*and Declarant_DecRep NOT IN(1,3,5,7)*/
                          "
        End If





        SQL_GP &= SQLSTR
        SQL_GP &= "  order by ConorTra_TIN,telanm_CRN "
        SQL_TT &= SQLSTR
        SQL_TT &= "  order by Absender,telanm_CRN "


    End Sub

    'Private Sub btnCBAM_DS_DAKOSY_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DAKOSY.Click
    '    btnCBAM_DS_DAKOSY_Deteil.Enabled = False
    '    btnCBAM_DS_DAKOSY_Copy.Enabled = False
    '    btnCBAM_DS_DAKOSY_Deteil.Tag = ""

    '    Dim SQLSTR_WHERE_FIRMEN = ""
    '    If cbxVERAG.Checked Then SQLSTR_WHERE_FIRMEN &= "'VERAG'"
    '    If cbxIMEX.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'IMEX'"
    '    If cbxUNISPED.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'UNISPED'"

    '    Try
    '        Dim EORI = txtEori.Text
    '        If cbxVERAG.Checked Then EORI = "VERAG"
    '        If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
    '        If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
    '        If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
    '        Me.Cursor = Cursors.WaitCursor


    '        Dim SQLSTR = "
    '           SELECT  
    '                  [eza_ANR] RegistriernummerATLAS 
    '               ,ezaWP_PositionsNummer PositionsNummer
    '                  ,isnull( eza_anmeldedatum, eza_Trans_DatumZeit) Anmeldedatum 
    '                  ,[eza_ObjectName] BezugsNr 
    '                  ,[eza_VertretungsVerhaeltnisCode] VertretungsVerhaeltnis 
    '                  ,ezaWP_WarennummerEZT Tarifnummer
    '               ,ezaWP_Eigenmasse Eigenmasse 
    '                  ,[eza_VersendungsLandCode] VersendungsLand
    '                  ,[eza_Bestimmungsland] Bestimmungsland
    '                  ,[ezaWP_Artikelpreis]Rechnungspreis
    '                  ,[ezaWP_ArtikelpreisWaehrung] Rechnungswaehrung
    '               ,(select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN') as Empfänger
    '               ,(select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CZ') as Absender

    '              FROM [VERAG].[dbo].[tblDakosy_EZA]
    '              inner join tblDakosy_EZA_Warenposition on ezaWP_EzaId=eza_Id 
    '              where  
    '              eza_anmeldedatum between '" & txtVon._value & "' and '" & txtBis._value & "'
    '              and 
    '              (
    '              left(ezaWP_WarennummerEZT,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7301 and 7311
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7205 and 7229
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7603 and 7614
    '              OR   ezaWP_WarennummerEZT like '25070080%'
    '              OR   ezaWP_WarennummerEZT like '283421%'
    '              OR   ezaWP_WarennummerEZT like '260112%'
    '              OR   ezaWP_WarennummerEZT like '720211%'
    '              OR   ezaWP_WarennummerEZT like '720219%'
    '              OR   ezaWP_WarennummerEZT like '720241%'
    '              OR   ezaWP_WarennummerEZT like '720249%'
    '              OR   ezaWP_WarennummerEZT like '720260%'
    '              OR   ezaWP_WarennummerEZT like '280410%' 
    '              )
    '              and ezaWP_WarennummerEZT not like '310560%' 
    '                 and (eza_status between 50  and 60 or [eza_ANR] LIKE 'ATC%')

    '        "


    '        If cbxVERAG.Checked Or cbxIMEX.Checked Or cbxUNISPED.Checked Then
    '            SQLSTR &= " 
    '                        and eza_VertretungsVerhaeltnisCode=2
    '                      "
    '        Else
    '            'Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.

    '            'SQLSTR &= " 
    '            '            and (select isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
    '            '          "

    '            SQLSTR &= " 
    '                        and EXISTS (select 1 FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN' AND isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI])='" & EORI & "') 
    '                      "
    '        End If

    '        If SQLSTR_WHERE_FIRMEN <> "" Then SQLSTR &= " and EZA_firma in ( " & SQLSTR_WHERE_FIRMEN & ")"

    '        SQLSTR &= "  order by Absender,eza_ANR, tblDakosy_EZA_Warenposition.ezaWP_PositionsNummer"


    '        Dim dt = SQL.loadDgvBySql(SQLSTR, "FMZOLL", 600)
    '        MsgBox(SQLSTR)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Detailbericht_" & txtVon._value & "-" & txtBis._value)
    '            btnCBAM_DS_DAKOSY_Deteil.Tag = path
    '            btnCBAM_DS_DAKOSY_Deteil.Enabled = True
    '            btnCBAM_DS_DAKOSY_Copy.Enabled = True
    '            Me.Cursor = Cursors.Default

    '        End If



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


    '    '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


    '    btnCBAM_DS_DAKOSY_Summe.Enabled = False
    '    btnCBAM_DS_DAKOSY_Summe.Tag = ""

    '    Try
    '        Dim EORI = txtEori.Text
    '        If cbxVERAG.Checked Then EORI = "VERAG"
    '        If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
    '        If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
    '        If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
    '        Me.Cursor = Cursors.WaitCursor

    '        Dim SQLSTR = "
    '            SELECT  
    '                 left(ezaWP_WarennummerEZT,8) Tarifnummer,sum(ezaWP_Eigenmasse)Eigenmasse,sum(ezaWP_Rohmasse)Rohmasse,sum(ezaWP_Artikelpreis)Rechnungspreis,eza_VersendungsLandCode VersendungsLand ,isnull(ezaWP_AnmeldeVErfahren,'') Verfahren,isnull([ezaWP_VerfahrensCodeVorangegangenesVerfahren],'') VorangegangenesVerfahren

    '                FROM [VERAG].[dbo].[tblDakosy_EZA]
    '              inner join tblDakosy_EZA_Warenposition on ezaWP_EzaId=eza_Id
    '               where  
    '                eza_anmeldedatum between '" & txtVon._value & "' and '" & txtBis._value & "'
    '              and 
    '              (
    '              left(ezaWP_WarennummerEZT,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7301 and 7311
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7205 and 7229
    '              OR   left(ezaWP_WarennummerEZT,4)  between 7603 and 7614
    '              OR   ezaWP_WarennummerEZT like '25070080%'
    '              OR   ezaWP_WarennummerEZT like '283421%'
    '              OR   ezaWP_WarennummerEZT like '260112%'
    '              OR   ezaWP_WarennummerEZT like '720211%'
    '              OR   ezaWP_WarennummerEZT like '720219%'
    '              OR   ezaWP_WarennummerEZT like '720241%'
    '              OR   ezaWP_WarennummerEZT like '720249%'
    '              OR   ezaWP_WarennummerEZT like '720260%'
    '              OR   ezaWP_WarennummerEZT like '280410%'

    '              )
    '                and ezaWP_WarennummerEZT not like '310560%'
    '                    and (eza_status between 50  and 60 or [eza_ANR] LIKE 'ATC%')

    '        "

    '        If cbxVERAG.Checked Or cbxIMEX.Checked Or cbxUNISPED.Checked Then
    '            SQLSTR &= " 
    '                        and eza_VertretungsVerhaeltnisCode=2
    '                      "
    '        Else
    '            'Die Unterabfrage hat mehr als einen Wert zurückgegeben. Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.
    '            'SQLSTR &= " 
    '            '            and (select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
    '            '          "

    '            SQLSTR &= " 
    '                         and EXISTS (select 1  FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN' and isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI])='" & EORI & "') 
    '                      "

    '        End If

    '        If SQLSTR_WHERE_FIRMEN <> "" Then SQLSTR &= " and EZA_firma in ( " & SQLSTR_WHERE_FIRMEN & ")"

    '        SQLSTR &= "   group by eza_VersendungsLandCode,left(ezaWP_WarennummerEZT,8),ezaWP_AnmeldeVErfahren,ezaWP_VerfahrensCodeVorangegangenesVerfahren"


    '        Dim dt = SQL.loadDgvBySql(SQLSTR, "FMZOLL", 600)
    '        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '            Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Summenbericht_" & txtVon._value & "-" & txtBis._value)
    '            btnCBAM_DS_DAKOSY_Summe.Tag = path
    '            btnCBAM_DS_DAKOSY_Summe.Enabled = True
    '            btnCBAM_DS_DAKOSY_Copy.Enabled = True

    '            Me.Cursor = Cursors.Default

    '        End If



    '        ''----- XML ----------------------------------------------------------------------------------------------------------------------------------------

    '        'btnCBAM_DS_DAKOSY_XML.Enabled = False
    '        'btnCBAM_DS_DAKOSY_XML.Tag = ""

    '        'If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
    '        '    '---------------------------------------------------------------------------------------------------------------------------------------------
    '        '    doCBAM_XML(dt, EORI)
    '        '    '---------------------------------------------------------------------------------------------------------------------------------------------

    '        'End If


    '        ''---------------------------------------------------------------------------------------------------------------------------------------------

    '    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 ButtonXML_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If sender Is Button1 Then

            Button2.Enabled = False
            btnCBAM_DS_DAKOSY_XML.Enabled = False
            btnCBAM_DS_DAKOSY_XML.Tag = ""

        End If

        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQLSTR = "
                SELECT  
                     left(ezaWP_WarennummerEZT,8) Tarifnummer,sum(ezaWP_Eigenmasse)Eigenmasse,sum(ezaWP_Rohmasse)Rohmasse,sum(ezaWP_Artikelpreis)Rechnungspreis,eza_VersendungsLandCode VersendungsLand ,isnull(ezaWP_AnmeldeVErfahren,'') Verfahren,isnull([ezaWP_VerfahrensCodeVorangegangenesVerfahren],'') VorangegangenesVerfahren
                   ,isnull(ezaAd_NameFirma1,'') as Empfänger,isnull(ezaAd_TeilnehmerEORI,'') as EmpfängerEORI
	                 
                    FROM [VERAG].[dbo].[tblDakosy_EZA]
                  inner join tblDakosy_EZA_Warenposition on ezaWP_EzaId=eza_Id
                  inner join tblDakosy_EZA_Adressen on ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN' 
                   where  
                    eza_anmeldedatum between '" & txtVon._value & "' and '" & txtBis._value & "'
                    and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("ezaWP_WarennummerEZT") & " 
                /*  (
                  left(ezaWP_WarennummerEZT,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
                  OR   left(ezaWP_WarennummerEZT,4)  between 7301 and 7311
                  OR   left(ezaWP_WarennummerEZT,4)  between 7205 and 7229
                  OR   left(ezaWP_WarennummerEZT,4)  between 7603 and 7614
                  OR   ezaWP_WarennummerEZT like '25070080%'
                  OR   ezaWP_WarennummerEZT like '283421%'
                  OR   ezaWP_WarennummerEZT like '260112%'
                  OR   ezaWP_WarennummerEZT like '720211%'
                  OR   ezaWP_WarennummerEZT like '720219%'
                  OR   ezaWP_WarennummerEZT like '720241%'
                  OR   ezaWP_WarennummerEZT like '720249%'
                  OR   ezaWP_WarennummerEZT like '720260%'
                  OR   ezaWP_WarennummerEZT like '280410%'
   
                  )
                    and ezaWP_WarennummerEZT not like '310560%'*/
                        and (eza_status between 50  and 60 or [eza_ANR] LIKE 'ATC%')
                    
            "

            If cbxVERAG.Checked Then
                SQLSTR &= " 
                            and eza_VertretungsVerhaeltnisCode=2
                          "
            Else
                ''Die Unterabfrage hat mehr als einen Wert zurückgegeben. Das ist nicht zulässig, wenn die Unterabfrage auf =, !=, <, <=, > oder >= folgt oder als Ausdruck verwendet wird.
                'SQLSTR &= " 
                '            and (select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
                '          "

                SQLSTR &= " 
                            and EXISTS(select 1 FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN' AND isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI])='" & EORI & "') 
                          "
            End If

            SQLSTR &= "   group by ezaAd_NameFirma1,ezaAd_TeilnehmerEORI,eza_VersendungsLandCode,left(ezaWP_WarennummerEZT,8),ezaWP_AnmeldeVErfahren,ezaWP_VerfahrensCodeVorangegangenesVerfahren"


            Dim dt = SQL.loadDgvBySql(SQLSTR, "FMZOLL", 600)



            '----- XML ----------------------------------------------------------------------------------------------------------------------------------------
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                '---------------------------------------------------------------------------------------------------------------------------------------------
                doCBAM_XML(dt, EORI)
                '---------------------------------------------------------------------------------------------------------------------------------------------
                Button2.Enabled = True
                btnCBAM_DS_DAKOSY_XML.Enabled = True

            End If

            '---------------------------------------------------------------------------------------------------------------------------------------------

        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 Button3gp_Click(sender As Object, e As EventArgs) Handles Button3.Click

        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQLSTR_WHERE_FIRMEN = ""
            If cbxVERAG.Checked Then SQLSTR_WHERE_FIRMEN &= "'SUB','WAI','SBG','NKD','NEU','AMBWO','AMB','IRU','EXP','SUW','DUR'"
            If cbxIMEX.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'IME'"
            If cbxUNISPED.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'ATSPED'" '???

            Dim SQL_DAKOSY = ""
            getDY_Detail_SQL_DK(SQLSTR_WHERE_FIRMEN, EORI, SQL_DAKOSY, "") '--> Aufbau SQL String


            Dim dt = SQL.loadDgvBySql(SQL_DAKOSY, "AVISO", 600)
            lblKafkaCnt.Text = "-"

            '----- kafka / Greenpulse ----------------------------------------------------------------------------------------------------------------------------------------
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then

                lblKafkaCnt.Text = "0/" & dt.Rows.Count

                Dim uniqueValues = dt.AsEnumerable() _
                    .Select(Function(r) r.Field(Of String)("RegistriernummerATLAS")) _
                    .Distinct() _
                    .ToList()

                doCBAM_KafkaFromDakosy(uniqueValues)

            End If

            '---------------------------------------------------------------------------------------------------------------------------------------------

        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 doCBAM_KafkaFromDakosy(list As List(Of String))
        Try
            Dim cnt = 1
            For Each RegistriernummerATLAS In list
                lblKafkaCnt.Text = cnt & "/" & list.Count
                Me.Refresh()
                cnt += 1

                Dim mrn As String = RegistriernummerATLAS 'g("RegistriernummerATLAS")
                Dim EZA = cDakosyEZA.LOADByMRN(mrn, True)


                Dim key = cATEZ_Greenpulse_KafkaDecs.GetUniqueKey_Pipe("DE", "DAKOSY", mrn)

                ' Objekt
                Dim rec = cDakosyEZA_Greenpulse.BuildByMrn(EZA)
                Dim dr = cATEZ_Greenpulse_KafkaDecs.InsertOrUpdateToKafkaSync_Bool(rec, key, 30000)

                'Unlerlagen
                Dim rec_inv = cDakosyEZA_Greenpulse.BuildByMrnInvoices(EZA)
                Dim dr_inv = cATEZ_Greenpulse_KafkaInvoices.InsertOrUpdateToKafkaSync_Bool(rec_inv, key, 30000)



                '     MessageBox.Show($"OK: {dr.Status} @ {dr.TopicPartitionOffset}")
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub doCBAM_KafkaFromVERAG_CostomsDeclarations(list As List(Of String))
        Try
            Dim cnt = 1
            For Each MRN In list
                lblKafkaCnt.Text = cnt & "/" & list.Count
                Me.Refresh()
                cnt += 1

                Dim EZA = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.loadByMRN(MRN, True)


                Dim key = cATEZ_Greenpulse_KafkaDecs.GetUniqueKey_Pipe_FromVERAG_CustomsDec(EZA, MRN)

                ' Objekt
                Dim rec = cDakosyEZA_Greenpulse.BuildByMrn(EZA)
                Dim dr = cATEZ_Greenpulse_KafkaDecs.InsertOrUpdateToKafkaSync_Bool(rec, key, 30000)

                'Unlerlagen
                If EZA.za_SendungsId IsNot Nothing AndAlso EZA.za_SendungsId > 0 Then
                    Try

                        Dim rec_inv = cDakosyEZA_Greenpulse.BuildInvoices(EZA.za_SendungsId)
                        Dim dr_inv = cATEZ_Greenpulse_KafkaInvoices.InsertOrUpdateToKafkaSync_Bool(rec_inv, key, 30000)
                    Catch ex As Exception
                        MessageBox.Show(ex.Message)
                    End Try
                End If


                '     MessageBox.Show($"OK: {dr.Status} @ {dr.TopicPartitionOffset}")
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub


    Private Sub doCBAM_XML(dt As DataTable, EORI As String)
        Dim CBAM_XML As New VERAG_PROG_ALLGEMEIN.CBAM_QReport_17.QReportType

        CBAM_XML.Year = cboJahr.Text
        CBAM_XML.ReportingPeriod = cboQuartal._value
        EORI = txtEori.Text ' Sont VERAG problem..

        If cbxVERAG.Checked Then ' VERAG--> Indirect Representative
            CBAM_XML.Representative.IdentificationNumber = EORI
            Dim AD As VERAG_PROG_ALLGEMEIN.cAdressen = Nothing
            Select Case EORI
                Case "DE4824105"
                    AD = New VERAG_PROG_ALLGEMEIN.cAdressen(712255) 'VERAG GmbH (DE)
                Case "ATEOS1000000199"
                    AD = New VERAG_PROG_ALLGEMEIN.cAdressen(711104) 'VERAG AG (AT)
                Case "ATEOS1000059121"
                    AD = New VERAG_PROG_ALLGEMEIN.cAdressen(600006) 'VERAG Customs Service GmbH (AT)

            End Select
            If AD IsNot Nothing Then
                CBAM_XML.Representative.Name = AD.Name_1
                If If(AD.Name_2, "") <> "" Then CBAM_XML.Representative.Name &= " " & AD.Name_2
                If AD.LandKz <> "" Then CBAM_XML.Representative.RepresentativeAddress.Country = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2Land(AD.LandKz)
                CBAM_XML.Representative.RepresentativeAddress.Street = If(AD.Straße, "")
                CBAM_XML.Representative.RepresentativeAddress.Postcode = If(AD.PLZ, "")
            End If
        End If

        'Dim KD_IMP = VERAG_PROG_ALLGEMEIN.cKunde.LOAD_ByEORI(EORI)
        'If KD_IMP.hasEntry Then
        '    Dim A_IMP As New VERAG_PROG_ALLGEMEIN.cAdressen(KD_IMP.KundenNrZentrale)
        '    If A_IMP IsNot Nothing AndAlso A_IMP.hasEntry Then
        '        CBAM_XML.Importer.Name = A_IMP.Name_1
        '        If If(A_IMP.Name_2, "") <> "" Then CBAM_XML.Importer.Name &= " " & A_IMP.Name_2
        '        If A_IMP.LandKz <> "" Then CBAM_XML.Importer.ImporterAddress.Country = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2Land(A_IMP.LandKz)
        '        CBAM_XML.Importer.ImporterAddress.Street = If(A_IMP.Straße, "")
        '        CBAM_XML.Importer.ImporterAddress.Postcode = If(A_IMP.PLZ, "")
        '    End If
        'End If


        For Each g In dt.Rows
            Dim GOODS As New VERAG_PROG_ALLGEMEIN.CBAM_QReport_17.ImportedGoodType
            GOODS.CommodityCode.HsCode = g("Tarifnummer").ToString.Substring(0, 6)
            GOODS.CommodityCode.CnCode = g("Tarifnummer").ToString.Substring(6, 2)
            GOODS.OriginCountry.Country = g("VersendungsLand")
            GOODS.MeasureImported.NetMass = g("Eigenmasse")
            GOODS.MeasureImported.MeasurementUnit = "KG"

            ' ezaAd_NameFirma1, ezaAd_TeilnehmerEORI,
            If g("EmpfängerEORI") <> "" Then


                Dim KD_IMP = VERAG_PROG_ALLGEMEIN.cKunde.LOAD_ByEORI(g("EmpfängerEORI"))
                If KD_IMP.hasEntry Then
                    Dim A_IMP As New VERAG_PROG_ALLGEMEIN.cAdressen(KD_IMP.KundenNrZentrale)
                    If A_IMP IsNot Nothing AndAlso A_IMP.hasEntry Then
                        GOODS.Importer.Name = A_IMP.Name_1
                        If If(A_IMP.Name_2, "") <> "" Then GOODS.Importer.Name &= " " & A_IMP.Name_2
                        If A_IMP.LandKz <> "" Then GOODS.Importer.ImporterAddress.Country = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2Land(A_IMP.LandKz)
                        GOODS.Importer.ImporterAddress.Street = If(A_IMP.Straße, "")
                        GOODS.Importer.ImporterAddress.Postcode = If(A_IMP.PLZ, "")
                    End If
                End If
            Else
                GOODS.Importer.Name = g("Empfänger")

            End If


            Dim IQ As New VERAG_PROG_ALLGEMEIN.CBAM_QReport_17.ImportedQuantityType
            If g("Verfahren") <> "" Then IQ.Procedure.RequestedProc = g("Verfahren").ToString.Substring(0, 2)
            If g("VorangegangenesVerfahren") <> "" Then IQ.Procedure.PreviousProc = g("VorangegangenesVerfahren").ToString.Substring(0, 2)
            GOODS.ImportedQuantity.Add(IQ)
            CBAM_XML.ImportedGood.Add(GOODS)
        Next

        Dim optFileName = EORI & "_XML_" & txtVon._value & "-" & txtBis._value
        Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\SDL\tmp\" ' My.Computer.FileSystem.GetTempFileName
        If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
            My.Computer.FileSystem.CreateDirectory(sPath)
        End If

        Dim filename = sPath & optFileName & ".xml"
        While System.IO.File.Exists(filename)
            filename = sPath & optFileName & Now.ToString("ddMMyyyyHHmmss") & ".xml"
        End While


        CBAM_XML.SaveToFile(filename)
        btnCBAM_DS_DAKOSY_XML.Tag = filename
        btnCBAM_DS_DAKOSY_XML.Enabled = True

        'Me.Cursor = Cursors.WaitCursor
    End Sub


    Private Sub btnCBAM_DS_DAKOSY_Deteil_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DAKOSY_Detail.Click, btnCBAM_DS_DAKOSY_Summe.Click, btnCBAM_DS_DHF_VERAG_Detail.Click,
        btnCBAM_DS_DHF_VERAG_Summe.Click, btnCBAM_DS_DHF_UNISPED_Detail.Click, btnCBAM_DS_DHF_UNISPED_Summe.Click, btnCBAM_DS_TELOTEC_Detail.Click, btnCBAM_DS_TELOTEC_Summe.Click,
        btnCBAM_DS_DAKOSY_XML.Click, btnCBAM_DS_DAKOSY_Spedb.Click, btnCBAM_DS_DAKOSY_GP.Click, btnCBAM_DS_DHF_UNISPED_GP.Click, btnCBAM_DS_DHF_VERAG_GP.Click, btnCBAM_DS_TELOTEC_GP.Click

        If sender.tag <> "" Then
            Try : Process.Start(sender.tag) : Catch : End Try
        End If
    End Sub

    Private Sub btnCBAM_DS_DAKOSY_Copy_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DAKOSY_Copy.Click
        Dim f As New List(Of String)
        If btnCBAM_DS_DAKOSY_Detail.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_Detail.Tag)
        If btnCBAM_DS_DAKOSY_Summe.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_Summe.Tag)
        If btnCBAM_DS_DAKOSY_GP.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_GP.Tag)

        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub btnCBAM_DS_DHF_VERAG_Copy_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DHF_VERAG_Copy.Click
        Dim f As New List(Of String)
        If btnCBAM_DS_DHF_VERAG_Detail.Tag <> "" Then f.Add(btnCBAM_DS_DHF_VERAG_Detail.Tag)
        If btnCBAM_DS_DHF_VERAG_Summe.Tag <> "" Then f.Add(btnCBAM_DS_DHF_VERAG_Summe.Tag)
        If btnCBAM_DS_DHF_VERAG_GP.Tag <> "" Then f.Add(btnCBAM_DS_DHF_VERAG_GP.Tag)

        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub btnCBAM_DS_DHF_UNISPED_Copy_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DHF_UNISPED_Copy.Click
        Dim f As New List(Of String)
        If btnCBAM_DS_DHF_UNISPED_Detail.Tag <> "" Then f.Add(btnCBAM_DS_DHF_UNISPED_Detail.Tag)
        If btnCBAM_DS_DHF_UNISPED_Summe.Tag <> "" Then f.Add(btnCBAM_DS_DHF_UNISPED_Summe.Tag)
        If btnCBAM_DS_DHF_UNISPED_GP.Tag <> "" Then f.Add(btnCBAM_DS_DHF_UNISPED_GP.Tag)


        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub btnCBAM_DS_TELOTEC_Copy_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_TELOTEC_Copy.Click
        Dim f As New List(Of String)
        If btnCBAM_DS_TELOTEC_Detail.Tag <> "" Then f.Add(btnCBAM_DS_TELOTEC_Detail.Tag)
        If btnCBAM_DS_TELOTEC_Summe.Tag <> "" Then f.Add(btnCBAM_DS_TELOTEC_Summe.Tag)
        If btnCBAM_DS_TELOTEC_GP.Tag <> "" Then f.Add(btnCBAM_DS_TELOTEC_GP.Tag)

        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub btnCBAM_DS_DHF_VERAG_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DHF_VERAG.Click, btnCBAM_DS_DHF_UNISPED.Click

        btnCBAM_DS_DHF_UNISPED_GP.Enabled = False
        btnCBAM_DS_DHF_VERAG_GP.Enabled = False
        btnCBAM_DS_DHF_UNISPED_GP.Tag = ""
        btnCBAM_DS_DHF_VERAG_GP.Tag = ""

        Dim EZOLL_SQL = "EZOLL"
        If sender Is btnCBAM_DS_DHF_VERAG Then
            btnCBAM_DS_DHF_VERAG_Detail.Enabled = False
            btnCBAM_DS_DHF_VERAG_Copy.Enabled = False
            btnCBAM_DS_DHF_VERAG_Detail.Tag = ""
        End If
        If sender Is btnCBAM_DS_DHF_UNISPED Then
            btnCBAM_DS_DHF_UNISPED_Detail.Enabled = False
            btnCBAM_DS_DHF_UNISPED_Copy.Enabled = False
            btnCBAM_DS_DHF_UNISPED_Detail.Tag = ""
            EZOLL_SQL = "EZOLL_UNISPED"
        End If

        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor



            Dim SQL_DHF = ""
            Dim SQL_GP = ""
            getDY_Detail_SQL_DHF(EORI, SQL_DHF, SQL_GP) '--> Aufbau SQL String

            Dim dt = SQL.loadDgvBySql(SQL_DHF, EZOLL_SQL, 600)

            Dim dtGP = SQL.loadDgvBySql(SQL_GP, EZOLL_SQL, 600)


            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Detailbericht_" & txtVon._value & "-" & txtBis._value)
                If sender Is btnCBAM_DS_DHF_VERAG Then
                    btnCBAM_DS_DHF_VERAG_Detail.Tag = path
                    btnCBAM_DS_DHF_VERAG_Detail.Enabled = True
                    btnCBAM_DS_DHF_VERAG_Copy.Enabled = True
                End If
                If sender Is btnCBAM_DS_DHF_UNISPED Then
                    btnCBAM_DS_DHF_UNISPED_Detail.Tag = path
                    btnCBAM_DS_DHF_UNISPED_Detail.Enabled = True
                    btnCBAM_DS_DHF_UNISPED_Copy.Enabled = True
                End If

            End If


            If dtGP IsNot Nothing AndAlso dt.Rows.Count > 0 Then

                'If ReDaten.Rows.Count > 0 Then
                '    dtGP.Columns("invoice date").ReadOnly = False
                '    dtGP.Columns("invoice numbers").ReadOnly = False
                '    dtGP.Columns("invoice date").MaxLength = -1
                '    dtGP.Columns("invoice numbers").MaxLength = -1
                'End If

                'For Each r As DataRow In dtGP.Rows
                '    Dim MDN_NR As String = r("declaration no")

                '    ' Look for matching row in dt2
                '    Dim found() As DataRow = ReDaten.Select("Registriernummer_MRN = '" & MDN_NR & "'")



                '    If found.Length > 0 Then

                '        Dim rechnugnsdatum As String = found(0)("Positionsunterlagendatum")
                '        If rechnugnsdatum <> "" Then rechnugnsdatum.Replace("00:00:00", "")

                '        r("invoice date") = rechnugnsdatum
                '        r("invoice numbers") = found(0)("Positionsunterlagennummer")
                '    Else
                '        r("invoice date") = "-"
                '        r("invoice numbers") = "-"
                '    End If

                'Next
                If sender Is btnCBAM_DS_DHF_VERAG Then
                    btnCBAM_DS_DHF_VERAG_GP.Tag = ""
                    btnCBAM_DS_DHF_VERAG_GP.Tag = createExcelForGreenPulse(dtGP, EORI, "")
                    btnCBAM_DS_DHF_VERAG_GP.Enabled = True
                End If

                If sender Is btnCBAM_DS_DHF_UNISPED Then
                    btnCBAM_DS_DHF_UNISPED_GP.Tag = ""
                    btnCBAM_DS_DHF_UNISPED_GP.Tag = createExcelForGreenPulse(dtGP, EORI, "")
                    btnCBAM_DS_DHF_UNISPED_GP.Enabled = True
                End If


            End If



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


        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


        If sender Is btnCBAM_DS_DHF_VERAG Then
            btnCBAM_DS_DHF_VERAG_Summe.Enabled = False
            btnCBAM_DS_DHF_VERAG_Summe.Tag = ""
        End If

        If sender Is btnCBAM_DS_DHF_UNISPED Then
            btnCBAM_DS_DHF_UNISPED_Summe.Enabled = False
            btnCBAM_DS_DHF_UNISPED_Summe.Tag = ""
        End If

        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor

            Dim SQLSTR = "
                 select   left(zsAnmGdsitem.ComCd,8) Tarifnummer, sum(Net)Eigenmasse, sum(ItVal)Rechnungspreis,Orig
  		                       from  				 zsAnmRefs 
				                    inner join zsAnmDHFRefs on zsAnmRefs.LizenzNr=zsAnmDHFRefs.LizenzNr and zsAnmRefs.AnmID=zsAnmDHFRefs.AnmID and zsAnmRefs.VorgangID=zsAnmDHFRefs.VorgangID and zsAnmRefs.OperatorID=zsAnmDHFRefs.OperatorID
			                          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
					 	                    where DecDT between '" & txtVon._value & "' and '" & txtBis._value & "'
					                       and " & VERAG_PROG_ALLGEMEIN.cGreendeal_CBAM_Trn.BuildCBAMPatternWhereClause("ComCd") & "  
                     /* (
                      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
                       and zsAnmDHFRefs.ErledigungsTypID like 'F%'  
            "

            If cbxVERAG.Checked Then
                SQLSTR &= " 
                                and DecRep IN(3)
                             "
            Else
                SQLSTR &= " 
                             and (SELECT TIN FROM zsAnmConeeTra WHERE (zsAnmConeeTra.LizenzNr =  zsAnmHea.LizenzNr ) And (zsAnmConeeTra.OperatorID =zsAnmHea.OperatorID ) And (zsAnmConeeTra.VorgangID = zsAnmHea.VorgangID ) And (zsAnmConeeTra.AnmID = zsAnmHea.AnmID )) LIKE '" & EORI & "' 
                 "
            End If
            SQLSTR &= " GROUP BY Orig,left(zsAnmGdsitem.ComCd,8) "


            Dim dt = SQL.loadDgvBySql(SQLSTR, EZOLL_SQL, 600)
            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Summenbericht_" & txtVon._value & "-" & txtBis._value)
                If sender Is btnCBAM_DS_DHF_VERAG Then
                    btnCBAM_DS_DHF_VERAG_Summe.Tag = path
                    btnCBAM_DS_DHF_VERAG_Summe.Enabled = True
                    btnCBAM_DS_DHF_VERAG_Copy.Enabled = True
                End If
                If sender Is btnCBAM_DS_DHF_UNISPED Then
                    btnCBAM_DS_DHF_UNISPED_Summe.Tag = path
                    btnCBAM_DS_DHF_UNISPED_Summe.Enabled = True
                    btnCBAM_DS_DHF_UNISPED_Copy.Enabled = True
                End If
                Me.Cursor = Cursors.Default

            End If



        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 CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles cbxVERAG.CheckedChanged, cbxUNISPED.CheckedChanged, cbxIMEX.CheckedChanged
        txtEori.Enabled = Not (cbxVERAG.Checked Or cbxUNISPED.Checked Or cbxIMEX.Checked)
    End Sub

    Private Sub btnCBAM_DS_DAKOSY_XML_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_DAKOSY_XML.Click

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim f As New List(Of String)
        If btnCBAM_DS_DAKOSY_XML.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_XML.Tag)

        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs)
        Dim f As New List(Of String)
        If btnCBAM_DS_DAKOSY_Detail.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_Detail.Tag)
        If btnCBAM_DS_DAKOSY_Summe.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_Summe.Tag)
        If btnCBAM_DS_DAKOSY_XML.Tag <> "" Then f.Add(btnCBAM_DS_DAKOSY_XML.Tag)

        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub btnCBAM_DS_TELOTEC_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_TELOTEC.Click
        btnCBAM_DS_TELOTEC_Detail.Enabled = False
        btnCBAM_DS_TELOTEC_Copy.Enabled = False
        btnCBAM_DS_TELOTEC_GP.Enabled = False


        Try
            Dim EORI = txtEori.Text
            If cbxVERAG.Checked Then EORI = "VERAG"
            If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            Me.Cursor = Cursors.WaitCursor


            Dim SQL_TT = ""
            Dim SQL_GP = ""
            getDY_Detail_SQL_TT(EORI, SQL_TT, SQL_GP) '--> Aufbau SQL String

            Dim dt = SQL.loadDgvBySql(SQL_TT, "FMZOLL", 600)

            Dim dtGP = SQL.loadDgvBySql(SQL_GP, "FMZOLL", 600)

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Detailbericht_" & txtVon._value & "-" & txtBis._value,, False)
                btnCBAM_DS_TELOTEC_Detail.Tag = path
                btnCBAM_DS_TELOTEC_Detail.Enabled = True
                btnCBAM_DS_TELOTEC_Copy.Enabled = True
                Me.Cursor = Cursors.Default

            End If


            If dtGP IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Me.Cursor = Cursors.WaitCursor
                btnCBAM_DS_TELOTEC_GP.Tag = ""
                btnCBAM_DS_TELOTEC_GP.Tag = createExcelForGreenPulse(dtGP, EORI, "")
                btnCBAM_DS_TELOTEC_GP.Enabled = True
                Me.Cursor = Cursors.Default
            End If



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


        '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


        'btnCBAM_DS_DAKOSY_Summe.Enabled = False
        'btnCBAM_DS_DAKOSY_Summe.Tag = ""

        'Try
        '    Dim EORI = txtEori.Text
        '    If cbxVERAG.Checked Then EORI = "VERAG"
        '    If EORI = "" Then MsgBox("EORI eingeben!") : Exit Sub
        '    If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
        '    If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
        '    Me.Cursor = Cursors.WaitCursor

        '    Dim SQLSTR = "
        '        SELECT  
        '             left(ezaWP_WarennummerEZT,8) Tarifnummer,sum(ezaWP_Eigenmasse)Eigenmasse,sum(ezaWP_Rohmasse)Rohmasse,sum(ezaWP_Artikelpreis)Rechnungspreis,eza_VersendungsLandCode VersendungsLand ,isnull(ezaWP_AnmeldeVErfahren,'') Verfahren,isnull([ezaWP_VerfahrensCodeVorangegangenesVerfahren],'') VorangegangenesVerfahren

        '            FROM [VERAG].[dbo].[tblDakosy_EZA]
        '          inner join tblDakosy_EZA_Warenposition on ezaWP_EzaId=eza_Id
        '           where  
        '            eza_anmeldedatum between '" & txtVon._value & "' and '" & txtBis._value & "'
        '          and 
        '          (
        '          left(ezaWP_WarennummerEZT,4) IN (2523,2716,2808,2814,3102,3105,7201,7203,7318,7326,7601,7616)
        '          OR   left(ezaWP_WarennummerEZT,4)  between 7301 and 7311
        '          OR   left(ezaWP_WarennummerEZT,4)  between 7205 and 7229
        '          OR   left(ezaWP_WarennummerEZT,4)  between 7603 and 7614
        '          OR   ezaWP_WarennummerEZT like '25070080%'
        '          OR   ezaWP_WarennummerEZT like '283421%'
        '          OR   ezaWP_WarennummerEZT like '260112%'
        '          OR   ezaWP_WarennummerEZT like '720211%'
        '          OR   ezaWP_WarennummerEZT like '720219%'
        '          OR   ezaWP_WarennummerEZT like '720241%'
        '          OR   ezaWP_WarennummerEZT like '720249%'
        '          OR   ezaWP_WarennummerEZT like '720260%'
        '          OR   ezaWP_WarennummerEZT like '280410%'

        '          )
        '            and ezaWP_WarennummerEZT not like '310560%'
        '                and (eza_status between 50  and 60 or [eza_ANR] LIKE 'ATC%')

        '    "

        '    If cbxVERAG.Checked Then
        '        SQLSTR &= " 
        '                    and eza_VertretungsVerhaeltnisCode=2
        '                  "
        '    Else
        '        SQLSTR &= " 
        '                    and (select   isnull([ezaAd_NameFirma1],[ezaAd_TeilnehmerEORI]) FROM tblDakosy_EZA_Adressen WHERE ezaAd_EZAId=eza_Id and [ezaAd_AdressTyp]='CN')='" & EORI & "' 
        '                  "
        '    End If

        '    SQLSTR &= "   group by eza_VersendungsLandCode,left(ezaWP_WarennummerEZT,8),ezaWP_AnmeldeVErfahren,ezaWP_VerfahrensCodeVorangegangenesVerfahren"


        '    Dim dt = SQL.loadDgvBySql(SQLSTR, "FMZOLL", 600)
        '    If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
        '        Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,,,,, False, EORI & "_Summenbericht_" & txtVon._value & "-" & txtBis._value)
        '        btnCBAM_DS_DAKOSY_Summe.Tag = path
        '        btnCBAM_DS_DAKOSY_Summe.Enabled = True
        '        btnCBAM_DS_DAKOSY_Copy.Enabled = True

        '        Me.Cursor = Cursors.Default

        '    End If



        ''----- XML ----------------------------------------------------------------------------------------------------------------------------------------

        'btnCBAM_DS_DAKOSY_XML.Enabled = False
        'btnCBAM_DS_DAKOSY_XML.Tag = ""

        'If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
        '    '---------------------------------------------------------------------------------------------------------------------------------------------
        '    doCBAM_XML(dt, EORI)
        '    '---------------------------------------------------------------------------------------------------------------------------------------------

        'End If


        ''---------------------------------------------------------------------------------------------------------------------------------------------

        '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


    Public Function createExcelForGreenPulse(dt As DataTable, EORI As String, Importer_City As String)


        Dim EORI_Ort As String = ""
        If AD IsNot Nothing Then
            EORI_Ort = AD.Ort
        End If

        Dim Path_GP = ""

        Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\SR\"
        If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
            My.Computer.FileSystem.CreateDirectory(sPath)
        End If

        Dim exclApp As Object 'as Application
        Dim Datei As Object 'Workbook
        Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
        exclApp = CreateObject("Excel.Application")



        With exclApp
            .Visible = False

            Try
                Path_GP = sPath & EORI & "_Detailbericht_GP_" & txtVon._value & "-" & txtBis._value & " .xlsx"
                While System.IO.File.Exists(Path_GP)
                    Path_GP = sPath & EORI & "_Detailbericht_GP_" & txtVon._value & "-" & txtBis._value & Now.ToString("ddMMyyyyHHmmss") & ".xlsx"
                End While
                My.Computer.FileSystem.WriteAllBytes(Path_GP, My.Resources.CBAM_Auswertung_GP, False)

                System.Threading.Thread.Sleep(200)
                GC.Collect()
                GC.WaitForPendingFinalizers()

            Catch ex As System.Exception
                '  MsgBox(ex.Message)
                MsgBox("ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace)
                Me.Cursor = Cursors.Default

                Return ""
            End Try

            Datei = .Workbooks.Open(Path_GP)
            Blatt = Datei.Worksheets(1)

            Dim cnt = 3

            Dim rowcounter As Integer = 0

            For Each row As DataRow In dt.Rows
                Blatt.Range("A" & cnt).Value = row("declaration no")
                Blatt.Range("B" & cnt).Value = row("declaration date")
                Blatt.Range("C" & cnt).Value = row("importer identification number")
                Blatt.Range("D" & cnt).Value = row("exporter identification number")
                Blatt.Range("E" & cnt).Value = row("commodity code")
                Blatt.Range("F" & cnt).Value = row("origin country code")
                Blatt.Range("G" & cnt).Value = row("requested procedure")
                Blatt.Range("H" & cnt).Value = row("previous procedure")
                Blatt.Range("I" & cnt).Value = row("net mass")
                Blatt.Range("J" & cnt).Value = row("type of measurement unit")
                Blatt.Range("K" & cnt).Value = row("invoice numbers")
                Blatt.Range("L" & cnt).Value = row("invoice date")
                Blatt.Range("M" & cnt).Value = row("member state auth")
                Blatt.Range("N" & cnt).Value = row("discharge bill waiver")
                Blatt.Range("O" & cnt).Value = row("authorisation")
                Blatt.Range("P" & cnt).Value = row("start time")
                Blatt.Range("Q" & cnt).Value = row("end time")
                Blatt.Range("R" & cnt).Value = row("deadline")
                Blatt.Range("S" & cnt).Value = row("reporting declarant EORI number")
                Blatt.Range("T" & cnt).Value = row("type of representation")
                Blatt.Range("U" & cnt).Value = row("importer title")
                Blatt.Range("V" & cnt).Value = row("importer email")
                Blatt.Range("W" & cnt).Value = row("importer phone")
                Blatt.Range("X" & cnt).Value = row("importer country code or member state")
                Blatt.Range("Y" & cnt).Value = row("importer subdivision")
                Blatt.Range("Z" & cnt).Value = IIf(Importer_City <> "", Importer_City, row("importer city"))

                Blatt.Range("AA" & cnt).Value = row("importer street")
                Blatt.Range("AB" & cnt).Value = row("importer street additional")
                Blatt.Range("AC" & cnt).Value = row("importer address number")
                Blatt.Range("AD" & cnt).Value = row("importer post code")
                Blatt.Range("AE" & cnt).Value = row("importer po box")
                Blatt.Range("AF" & cnt).Value = row("importer coordinate longitude (x)")
                Blatt.Range("AG" & cnt).Value = row("importer coordinate latitude (y)")

                Blatt.Range("AH" & cnt).Value = row("exporter title")
                Blatt.Range("AI" & cnt).Value = row("exporter country code or member state")
                Blatt.Range("AJ" & cnt).Value = row("exporter street")
                Blatt.Range("AK" & cnt).Value = row("exporter street additional")

                cnt += 1
                rowcounter += 1
            Next

            Datei.Save()
            Datei.Close(SaveChanges:=True)
            Datei = Nothing

        End With

        exclApp.Quit()
        exclApp = Nothing


        Return Path_GP

    End Function

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        txtCalcErg.Text = cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM(txtCalcKN8._value, txtCalcGewicht._value, txtCalcLand._value, txtCalcEmission._value, txtCalcJahr._value, txtBenchmark._value)
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        txtCalc_Defaut_Country.Enabled = True
        'MsgBox(CountCBAMTariffNumbersBySystemAndEORI("DAKOSY", txtEori.Text, txtVon._value, txtBis._value))
        'MsgBox(CountCBAMTariffNumbersBySystemAndEORI("DHF", txtEori.Text, txtVon._value, txtBis._value))
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim EORI = {txtEori.Text}
        If cbxIndirekt.Checked Then EORI = {cboIndirekt._value}
        If EORI(0) = "" Then MsgBox("EORI eingeben!") : Exit Sub
        If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
        If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub

        lblErg_VERAG.Text = "-"
        lblErg_VERAG2.Text = "-"

        Dim LIST = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM(EORI, "", txtVon._value, txtBis._value,, False)

        cbo_VERAG_ImpLand.Items.Clear()

        Dim sumEigenmasse As Decimal = LIST.SelectMany(Function(za) za.Items).Sum(Function(it) If(it.zaItem_NetMass, 0D))

        Dim countries = LIST.Where(Function(za) Not String.IsNullOrWhiteSpace(za.za_CountryImport)).
                Select(Function(za) za.za_CountryImport.Trim()).
                Distinct().
                OrderBy(Function(c) c).
                ToList()
        cbo_VERAG_ImpLand.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        For Each c In countries
            cbo_VERAG_ImpLand.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(c, c))
        Next
        If cbo_VERAG_ImpLand.Items.Count = 2 Then
            cbo_VERAG_ImpLand.SelectedIndex = 1
        End If

        lblErg_VERAG.Text = LIST.Count
        lblErg_VERAG2.Text = String.Join(", ", countries)

        'MsgBox("Anzahl der Anmeldungen: " & LIST.Count)
    End Sub

    Private Sub Button16_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_VERAG.Click
        Dim EORI = {txtEori.Text}
        If cbxIndirekt.Checked Then EORI = {cboIndirekt._value}
        If EORI(0) = "" Then MsgBox("EORI eingeben!") : Exit Sub
        If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
        If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
        If cbo_VERAG_ImpLand._value = "" Then MsgBox("Importland auswählen!") : Exit Sub : 
        Me.Cursor = Cursors.WaitCursor
        Try



            Dim LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations) = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM(EORI, cbo_VERAG_ImpLand._value, txtVon._value, txtBis._value,, True)
            TextBox1.Text = LIST.Count


            doVERAG_SUM(LIST, EORI(0))
            doVERAG_DETAIL_OLD(LIST, EORI(0))
            'doVERAG_DETAIL(LIST, EORI(0))
            If cbxVERAG_GPXLS.Checked Then doVERAG_GREENPULSE_XLS(LIST, EORI(0))


        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


    Function LeftStr(s As String, l As Integer) As String
        If s Is Nothing Then Return ""
        If s Is DBNull.Value Then Return ""
        LeftStr = If(s.Length >= l, s.Substring(0, l), s)
    End Function


    Sub doVERAG_SUM(LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations), EORI As String)

        btnCBAM_DS_VERAG_Summe.Enabled = False
        btnCBAM_DS_VERAG_Detail.Tag = ""

        Try
            Dim summary =
                From za In LIST
                From it In za.Items
                Group By
                    Tarifnummer = LeftStr(it.zaItem_HSCode, 8),
                    Ursprungsland = it.zaItem_OriginCountry
                Into grp = Group
                Let verfahren =
                    grp.Select(Function(x) LeftStr(x.za.za_MainProcedure, 2)).
                        FirstOrDefault(Function(v) Not String.IsNullOrWhiteSpace(v))
                Let verfahrenFallback =
                    grp.Select(Function(x) LeftStr(x.it.zaItem_MainProcedure, 2)).
                        FirstOrDefault(Function(v) Not String.IsNullOrWhiteSpace(v))
                Let vorverfahren =
                    grp.Select(Function(x) x.it.zaItem_PrevProcedure).
                        FirstOrDefault(Function(v) Not String.IsNullOrWhiteSpace(v))
                Let rohmasseItems =
                    grp.Sum(Function(x) If(x.it.zaItem_GrossMass, 0D))
                Let rohmasseZA =
                    grp.Max(Function(x) If(x.za.za_TotGrossMass, 0D))
                Select New With {
                    .Tarifnummer = Tarifnummer,
                    .Eigenmasse = grp.Sum(Function(x) If(x.it.zaItem_NetMass, 0D)),
                    .Rohmasse = Math.max(rohmasseItems, rohmasseZA),
                    .Rechnungspreis = grp.Sum(Function(x) If(x.it.zaItem_InvoiceValueEUR, x.it.zaItem_StatisticalValueEUR)),
                    .Ursprungsland = Ursprungsland,
                    .Verfahren = If(verfahrenFallback, verfahren),
                    .VorangegangenesVerfahren = vorverfahren
                }

            Dim dt As New DataTable

            dt.Columns.Add("Tarifnummer", GetType(String))
            dt.Columns.Add("Eigenmasse", GetType(Decimal))
            '  dt.Columns.Add("Rohmasse", GetType(Decimal))
            dt.Columns.Add("Rechnungspreis", GetType(Decimal))
            dt.Columns.Add("Ursprungsland", GetType(String))
            dt.Columns.Add("Verfahren", GetType(String))
            dt.Columns.Add("VorangegangenesVerfahren", GetType(String))

            If cbxKosten.Checked Then
                dt.Columns.Add("Def_benchmark", GetType(Decimal))
                dt.Columns.Add("Def_Emission", GetType(Decimal))
                dt.Columns.Add("Faktor", GetType(Decimal))
                dt.Columns.Add("EstimatedCost", GetType(Decimal))
            End If


            For Each r In summary

                If cbxKosten.Checked Then
                    ' =========================================================
                    ' Berechnung pro Zeile
                    ' =========================================================

                    Dim benchmark As Object = Nothing
                    Dim emission As Object = Nothing
                    Dim faktor As Object = Nothing
                    Dim weight = r.Eigenmasse
                    Dim year = If(txtBis._value <> "", CDate(txtBis._value).Year, Now.Year)

                    Dim cost As String = "0"
                    If IsNumeric(txtVERA_ZertPreis._value) Then
                        cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(
                                    cn_code:=Convert.ToString(r.Tarifnummer),
                                    weight / 1000,
                                    country_code:=Convert.ToString(r.Ursprungsland),
                                    CDbl(txtVERA_ZertPreis._value),
                                    year,
                                    cost,
                                    emission,
                                    benchmark,
                                    faktor
                                )
                    Else
                        cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM(
                                     cn_code:=Convert.ToString(r.Tarifnummer),
                                    weight / 1000,
                                    country_code:=Convert.ToString(r.Ursprungsland),
                                     Nothing,
                                    year,
                                    Nothing,
                                    cost,
                                    emission,
                                    benchmark,
                                    faktor
                        )
                    End If

                    Dim Def_benchmark = If(benchmark Is Nothing, "", benchmark)
                    Dim Def_Emission = If(emission Is Nothing, "", emission)
                    Dim EstimatedCost = If(cost < 0, "", Convert.ToDecimal(cost))

                    dt.Rows.Add(
                                r.Tarifnummer,
                                r.Eigenmasse,
                                r.Rechnungspreis,
                                r.Ursprungsland,
                                r.Verfahren,
                                r.VorangegangenesVerfahren,
                                Def_benchmark,
                                Def_Emission,
                                faktor,
                                EstimatedCost
                            )

                Else
                    dt.Rows.Add(
                        r.Tarifnummer,
                        r.Eigenmasse,
                        r.Rechnungspreis,
                        r.Ursprungsland,
                        r.Verfahren,
                        r.VorangegangenesVerfahren
                    )
                End If


                ' MsgBox(r.Tarifnummer)
            Next

            ' MsgBox(dt.Rows.Count)

            If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
                Dim range = If(cbxKosten.Checked, {"C:C", "J:J"}, {"C:C"})

                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt,, , , , False, EORI & "_Summenbericht_" & txtVon._value & "-" & txtBis._value,, True)
                btnCBAM_DS_VERAG_Summe.Tag = path
                btnCBAM_DS_VERAG_Summe.Enabled = True
                btnCBAM_DS_VERAG_Copy.Enabled = True
            End If

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

    Public Sub doVERAG_DETAIL(LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations), EORI As String)

        btnCBAM_DS_VERAG_Detail.Enabled = False
        btnCBAM_DS_VERAG_Detail.Tag = ""

        Try

            ' =========================================================
            ' Daten holen
            ' =========================================================
            Dim details =
            From za In LIST
            From it In za.Items
            Let importer = za.Parties.
                FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.IMPORTER_ROLES.Contains(p.zaParty_Role))
            Let exporter = za.Parties.
                FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.EXPORTER_ROLES.Contains(p.zaParty_Role))
            Let declarant = za.Parties.
                FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.DECLARANT_ROLES.Contains(p.zaParty_Role))
            Let cbamDeclarantTmp = za.Parties.
                FirstOrDefault(Function(p) p.zaParty_Role = "CBAM")
            Let cbamDeclarant = If(cbamDeclarantTmp, declarant)
            Let invoice =
                it.Documents.FirstOrDefault(Function(d) d.zaDoc_Code = "N380" OrElse d.zaDoc_Code = "N325")
            Let anmeldedatum = If(za.za_ReleaseDate, za.za_DeclarationDate)
            Order By anmeldedatum
            Select New With {
                .MRN = If(za.za_MRN, ""),
                .SendungsId = za.za_SendungsId,
                .PositionsNummer = it.zaItem_PosNo,
                .Anmeldedatum = anmeldedatum,
                .BezugsNr = If(za.za_LRN, ""),
                .VertretungsVerhaeltnis = If(za.za_RepresentationCode, ""),
                .Tarifnummer = If(LeftStr(it.zaItem_HSCode, 8), ""),
                .Eigenmasse = it.zaItem_NetMass,
                .Rohmasse = it.zaItem_GrossMass,
                .Ursprungsland = If(it.zaItem_OriginCountry, ""),
                .VersendungsLand = If(za.za_CountryDispatch, ""),
                .BestimmungsLand = If(za.za_CountryDestination, ""),
                .Rechnungspreis = If(it.zaItem_InvoiceValueEUR, it.zaItem_StatisticalValueEUR),
                .Rechnungswaehrung = If(it.zaItem_InvoiceCurrency, ""),
                .EmpfaengerEORI = If(importer IsNot Nothing, If(importer.zaParty_EORI, ""), ""),
                .Empfaenger = If(importer IsNot Nothing, If(importer.zaParty_Name, ""), ""),
                .AbsenderEORI = If(exporter IsNot Nothing, If(exporter.zaParty_EORI, ""), ""),
                .Absender = If(exporter IsNot Nothing, If(exporter.zaParty_Name, ""), ""),
                .DeclarantEORI = If(declarant IsNot Nothing, If(declarant.zaParty_EORI, ""), ""),
                .DeclarantName = If(declarant IsNot Nothing, If(declarant.zaParty_Name, ""), ""),
                .CBAMDeclarantEORI = If(cbamDeclarant IsNot Nothing, If(cbamDeclarant.zaParty_EORI, ""), ""),
                .CBAMDeclarantName = If(cbamDeclarant IsNot Nothing, If(cbamDeclarant.zaParty_Name, ""), ""),
                .Rechnungsnummer = If(invoice IsNot Nothing, If(invoice.zaDoc_Reference, ""), ""),
                .Rechnungsdatum = If(invoice IsNot Nothing, ParseDateSafe(invoice.zaDoc_Date), Nothing),
                .RequestedProcedure = If(za.za_MainProcedure, ""),
                .PreviousProcedure = If(it.zaItem_PrevProcedure, ""),
                .MeasurementUnit = If(it.zaItem_SuppUnitCode, "")
            }

            ' =========================================================
            ' DataTable exakt nach Excel-Template
            ' =========================================================
            Dim dt As New DataTable

                dt.Columns.Add("MRN")
                dt.Columns.Add("position_no")
                dt.Columns.Add("declaration_date")
                dt.Columns.Add("reference_no")
                dt.Columns.Add("customer_reference")
                dt.Columns.Add("representation_type")
                dt.Columns.Add("tariff_code")
                dt.Columns.Add("net_mass_kg")
                dt.Columns.Add("gross_mass_kg")
                dt.Columns.Add("origin_country")
                dt.Columns.Add("dispatch_country")
                dt.Columns.Add("destination_country")
                dt.Columns.Add("invoice_number")
                dt.Columns.Add("invoice_date")
                dt.Columns.Add("invoice_amount")
                dt.Columns.Add("invoice_currency")
                dt.Columns.Add("sender_eori")
                dt.Columns.Add("sender_name")
                dt.Columns.Add("sender_address")
                dt.Columns.Add("sender_country")
                dt.Columns.Add("recipient_eori")
                dt.Columns.Add("recipient_name")
                dt.Columns.Add("recipient_address")
                dt.Columns.Add("recipient_country")
                dt.Columns.Add("importer_eori")
                dt.Columns.Add("importer_name")
                dt.Columns.Add("importer_address")
                dt.Columns.Add("importer_country")
                dt.Columns.Add("importer_email")
                dt.Columns.Add("importer_phone")
                dt.Columns.Add("declarant_eori")
                dt.Columns.Add("declarant_name")
                dt.Columns.Add("declarant_address")
                dt.Columns.Add("declarant_country")
                dt.Columns.Add("requested_procedure")
                dt.Columns.Add("previous_procedure")
                dt.Columns.Add("measurement_unit")
                dt.Columns.Add("member_state_authorisation")
                dt.Columns.Add("discharge_bill_waiver")
                dt.Columns.Add("authorisation")
                dt.Columns.Add("inward_processing_start")
                dt.Columns.Add("inward_processing_end")
                dt.Columns.Add("inward_processing_deadline")
                dt.Columns.Add("Benchmark (Default)")
                dt.Columns.Add("Emission (Default)")
                dt.Columns.Add("Factor")
                dt.Columns.Add("Estimated Cost")

                ' =========================================================
                ' Befüllen
                ' =========================================================
                For Each r In details

                    Dim KdAtrNr As String = ""

                    If cbxKdAtrNr.Checked AndAlso r.SendungsId IsNot Nothing Then
                        Dim Snd = New VERAG_PROG_ALLGEMEIN.cSendungen(r.SendungsId)
                        If Snd IsNot Nothing Then
                            KdAtrNr = Snd.getKdAtrNr("AUFTRAGGEBER")
                            If KdAtrNr = "" Then
                                KdAtrNr = Snd.getKdAtrNr("EMPFAENGER")
                            End If
                        End If

                        If EORI = "DE4991397" AndAlso KdAtrNr.Contains("/") Then
                            KdAtrNr = KdAtrNr.Split("/"c)(0)
                        End If
                    End If

                Dim benchmark As Object = Nothing
                Dim emission As Object = Nothing
                Dim faktor As Object = Nothing
                Dim weight = r.Eigenmasse
                Dim year = If(txtBis._value <> "", CDate(txtBis._value).Year, Now.Year)
                Dim cost As String = "0"

                If cbxKosten.Checked Then
                        Dim benchmarkObj As Object = Nothing
                    Dim emissionObj As Object = Nothing
                    Dim faktorObj As Object = Nothing
                    Dim costObj As String = "0"

                    '  Dim weight = 0D
                    If IsNumeric(r.Eigenmasse) Then weight = CDbl(r.Eigenmasse)

                    'Dim year = If(txtBis._value <> "", CDate(txtBis._value).Year, Now.Year)

                    If IsNumeric(txtVERA_ZertPreis._value) Then
                        cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(
                            cn_code:=Convert.ToString(r.Tarifnummer),
                            weight:=weight / 1000,
                            country_code:=Convert.ToString(r.Ursprungsland),
                            certificate_price:=CDbl(txtVERA_ZertPreis._value),
                            year:=year,
                            costObj,
                            emissionObj,
                            benchmarkObj,
                            faktorObj
                        )
                    Else
                        cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM(
                            cn_code:=Convert.ToString(r.Tarifnummer),
                            weight:=weight / 1000,
                            country_code:=Convert.ToString(r.Ursprungsland),
                            Nothing,
                            year:=year,
                            Nothing,
                            costObj,
                            emissionObj,
                            benchmarkObj,
                            faktorObj
                        )
                    End If

                    benchmark = If(benchmarkObj Is Nothing, "", Convert.ToString(benchmarkObj))
                        emission = If(emissionObj Is Nothing, "", Convert.ToString(emissionObj))
                        faktor = If(faktorObj Is Nothing, "", Convert.ToString(faktorObj))

                        If IsNumeric(costObj) Then
                            If CDbl(costObj) >= 0 Then
                                cost = Convert.ToString(costObj)
                            Else
                                cost = ""
                            End If
                        Else
                            cost = ""
                        End If
                    End If

                    Dim row = dt.NewRow()

                row("MRN") = If(r.MRN, "")
                row("position_no") = r.PositionsNummer
                row("declaration_date") = If(r.Anmeldedatum Is Nothing, "", CDate(r.Anmeldedatum).ToString("yyyy-MM-dd"))
                row("reference_no") = If(r.BezugsNr, "")
                row("customer_reference") = If(KdAtrNr, "")
                row("representation_type") = If(r.VertretungsVerhaeltnis, "")
                row("tariff_code") = If(r.Tarifnummer, "")
                row("net_mass_kg") = If(r.Eigenmasse Is Nothing, "", Convert.ToString(r.Eigenmasse))
                row("gross_mass_kg") = If(r.Rohmasse Is Nothing, "", Convert.ToString(r.Rohmasse))
                row("origin_country") = If(r.Ursprungsland, "")
                row("dispatch_country") = If(r.VersendungsLand, "")
                row("destination_country") = If(r.BestimmungsLand, "")

                row("invoice_number") = If(r.Rechnungsnummer, "")
                row("invoice_date") = If(r.Rechnungsdatum Is Nothing, "", CDate(r.Rechnungsdatum).ToString("yyyy-MM-dd"))
                row("invoice_amount") = If(r.Rechnungspreis Is Nothing, "", Convert.ToString(r.Rechnungspreis))
                row("invoice_currency") = If(r.Rechnungswaehrung, "")

                row("sender_eori") = If(r.AbsenderEORI, "")
                row("sender_name") = If(r.Absender, "")
                row("sender_address") = ""
                row("sender_country") = ""

                row("recipient_eori") = If(r.EmpfaengerEORI, "")
                row("recipient_name") = If(r.Empfaenger, "")
                row("recipient_address") = ""
                row("recipient_country") = ""

                row("importer_eori") = If(r.EmpfaengerEORI, "")
                row("importer_name") = If(r.Empfaenger, "")
                row("importer_address") = ""
                row("importer_country") = ""
                row("importer_email") = ""
                row("importer_phone") = ""

                row("declarant_eori") = If(r.DeclarantEORI, "")
                row("declarant_name") = If(r.DeclarantName, "")
                row("declarant_address") = ""
                row("declarant_country") = ""

                row("requested_procedure") = If(r.RequestedProcedure, "")
                row("previous_procedure") = If(r.PreviousProcedure, "")
                row("measurement_unit") = If(r.MeasurementUnit, "")
                row("member_state_authorisation") = ""
                row("discharge_bill_waiver") = ""
                row("authorisation") = ""
                row("inward_processing_start") = ""
                row("inward_processing_end") = ""
                row("inward_processing_deadline") = ""

                row("Benchmark (Default)") = benchmark
                row("Emission (Default)") = emission
                row("Factor") = faktor
                row("Estimated Cost") = cost

                dt.Rows.Add(row)

            Next

            ' =========================================================
            ' Datei vorbereiten
            ' =========================================================
            Dim Path_DETAIL As String = ""
                Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\CBAM_REPORT_DETAIL\"

                If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
                    My.Computer.FileSystem.CreateDirectory(sPath)
                End If

                Path_DETAIL = sPath & EORI & "_CBAM_Detail_" & txtVon._value & "-" & txtBis._value & ".xlsx"
                While System.IO.File.Exists(Path_DETAIL)
                    Path_DETAIL = sPath & EORI & "_CBAM_Detail_" & txtVon._value & "-" & txtBis._value & "_" & Now.ToString("ddMMyyyyHHmmss") & ".xlsx"
                End While

                My.Computer.FileSystem.WriteAllBytes(Path_DETAIL, My.Resources.VERAG_CBAM_Report_Template, False)

                ' =========================================================
                ' Excel schreiben
                ' =========================================================
                Dim wb = New ClosedXML.Excel.XLWorkbook(Path_DETAIL)
                Dim ws = wb.Worksheet("CBAM_Report")

                ' Header
                ws.Cell("A3").Value = txtVon._value
                ws.Cell("C3").Value = txtBis._value

                ' CBAM Declarant
                ws.Cell("A6").Value = "VERAG"
                ws.Cell("B6").Value = ""
                ws.Cell("C6").Value = ""
                ws.Cell("D6").Value = ""
                ws.Cell("E6").Value = ""
                ws.Cell("F6").Value = EORI

                ' Declarant
                ws.Cell("A8").Value = "VERAG"
                ws.Cell("B8").Value = ""
                ws.Cell("C8").Value = ""
                ws.Cell("D8").Value = ""
                ws.Cell("E8").Value = ""
                ws.Cell("F8").Value = EORI

                ' Importer (Default) - aus Parameter / erster Datensatz
                Dim firstImporterName As String = ""
                If dt.Rows.Count > 0 Then
                    firstImporterName = Convert.ToString(dt.Rows(0)("importer_name"))
                End If

                ws.Cell("A10").Value = firstImporterName
                ws.Cell("B10").Value = ""
                ws.Cell("C10").Value = ""
                ws.Cell("D10").Value = ""
                ws.Cell("E10").Value = ""
                ws.Cell("F10").Value = EORI

                ' Alte Detaildatenbereich-Inhalte leeren
                Dim startRow As Integer = 14
            'For r As Integer = startRow To Math.max(ws.LastRowUsed().RowNumber(), startRow + 5000)
            '    For c As Integer = 1 To 47
            '        ws.Cell(r, c).Clear(XLCellClearOptions.Contents)
            '    Next
            'Next

            ' Detaildaten schreiben
            For i As Integer = 0 To dt.Rows.Count - 1
                    For j As Integer = 0 To dt.Columns.Count - 1
                        ws.Cell(startRow + i, j + 1).Value = If(dt.Rows(i)(j), "")
                    Next
                Next

                wb.SaveAs(Path_DETAIL)

                If dt.Rows.Count > 0 Then
                    btnCBAM_DS_VERAG_Detail.Tag = Path_DETAIL
                    btnCBAM_DS_VERAG_Detail.Enabled = True
                    btnCBAM_DS_VERAG_Copy.Enabled = True
                End If

    Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub
    Sub doVERAG_DETAIL_OLD(LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations), EORI As String)

        btnCBAM_DS_VERAG_Detail.Enabled = False
        btnCBAM_DS_VERAG_Detail.Tag = ""

        Try
            Dim details =
            From za In LIST
            From it In za.Items
            Let importer = za.Parties.
                      FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.IMPORTER_ROLES.Contains(p.zaParty_Role))
            Let exporter = za.Parties.
                        FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.EXPORTER_ROLES.Contains(p.zaParty_Role))
            Let invoice =
                        it.Documents.FirstOrDefault(Function(d) d.zaDoc_Code = "N380" OrElse d.zaDoc_Code = "N325")
            Let Anmeldedatum = (Function(x) If(x.za_releaseDate, x.za_DeclarationDate))
            Order By Anmeldedatum
            Select New With {
                            .MRN = za.za_MRN,
                            .SendungsId = za.za_SendungsId,
                            .AvisoId = za.za_AvisoId,
                            .PositionsNummer = it.zaItem_PosNo,
                            .Anmeldedatum = If(za.za_ReleaseDate, za.za_DeclarationDate),
                            .BezugsNr = za.za_LRN,
                            .VertretungsVerhaeltnis = za.za_RepresentationCode,
                            .Tarifnummer = LeftStr(it.zaItem_HSCode, 8),
                            .Eigenmasse = it.zaItem_NetMass,
                            .Rohmasse = it.zaItem_GrossMass,
                            .Ursprungsland = it.zaItem_OriginCountry,
                            .VersendungsLand = za.za_CountryDispatch,
                            .BestimmungsLand = za.za_CountryDestination,
                            .Rechnungspreis = If(it.zaItem_InvoiceValueEUR, it.zaItem_StatisticalValueEUR),
                            .Rechnungswaehrung = it.zaItem_InvoiceCurrency,
                            .EmpfaengerEORI = If(importer IsNot Nothing, importer.zaParty_EORI, ""),
                            .Empfaenger = If(importer IsNot Nothing, importer.zaParty_Name, ""),
                            .AbsenderEORI = If(exporter IsNot Nothing, exporter.zaParty_EORI, ""),
                            .Absender = If(exporter IsNot Nothing, exporter.zaParty_Name, ""),
                            .Rechnungsnummer = If(invoice IsNot Nothing, invoice.zaDoc_Reference, "-"),
                            .Rechnungsdatum = If(invoice IsNot Nothing, ParseDateSafe(invoice.zaDoc_Date), Nothing)
                        }




            Dim dt As New DataTable

            dt.Columns.Add("MRN")
            dt.Columns.Add("PositionsNummer", GetType(Integer))
            dt.Columns.Add("Anmeldedatum", GetType(Date))
            dt.Columns.Add("BezugsNr")
            If cbxKdAtrNr.Checked Then
                dt.Columns.Add("ReferenzKunde")
            Else
                dt.Columns.Add("-")
            End If
            dt.Columns.Add("VertretungsVerhaeltnis")
            dt.Columns.Add("Tarifnummer")
            dt.Columns.Add("Eigenmasse", GetType(Decimal))
            dt.Columns.Add("Rohmasse", GetType(Decimal))
            dt.Columns.Add("Ursprungsland")
            dt.Columns.Add("VersendungsLand")
            dt.Columns.Add("BestimmungsLand")
            dt.Columns.Add("Rechnungspreis", GetType(Decimal))
            dt.Columns.Add("Rechnungswaehrung")
            dt.Columns.Add("EmpfaengerEORI")
            dt.Columns.Add("Empfaenger")
            dt.Columns.Add("AbsenderEORI")
            dt.Columns.Add("Absender")
            dt.Columns.Add("Rechnungsnummer")
            dt.Columns.Add("Rechnungsdatum", GetType(Date))

            If cbxKosten.Checked Then
                dt.Columns.Add("Def_benchmark", GetType(Decimal))
                dt.Columns.Add("Def_Emission", GetType(Decimal))
                dt.Columns.Add("Faktor", GetType(Decimal))
                dt.Columns.Add("EstimatedCost", GetType(Decimal))
            End If


            For Each r In details

                ' =========================================================
                ' Ermittlung Kunden-Auftragsnummer über SendungsId
                ' =========================================================
                Dim KdAtrNr = ""
                If cbxKdAtrNr.Checked Then
                    'If r.SendungsId IsNot Nothing Then
                    '    Dim Snd = New VERAG_PROG_ALLGEMEIN.cSendungen(r.SendungsId)
                    '    If Snd IsNot Nothing Then
                    '        KdAtrNr = Snd.getKdAtrNrByEORI(EORI)
                    '    End If
                    'End If
                    If r.SendungsId IsNot Nothing Then
                        Dim Snd = New VERAG_PROG_ALLGEMEIN.cSendungen(r.SendungsId)
                        If Snd IsNot Nothing Then
                            KdAtrNr = Snd.getKdAtrNr("AUFTRAGGEBER")
                            If KdAtrNr = "" Then
                                KdAtrNr = Snd.getKdAtrNr("EMPFAENGER")
                            End If
                        End If
                    End If
                    'Sonderfall Kanadevia 
                    If EORI = "DE4991397" Then
                        If KdAtrNr.Contains("/") Then
                            Dim split = KdAtrNr.split("/")
                            KdAtrNr = split(0)
                        End If
                    End If
                End If
                ' =========================================================
                ' =========================================================


                If cbxKosten.Checked Then

                    ' =========================================================
                    ' Berechnung pro Zeile
                    ' =========================================================

                    Dim benchmark As Object = Nothing
                    Dim emission As Object = Nothing
                    Dim faktor As Object = Nothing
                    Dim weight = r.Eigenmasse
                    Dim year = If(txtBis._value <> "", CDate(txtBis._value).Year, Now.Year)

                    Dim cost As String = "0"
                    If IsNumeric(txtVERA_ZertPreis._value) Then
                        cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(
                                    cn_code:=Convert.ToString(r.Tarifnummer),
                                    weight / 1000,
                                    country_code:=Convert.ToString(r.Ursprungsland),
                                    CDbl(txtVERA_ZertPreis._value),
                                    year,
                                    cost,
                                    emission,
                                    benchmark,
                                    faktor
                                )
                    Else
                        cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM(
                                    cn_code:=Convert.ToString(r.Tarifnummer),
                                    weight / 1000,
                                    country_code:=Convert.ToString(r.Ursprungsland),
                                    Nothing,
                                    year,
                                    Nothing,
                                    cost,
                                    emission,
                                    benchmark,
                                    faktor
                        )
                    End If

                    Dim Def_benchmark = If(benchmark Is Nothing, "", benchmark)
                    Dim Def_Emission = If(emission Is Nothing, "", emission)
                    Dim EstimatedCost = If(cost < 0, "", Convert.ToDecimal(cost))
                    ' =========================================================
                    ' =========================================================




                    dt.Rows.Add(
                            r.MRN,
                            r.PositionsNummer,
                            If(r.Anmeldedatum, DBNull.Value),
                            r.BezugsNr,
                            KdAtrNr,
                            r.VertretungsVerhaeltnis,
                            r.Tarifnummer,
                            If(r.Eigenmasse, 0D),
                            If(r.Rohmasse, 0D),
                            r.Ursprungsland,
                            r.VersendungsLand,
                            r.BestimmungsLand,
                            If(r.Rechnungspreis, 0D),
                            r.Rechnungswaehrung,
                            r.EmpfaengerEORI,
                            r.Empfaenger,
                            r.AbsenderEORI,
                            r.Absender,
                            r.Rechnungsnummer,
                            If(r.Rechnungsdatum Is Nothing, DBNull.Value, r.Rechnungsdatum),
                            Def_benchmark,
                            Def_Emission,
                            faktor,
                            EstimatedCost
                        )
                Else
                    dt.Rows.Add(
                            r.MRN,
                            r.PositionsNummer,
                            If(r.Anmeldedatum, DBNull.Value),
                            r.BezugsNr,
                            KdAtrNr,
                            r.VertretungsVerhaeltnis,
                            r.Tarifnummer,
                            If(r.Eigenmasse, 0D),
                            If(r.Rohmasse, 0D),
                            r.Ursprungsland,
                            r.VersendungsLand,
                            r.BestimmungsLand,
                            If(r.Rechnungspreis, 0D),
                            r.Rechnungswaehrung,
                            r.EmpfaengerEORI,
                            r.Empfaenger,
                            r.AbsenderEORI,
                            r.Absender,
                            r.Rechnungsnummer,
                            If(r.Rechnungsdatum Is Nothing, DBNull.Value, r.Rechnungsdatum)
                        )
                End If

            Next




            If dt.Rows.Count > 0 Then
                Dim range = If(cbxKosten.Checked, {"L:L", "V:V"}, {"L:L"})

                Dim path = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt, range, , , , False, EORI & "_Detailbericht_" & txtVon._value & "-" & txtBis._value,, True)

                btnCBAM_DS_VERAG_Detail.Tag = path
                btnCBAM_DS_VERAG_Detail.Enabled = True
                btnCBAM_DS_VERAG_Copy.Enabled = True
            End If

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

    Public Shared Function ParseDateSafe(value As String) As Date?
        If String.IsNullOrWhiteSpace(value) Then Return Nothing
        Dim d As DateTime
        If DateTime.TryParseExact(
        value.Trim(),
        {"dd.MM.yyyy", "dd.MM.yyyy HH:mm:ss", "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy", "MM/dd/yyyy HH:mm:ss"},
        Globalization.CultureInfo.InvariantCulture,
        Globalization.DateTimeStyles.None,
        d) Then
            Return d
        End If
        If DateTime.TryParse(value, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, d) Then
            Return d
        End If
        If DateTime.TryParse(value, Globalization.CultureInfo.CurrentCulture, Globalization.DateTimeStyles.None, d) Then
            Return d
        End If
        Return Nothing
    End Function
    Sub doVERAG_GREENPULSE_XLS(LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations), EORI As String)

        btnCBAM_DS_VERAG_GP.Enabled = False
        btnCBAM_DS_VERAG_GP.Tag = ""

        Try
            ' ------------------------------------------------------------
            ' LINQ: Greenpulse-Logik (MRN-aggregiert)
            ' ------------------------------------------------------------
            Dim gp =
                From za In LIST
                Group By MRN = za.za_MRN Into grp = Group
                Let importer = grp.
                    SelectMany(Function(x) x.Parties).
                    FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.IMPORTER_ROLES.Contains(p.zaParty_Role))
                Let exporter = grp.
                    SelectMany(Function(x) x.Parties).
                    FirstOrDefault(Function(p) cVERAG_CustomsDeclarations.EXPORTER_ROLES.Contains(p.zaParty_Role))
                Let invoice = grp.
                    SelectMany(Function(x) x.Documents).
                    FirstOrDefault(Function(d) d.zaDoc_Code = "N380" OrElse d.zaDoc_Code = "N325")
                Select New With {
                    .DeclarationNo = MRN,
                    .DeclarationDate = grp.Max(Function(x) If(x.za_ReleaseDate, x.za_DeclarationDate)),
                    .ImporterEORI = If(importer IsNot Nothing, importer.zaParty_EORI, ""),
                    .ExporterEORI = If(exporter IsNot Nothing, exporter.zaParty_EORI, ""),
                    .CommodityCode = grp.
                        SelectMany(Function(x) x.Items).
                        Select(Function(i) i.zaItem_HSCode).
                        FirstOrDefault(),
                    .OriginCountry = grp.
                        SelectMany(Function(x) x.Items).
                        Select(Function(i) i.zaItem_OriginCountry).
                        FirstOrDefault(),
                    .RequestedProcedure = If(
                        grp.First().za_MainProcedure IsNot Nothing AndAlso
                        grp.First().za_MainProcedure.Length >= 2,
                        grp.First().za_MainProcedure.Substring(0, 2),
                        ""
                    ),
                    .NetMassTonnes = grp.
                        SelectMany(Function(x) x.Items).
                        Sum(Function(i) If(i.zaItem_NetMass, 0D)) / 1000D,
                    .ImporterTitle = If(importer IsNot Nothing, importer.zaParty_Name, ""),
                    .ImporterCountry = If(importer IsNot Nothing, importer.zaParty_Country, ""),
                    .ExporterTitle = If(exporter IsNot Nothing, exporter.zaParty_Name, ""),
                    .ExporterCountry = If(exporter IsNot Nothing, exporter.zaParty_Country, ""),
                    .InvoiceNumber = If(invoice IsNot Nothing, invoice.zaDoc_Reference, "-"),
                    .InvoiceDate = If(invoice IsNot Nothing, invoice.zaDoc_Date, Nothing)
                }


            ' ------------------------------------------------------------
            ' DataTable: exakt Greenpulse-Struktur
            ' ------------------------------------------------------------
            Dim dtGP As New DataTable

            dtGP.Columns.Add("declaration no")
            dtGP.Columns.Add("declaration date", GetType(Date))
            dtGP.Columns.Add("importer identification number")
            dtGP.Columns.Add("exporter identification number")
            dtGP.Columns.Add("commodity code")
            dtGP.Columns.Add("origin country code")
            dtGP.Columns.Add("requested procedure")
            dtGP.Columns.Add("previous procedure")
            dtGP.Columns.Add("net mass", GetType(Decimal))
            dtGP.Columns.Add("type of measurement unit")
            dtGP.Columns.Add("invoice numbers")
            dtGP.Columns.Add("invoice date")
            dtGP.Columns.Add("member state auth")
            dtGP.Columns.Add("discharge bill waiver")
            dtGP.Columns.Add("authorisation")
            dtGP.Columns.Add("start time")
            dtGP.Columns.Add("end time")
            dtGP.Columns.Add("deadline")
            dtGP.Columns.Add("reporting declarant EORI number")
            dtGP.Columns.Add("type of representation")
            dtGP.Columns.Add("importer title")
            dtGP.Columns.Add("importer email")
            dtGP.Columns.Add("importer phone")
            dtGP.Columns.Add("importer country code or member state")
            dtGP.Columns.Add("importer subdivision")
            dtGP.Columns.Add("importer city")
            dtGP.Columns.Add("importer street")
            dtGP.Columns.Add("importer street additional")
            dtGP.Columns.Add("importer address number")
            dtGP.Columns.Add("importer post code")
            dtGP.Columns.Add("importer po box")
            dtGP.Columns.Add("importer coordinate longitude (x)")
            dtGP.Columns.Add("importer coordinate latitude (y)")
            dtGP.Columns.Add("exporter title")
            dtGP.Columns.Add("exporter country code or member state")
            dtGP.Columns.Add("exporter street")
            dtGP.Columns.Add("exporter street additional")

            ' ------------------------------------------------------------
            ' Befüllen
            ' ------------------------------------------------------------
            For Each r In gp
                dtGP.Rows.Add(
            r.DeclarationNo,
            r.DeclarationDate,
            r.ImporterEORI,
            r.ExporterEORI,
            r.CommodityCode,
            r.OriginCountry,
            r.RequestedProcedure,
            "",
            r.NetMassTonnes,
            "TONNES",
            r.InvoiceNumber,
            If(r.InvoiceDate Is Nothing, "-", r.InvoiceDate),
            "",
            "",
            "",
            "",
            "",
            "",
            r.ImporterEORI,
            "",
            r.ImporterTitle,
            "",
            "",
            r.ImporterCountry,
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            r.ExporterTitle,
            r.ExporterCountry,
            "",
            ""
        )
            Next

            ' ------------------------------------------------------------
            ' Excel-Export Greenpulse
            ' ------------------------------------------------------------
            If dtGP.Rows.Count > 0 Then
                btnCBAM_DS_VERAG_GP.Tag =
            createExcelForGreenPulse(dtGP, EORI, "")
                btnCBAM_DS_VERAG_GP.Enabled = True
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub

    Private Sub btnCBAM_DS_VERAG_Detail_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_VERAG_Detail.Click, btnCBAM_DS_VERAG_GP.Click, btnCBAM_DS_VERAG_Summe.Click, btnCBAM_DS_VERAG_SpedB.Click, btnCBAM_DS_VERAG_XML.Click
        If sender.tag <> "" Then
            Try : Process.Start(sender.tag) : Catch : End Try
        End If
    End Sub

    Private Sub btnCBAM_DS_VERAG_Copy_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_VERAG_Copy.Click
        Dim f As New List(Of String)
        If btnCBAM_DS_VERAG_Detail.Tag <> "" Then f.Add(btnCBAM_DS_VERAG_Detail.Tag)
        If btnCBAM_DS_VERAG_Summe.Tag <> "" Then f.Add(btnCBAM_DS_VERAG_Summe.Tag)
        If btnCBAM_DS_VERAG_GP.Tag <> "" Then f.Add(btnCBAM_DS_VERAG_GP.Tag)

        If f.Count > 0 Then
            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, f.ToArray)
            Clipboard.SetDataObject(d, True)
        End If
    End Sub

    Private Sub btnCBAM_DS_VERAG_GenXML_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_VERAG_GenXML.Click


        Button2.Enabled = False
        btnCBAM_DS_VERAG_XML.Enabled = False
        btnCBAM_DS_VERAG_XML.Tag = ""


        Try
            Dim EORI = {txtEori.Text}
            If cbxIndirekt.Checked Then EORI = {cboIndirekt._value}
            If EORI(0) = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            If cbo_VERAG_ImpLand._value = "" Then MsgBox("Importland auswählen!") : Exit Sub


            Dim LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations) = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM(EORI, cbo_VERAG_ImpLand._value, txtVon._value, txtBis._value,, False)

            Me.Cursor = Cursors.WaitCursor

            ' summary
            Dim ImporterRoles = cVERAG_CustomsDeclarations.IMPORTER_ROLES
            Dim summary =
                From za In LIST
                Let importer = za.Parties.FirstOrDefault(Function(p) ImporterRoles.Contains(p.zaParty_Role))
                From it In za.Items
                Let hs8 = LeftStr(it.zaItem_HSCode, 8)
                Group By
                    Tarifnummer = hs8,
                    VersendungsLand = za.za_CountryDispatch,
                    Verfahren = If(it.zaItem_MainProcedure, ""),
                    Vorverfahren = If(it.zaItem_PrevProcedure, ""),
                    Empfaenger = If(importer IsNot Nothing, importer.zaParty_Name, ""),
                    EmpfaengerEORI = If(importer IsNot Nothing, importer.zaParty_EORI, "")
                Into grp = Group
                Select New With {
                    .Tarifnummer = Tarifnummer,
                    .Eigenmasse = grp.Sum(Function(x) If(x.it.zaItem_NetMass, 0D)),
                    .Rohmasse = grp.Sum(Function(x) If(x.it.zaItem_GrossMass, 0D)),
                    .Rechnungspreis = grp.Sum(Function(x) If(x.it.zaItem_InvoiceValueEUR, 0D)),
                    .VersendungsLand = VersendungsLand,
                    .Verfahren = Verfahren,
                    .VorangegangenesVerfahren = Vorverfahren,
                    .Empfaenger = Empfaenger,
                    .EmpfaengerEORI = EmpfaengerEORI
                }



            Dim dt As New DataTable
            dt.Columns.Add("Tarifnummer")
            dt.Columns.Add("Eigenmasse", GetType(Decimal))
            dt.Columns.Add("Rohmasse", GetType(Decimal))
            dt.Columns.Add("Rechnungspreis", GetType(Decimal))
            dt.Columns.Add("VersendungsLand")
            dt.Columns.Add("Verfahren")
            dt.Columns.Add("VorangegangenesVerfahren")
            dt.Columns.Add("Empfänger")
            dt.Columns.Add("EmpfängerEORI")

            For Each r In summary
                dt.Rows.Add(
                    r.Tarifnummer,
                    r.Eigenmasse,
                    r.Rohmasse,
                    r.Rechnungspreis,
                    r.VersendungsLand,
                    r.Verfahren,
                    r.VorangegangenesVerfahren,
                    r.Empfaenger,
                    r.EmpfaengerEORI
                )
            Next



            If dt.Rows.Count > 0 Then
                doCBAM_XML(dt, EORI(0))
                Button2.Enabled = True
                btnCBAM_DS_VERAG_XML.Enabled = True
            End If

        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 btnCBAM_DS_VERAG_SendToGreenpulse_Click(sender As Object, e As EventArgs) Handles btnCBAM_DS_VERAG_SendToGreenpulse.Click

        Try
            Dim EORI = {txtEori.Text}
            If cbxIndirekt.Checked Then EORI = {cboIndirekt._value}
            If EORI(0) = "" Then MsgBox("EORI eingeben!") : Exit Sub
            If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
            If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
            If cbo_VERAG_ImpLand._value = "" Then MsgBox("Importland auswählen!") : Exit Sub

            Me.Cursor = Cursors.WaitCursor
            lblKafkaCnt.Text = "-"

            Dim LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations) = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM(EORI, cbo_VERAG_ImpLand._value, txtVon._value, txtBis._value,, False)

            If LIST Is Nothing AndAlso LIST.Count = 0 Then
                MsgBox("Keine Anmeldungen gefunden!")
                Exit Sub
            End If

            For Each i In LIST
                Console.WriteLine("Regime: " & i.za_REGIME)
            Next

            ' -----------------------------
            ' MRNs aus CustomsDeclarations
            ' -----------------------------
            Dim mrns = LIST.Where(Function(za) (za.za_REGIME.ToString = "IMPORT") AndAlso Not String.IsNullOrWhiteSpace(za.za_MRN)).
                                 Select(Function(za) za.za_MRN).
                                 Distinct().
                                 ToList()

            If mrns.Count = 0 Then Exit Sub

            lblKafkaCnt.Text = "0/" & mrns.Count.ToString()

            ' -----------------------------
            ' Übergabe an Greenpulse/Kafka
            ' -----------------------------
            doCBAM_KafkaFromVERAG_CostomsDeclarations(mrns)

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

    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click

        txtCalcErg.Text = cATEZ_Greenpulse_CBAM_CostCalculation.calcCBAM_ByCertificatePrice(txtCalc_Defaut_KN8._value, txtCalc_Defaut_Weight._value, txtCalc_Defaut_Country._value, txtCalc_Defaut_CertPrice._value, txtCalcJahr._value)

    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles btnVERAGCost.Click
        Dim EORI = {txtEori.Text}
        If cbxIndirekt.Checked Then EORI = {cboIndirekt._value}
        If EORI(0) = "" Then MsgBox("EORI eingeben!") : Exit Sub
        If txtVon._value = "" Then MsgBox("Datum von eingeben!") : Exit Sub
        If txtBis._value = "" Then MsgBox("Datum bis eingeben!") : Exit Sub
        'If cbo_VERAG_ImpLand._value = "" Then MsgBox("Importland auswählen!") : Exit Sub

        Me.Cursor = Cursors.WaitCursor

        Dim SQLSTR_WHERE_FIRMEN = ""
        If cbxVERAG.Checked Then SQLSTR_WHERE_FIRMEN &= "'SUB','WAI','SBG','NKD','NEU','AMBWO','AMB','IRU','EXP','SUW','DUR'"
        If cbxIMEX.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'IME'"
        If cbxUNISPED.Checked Then SQLSTR_WHERE_FIRMEN &= IIf(SQLSTR_WHERE_FIRMEN <> "", ", ", "") & "'ATSPED'" '???


        Dim LIST As List(Of VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations) = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM(EORI, cbo_VERAG_ImpLand._value, txtVon._value, txtBis._value,, True)


        Dim grouped =
                    From za In LIST
                    Where za.Items IsNot Nothing
                    From it In za.Items
                    Let tarif = If(it.zaItem_HSCode IsNot Nothing AndAlso it.zaItem_HSCode.Length >= 8,
                                   it.zaItem_HSCode.Substring(0, 8),
                                   it.zaItem_HSCode)
                    Let country = it.zaItem_OriginCountry
                    Group By tarif, country
                    Into grp = Group
                    Select New With {
                        .Tarif = tarif,
                        .Country = country,
                        .Eigenmasse = grp.Sum(Function(x) If(x.it.zaItem_NetMass, 0D)),
                        .Rohmasse = grp.Sum(Function(x) If(x.it.zaItem_GrossMass, 0D)),
                        .RechnungswertEUR = grp.Sum(Function(x) If(x.it.zaItem_InvoiceValueEUR, 0D))
                    }
        Me.Cursor = Cursors.Default

        Dim f As New frmVorauskasse_CBAM
        f.MyDatagridview1.Rows.Clear()


        For Each g In grouped
            Dim idx = f.MyDatagridview1.Rows.Add()
            Dim eigMasse = If(IsNumeric(g.Eigenmasse), g.Eigenmasse / 1000, 0)
            With f.MyDatagridview1.Rows(idx)
                .Cells("clmnTarif").Value = g.Tarif
                .Cells("clmnWeight").Value = eigMasse
                .Cells("clmnCountry").Value = g.Country
                .Cells("clmnYear").Value = If(txtBis._value <> "" AndAlso CDate(txtBis._value).Year >= 2026, CDate(txtBis._value).Year, Now.Year)
            End With
        Next
        f.autocalc = True
        f.Show()

    End Sub

    Private Sub CheckBox1_CheckedChanged_1(sender As Object, e As EventArgs) Handles cbxIndirekt.CheckedChanged
        cboIndirekt.Visible = cbxIndirekt.Checked
        txtEori.Visible = Not cbxIndirekt.Checked
    End Sub

    Private Sub Button8_Click_1(sender As Object, e As EventArgs) Handles Button8.Click
        Dim LIST = VERAG_PROG_ALLGEMEIN.cVERAG_CustomsDeclarations.LOAD_List_CBAM({}, "", Now.ToShortDateString, Now.ToShortDateString,, False, True)
        MsgBox(LIST.Count & " Einträge: " & vbNewLine & vbNewLine &
               String.Join(vbNewLine, LIST.
                Where(Function(x) Not String.IsNullOrWhiteSpace(x.za_LRN))))
    End Sub

End Class

