Imports com.sun.tools.internal.xjc.reader.gbind
Imports Renci.SshNet
Imports System.IO
Imports System.Windows.Forms

Public Class cDakosyFunftions

    Public Shared Function getFirma_DY(FilialenNr As String, F_ME As Form, Procedure As String) As String
        Dim FIRMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        If (VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO") Or VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX") And FilialenNr = 5501 Then
            FIRMA_DY = "IMEX"
        ElseIf FilialenNr = 5701 Then
            Select Case Procedure
                Case "NCTS"
                    FIRMA_DY = "AMBAR"
                Case Else
                    If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_firma = "AMBAR" Then
                        FIRMA_DY = "AMBAR"
                    Else
                        FIRMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.getFirma ' Akt von AMBAR aber kein AMBAR-MA -> Dakosy unter VERAG!
                    End If
            End Select
        ElseIf FilialenNr = 5601 Then
            FIRMA_DY = "UNISPED"
        ElseIf FilialenNr = 4801 Or FilialenNr = 4802 Then
            FIRMA_DY = "ATILLA"
        Else
            If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Then

                'If DY Is Nothing Then
                Dim f As New frmDakosy_SelFirma
                If f.ShowDialog() = DialogResult.OK Then
                    FIRMA_DY = f.FIMRA_DY
                Else
                    If F_ME IsNot Nothing Then F_ME.Close()
                End If
                'End If
            Else
                FIRMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(FilialenNr)
            End If
        End If
        Return FIRMA_DY
    End Function

    Public Shared Sub replaceNullDateXML(XMLFile As String)
        Try
            If Not System.IO.File.Exists(XMLFile) Then Exit Sub
            Dim lines() As String = System.IO.File.ReadAllLines(XMLFile)
            Using writer = New System.IO.StreamWriter(XMLFile, False)
                For Each line In lines
                    If Not line.Contains("0001-01-01") Then writer.WriteLine(line)
                Next
            End Using

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub
    Shared Function getDivision(FIRMA_DY, PROCEDURE, Optional fiskal = False) As String
        If If(FIRMA_DY, "") = "" Then FIRMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
            Return "SUB"
        Else
            Select Case FIRMA_DY
                Case "ATILLA"
                    Return "SUW"
                Case "AMBAR"
                    Return "AMBWO"
                Case "VERAG"
                    Select Case PROCEDURE ' Wenn EZA,... -> Alles über Suben
                        Case "EZA", "AA", "AES", "T1", "T2"
                            Return "SUB"
                        Case Else '  -->  NCTS
                            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER IsNot Nothing Then
                                Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_niederlassung
                                    Case "SUB" : Return "SUB"
                                    Case "SBG" : Return "SBG"
                                    Case "NKD" : Return "NKD"
                                    Case "NEU" : Return "SUB" 'Return "NEU"
                                    Case "WAI" : Return "WAI"
                                    Case Else : Return "SUB"
                                End Select
                            Else
                                Return "SUB"
                            End If
                    End Select

                Case "UNISPED"
                    Return ""'"ATSP"
                Case "IMEX"
                    If fiskal Then
                        Return "GLO"
                    Else
                        Select Case PROCEDURE ' Wenn AA,... -> Alles über VERG/SUB
                            Case "AA"
                                Return "SUB"
                            Case Else
                                Return "IME"
                        End Select
                    End If
                Case Else : Return "SUB"
            End Select
        End If

    End Function

    Shared Function getIOPartner(FIRMA_DY, PROCEDURE) As String
        If If(FIRMA_DY, "") = "" Then FIRMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
            Return "VERA"
        Else
            Select Case FIRMA_DY
                Case "ATILLA"
                    Return "VERG"
                Case "VERAG"
                    Return "VERG"
                Case "DURMAZ"
                    Return "DUR"
                Case "IMEX"
                    Select Case PROCEDURE ' Wenn AA,... -> Alles über VERAG
                        Case "AA"
                            Return "VERG"
                        Case Else
                            Return "IMEX"
                    End Select
                Case "UNISPED"
                    Return "UNAT"
                Case "AMBAR"
                    Select Case PROCEDURE ' Wenn AA über VERAG
                        Case "AA"
                            Return "VERG"
                        Case Else
                            Return "VERG"  '"VRAS" 'warum auch immer.. irgendwie wg der eigenen EORI von AMBAR..
                    End Select
                Case Else : Return "VERG"
            End Select
        End If

    End Function
    Shared Function send_Data_To_Dakosy_FTP(file, dySt_BezugsNr, dy_Id, FRIMA_DY)
        Try
            If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("ZOLL_DakosyZA_Senden", "AVISO") Then
                MsgBox("Sie haben keine Sendeberechtigung.")
                Return False
            End If

            If Not System.IO.File.Exists(file) Then Return False
            Dim F As New System.IO.FileInfo(file)

            Dim DY_server = ""
            Dim DY_name = ""
            Dim DY_pwd = ""
            Dim DY_port = ""
            Dim DY_PFAD_IN = ""
            Dim DY_PFAD_IN_KD = ""

            getSFTPLoginData(DY_server, DY_name, DY_pwd, DY_port, DY_PFAD_IN, "", DY_PFAD_IN_KD, FRIMA_DY)

            Dim ConnectionInfo As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))
            Using client = New SftpClient(ConnectionInfo)
                client.Connect()
                'client.Create(file, file)
                client.ChangeDirectory(DY_PFAD_IN)
                If System.IO.File.Exists(file) Then
                    'MsgBox(file)
                    Using uplfileStream = System.IO.File.OpenRead(file)
                        client.UploadFile(uplfileStream, "." & F.Name, True)
                        client.RenameFile("." & F.Name, F.Name)
                    End Using
                    client.Disconnect()
                Else
                    MsgBox("Sendedatei nicht gefunden!")
                End If


            End Using

            Dim STATUS As New DAKOSY_Worker.cDakosy_Statusmeldungen
            STATUS.dySt_BezugsNr = dySt_BezugsNr
            STATUS.dySt_artMitteilung = "VERAG_SND"
            STATUS.dySt_dyArt = "" '"NCTS" 'T1/T2

            STATUS.dySt_status = DAKOSY_Worker.cDY_Statusliste.S_03
            'STATUS.dySt_ergCode = "ANR"
            STATUS.dySt_ergCode = "SND"
            STATUS.dySt_ergMitteilung = "An Dakosy gesendet"
            STATUS.dySt_ergZeitpunkt = Now

            STATUS.dySt_dyId = dy_Id
            STATUS.SAVE()

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

    Shared Function send_Data_To_Dakosy_FTP_file(file, FRIMA_DY, Optional misc = False)
        Try
            If Not System.IO.File.Exists(file) Then Return False
            Dim F As New System.IO.FileInfo(file)

            Dim DY_server = ""
            Dim DY_name = ""
            Dim DY_pwd = ""
            Dim DY_port = ""
            Dim DY_PFAD_IN = ""
            Dim DY_PFAD_IN_KD = ""

            If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "" Then VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
            If FRIMA_DY = "" Then FRIMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

            getSFTPLoginData(DY_server, DY_name, DY_pwd, DY_port, DY_PFAD_IN, "", DY_PFAD_IN_KD, FRIMA_DY)

            Dim ConnectionInfo As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))
            Using client = New SftpClient(ConnectionInfo)
                client.Connect()
                'client.Create(file, file)
                If misc Then
                    client.ChangeDirectory(DY_PFAD_IN_KD) 'DY_PFAD_IN.Replace("gebox", "misc"))
                Else
                    client.ChangeDirectory(DY_PFAD_IN)
                End If

                If System.IO.File.Exists(file) Then
                    'MsgBox(file)
                    Using uplfileStream = System.IO.File.OpenRead(file)
                        client.UploadFile(uplfileStream, "." & F.Name, True)
                        client.RenameFile("." & F.Name, F.Name)
                    End Using
                    client.Disconnect()
                Else
                    MsgBox("Sendedatei nicht gefunden!")
                End If


            End Using

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


    Shared Sub getSFTPLoginData(ByRef DY_server, ByRef DY_name, ByRef DY_pwd, ByRef DY_port, ByRef DY_PFAD_IN, ByRef DY_PFAD_OUT, ByRef DY_PFAD_IN_KD, FIRMA_DY)
        If False Then 'VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
            DY_server = cDY_Paramter.GET_PARAM_ByName("FTP_TEST_SERVER", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_name = cDY_Paramter.GET_PARAM_ByName("FTP_TEST_NAME", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_pwd = cDY_Paramter.GET_PARAM_ByName("FTP_TEST_PASSWORD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_port = cDY_Paramter.GET_PARAM_ByName("FTP_TEST_PORT", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)

            DY_PFAD_IN = cDY_Paramter.GET_PARAM_ByName("DY_PFAD_IN", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_PFAD_OUT = cDY_Paramter.GET_PARAM_ByName("DY_PFAD_OUT", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            If DY_PFAD_IN = "" Then DY_PFAD_IN = "in/test/gebox/"
            If DY_PFAD_OUT = "" Then DY_PFAD_OUT = "out/test/"

            DY_PFAD_IN_KD = cDY_Paramter.GET_PARAM_ByName("DY_PFAD_IN_KD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
        Else
            DY_server = cDY_Paramter.GET_PARAM_ByName("FTP_PROD_SERVER", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_name = cDY_Paramter.GET_PARAM_ByName("FTP_PROD_NAME", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_pwd = cDY_Paramter.GET_PARAM_ByName("FTP_PROD_PASSWORD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_port = cDY_Paramter.GET_PARAM_ByName("FTP_PROD_PORT", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)

            DY_PFAD_IN = cDY_Paramter.GET_PARAM_ByName("DY_PFAD_IN", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            DY_PFAD_OUT = cDY_Paramter.GET_PARAM_ByName("DY_PFAD_OUT", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
            If DY_PFAD_IN = "" Then DY_PFAD_IN = "in/prod/gebox/"
            If DY_PFAD_OUT = "" Then DY_PFAD_OUT = "out/prod/"

            DY_PFAD_IN_KD = cDY_Paramter.GET_PARAM_ByName("DY_PFAD_IN_KD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, FIRMA_DY)
        End If

    End Sub


    Shared Function getKDData() As DataTable
        Dim sqlstr = "SELECT TOP 999 *  "
        sqlstr &= " ,(SELECT TOP 1 [Länderverzeichnis für die Außenhandelsstatistik].LandKz AS LandKzISO2 FROM [Länderverzeichnis für die Außenhandelsstatistik] LEFT JOIN Währungstabelle ON [Länderverzeichnis für die Außenhandelsstatistik].LandNr = Währungstabelle.Währungsschlüssel"
        sqlstr &= " WHERE Währungstabelle.LandKz=[Adressen].LandKz) as LandKzISO2"
        sqlstr &= " FROM [Kunden] inner join Adressen on AdressenNr=KundenNr"
        sqlstr &= " where DakosyExport Is null And EORITIN Is Not null"
        'sqlstr &= " and KundenNrZentrale=KundenNr "
        sqlstr &= " and Auswahl='A' "
        sqlstr &= " order by  Kunden.[Geändert am] desc"
        ' MsgBox(sqlstr)
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Return SQL.loadDgvBySql(sqlstr, "FMZOLL")
    End Function

    Shared Function getKDDataByKdNr(KdNR As Integer) As DataTable
        Dim sqlstr = "SELECT TOP 1 *  "
        sqlstr &= " ,(SELECT TOP 1 [Länderverzeichnis für die Außenhandelsstatistik].LandKz AS LandKzISO2 FROM [Länderverzeichnis für die Außenhandelsstatistik] LEFT JOIN Währungstabelle ON [Länderverzeichnis für die Außenhandelsstatistik].LandNr = Währungstabelle.Währungsschlüssel"
        sqlstr &= " WHERE Währungstabelle.LandKz=[Adressen].LandKz) as LandKzISO2"
        sqlstr &= " FROM [Kunden] inner join Adressen on AdressenNr=KundenNr"
        sqlstr &= " where " '/*DakosyExport Is null And EORITIN Is Not null */"
        sqlstr &= "  KundenNr='" & KdNR & "'  "
        sqlstr &= " order by  Kunden.[Geändert am] desc"
        ' MsgBox(sqlstr)
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Return SQL.loadDgvBySql(sqlstr, "FMZOLL")
    End Function


    Shared Function updateKdDakosyExportDate(KdNR As Integer) As Boolean
        Dim sqlstr = "update [Kunden] SET [DakosyExport]=getDate() WHERE KundenNr='" & KdNR & "'  "
        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
        Return SQL.doSQL(sqlstr, "FMZOLL")
    End Function


    Shared Function sendData(Optional defaultFolder As String = "") ', Optional Dakosy_Mandant As String = "VERG")
        Dim Dakosy_Mandant = "VERG"
        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "UNISPED" : Dakosy_Mandant = "UNAT"
                'Case Else
                '    Dakosy_Mandant = "VERG"
        End Select

        Dim dt = DAKOSY_Worker.cDakosyFunftions.getKDData

        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
            Dim saveFile = ""
            If DAKOSY_Worker.cDakosyFunftions.generateVERAGKdData(dt, getDefaultFolder_SEND, saveFile, Dakosy_Mandant) Then
                If cDakosyFunftions.send_Data_To_Dakosy_FTP_file(saveFile, VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, True) Then
                    For Each ROW As DataRow In dt.Rows
                        updateKdDakosyExportDate(ROW("KundenNr"))
                    Next
                    Return True
                End If
            End If
        End If
        Return False
    End Function

    Shared Function sendDataByKdNr(KdNr As Integer, Optional defaultFolder As String = "") ', Optional Dakosy_Mandant As String = "VERG")
        Dim Dakosy_Mandant = "VERG"
        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "UNISPED" : Dakosy_Mandant = "UNAT"
                'Case Else
                '    Dakosy_Mandant = "VERG"
        End Select

        'If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX" Then
        '    MsgBox("Übertrag derzeit nicht möglich!")
        '    Return False
        'End If
        Dim dt = DAKOSY_Worker.cDakosyFunftions.getKDDataByKdNr(KdNr)

        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
            Dim saveFile = ""
            If DAKOSY_Worker.cDakosyFunftions.generateVERAGKdData(dt, getDefaultFolder_SEND, saveFile, Dakosy_Mandant) Then
                If cDakosyFunftions.send_Data_To_Dakosy_FTP_file(saveFile, VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, True) Then
                    updateKdDakosyExportDate(KdNr)
                    Return True
                End If
            End If
        End If
        Return False
    End Function

    Shared Function getDefaultFolder_SEND() As String
        Try
            getDefaultFolder_SEND = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir(False) & "DAKOSY\" & If(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "TESTSYSTEM", "ECHTSYSTEM") & "\Ausgang_Kundendaten\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\" ' Path.GetTempPath
            If Not System.IO.Directory.Exists(getDefaultFolder_SEND) Then
                System.IO.Directory.CreateDirectory(getDefaultFolder_SEND)
            End If
        Catch ex As Exception
            Try
                getDefaultFolder_SEND = "C:\TEMP\" ' Path.GetTempPath
                If Not System.IO.Directory.Exists(getDefaultFolder_SEND) Then
                    System.IO.Directory.CreateDirectory(getDefaultFolder_SEND)
                End If
            Catch ex2 As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                getDefaultFolder_SEND = ""
            End Try
        End Try

    End Function

    Shared Function generateVERAGKdData(dt As DataTable, path As String, ByRef saveFile As String, Optional Dakosy_Mandant As String = "VERG") As Boolean
        Return generateVERAGKdData_V2(dt, path, saveFile, Dakosy_Mandant)
        'Alle mit V2
        '---------------------

        If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX" Then Return generateVERAGKdData_V2(dt, path, saveFile, Dakosy_Mandant)
        Select Case Dakosy_Mandant
            Case "UNAT" : Return generateVERAGKdData_V2(dt, path, saveFile, Dakosy_Mandant)
            Case Else : Return generateVERAGKdData_V1(dt, path, saveFile, Dakosy_Mandant)
        End Select
    End Function


    Shared Function generateVERAGKdData_V1(dt As DataTable, path As String, ByRef saveFile As String, Optional Dakosy_Mandant As String = "VERG") As Boolean
        Try

            Dim Interface_VERSION = "003"

            Dim XML As New DAKOSY_Worker.VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORT

            For Each ROW As DataRow In dt.Rows
                Dim KD As New DAKOSY_Worker.VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDaten
                KD.Dakosy_Mandant = Dakosy_Mandant
                KD.KundenNr = ROW("KundenNr")
                KD.EORI = ROW("EORITIN")
                If ROW("EORITIN_NL") Is DBNull.Value OrElse If(ROW("EORITIN_NL"), "") = "" Then
                    KD.EORI_Niederlassung = "0000"
                Else
                    KD.EORI_Niederlassung = ROW("EORITIN_NL")
                End If
                If ROW("Ordnungsbegriff") IsNot DBNull.Value Then KD.Kurzname = ROW("Ordnungsbegriff")
                If ROW("Name 1") IsNot DBNull.Value Then KD.Name1 = ROW("Name 1")

                If ROW("Name 2") IsNot DBNull.Value Then KD.Name2 = ROW("Name 2")
                If ROW("UstIdKz") IsNot DBNull.Value And ("UstIdNr") IsNot DBNull.Value Then KD.UID_Nr = ROW("UstIdKz") & ROW("UstIdNr")

                KD.Adresse = New DAKOSY_Worker.VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenAdresse
                If ROW("Straße") IsNot DBNull.Value Then KD.Adresse.Strasse = ROW("Straße")
                If ROW("PLZ") IsNot DBNull.Value Then KD.Adresse.Plz = ROW("PLZ")
                If ROW("Ort") IsNot DBNull.Value Then KD.Adresse.Ort = ROW("Ort")
                If ROW("LandKz") IsNot DBNull.Value Then KD.Adresse.LandKz = ROW("LandKzISO2")




                KD.Kontakt = New DAKOSY_Worker.VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenKontakt
                If ROW("E-Mail") IsNot DBNull.Value Then KD.Kontakt.EMail = ROW("E-Mail")
                If ROW("Telefon") IsNot DBNull.Value Then KD.Kontakt.Tel = ROW("Telefon")
                If ROW("Telefax") IsNot DBNull.Value Then KD.Kontakt.Fax = ROW("Telefax")
                If ROW("Ansprechpartner") IsNot DBNull.Value Then KD.Kontakt.Ansprechpartner = If(ROW("Anrede") IsNot DBNull.Value, ROW("Anrede") & " ", "") & ROW("Ansprechpartner")


                Dim KD_AKTO = VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten.LOAD_ListAufschubKTOByKdNr(KD.KundenNr)

                If KD_AKTO IsNot Nothing Then
                    Dim AKTOLIST = New List(Of VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenAufschub)

                    For Each KTO In KD_AKTO
                        If If(KTO.kdAkto_bin, "").ToString.Trim <> String.Empty And
                            If(KTO.kdAkto_eori, "").ToString.Trim <> String.Empty And
                            If(KTO.kdAkto_hauptzollamt, "").ToString.Trim <> String.Empty And
                            If(KTO.kdAkto_kontonummer, "").ToString.Trim <> String.Empty Then


                            Dim AUFSCH As New DAKOSY_Worker.VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenAufschub
                            Select Case KTO.kdAkto_art
                                Case "10" : AUFSCH.Art = VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenAufschubArt.Item10
                                Case "15" : AUFSCH.Art = VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenAufschubArt.Item15
                                Case "20" : AUFSCH.Art = VERAG_KundenStamm_Export.VERAG_Kundenstamm_IMPORTKundenDatenAufschubArt.Item20
                            End Select

                            AUFSCH.BIN = KTO.kdAkto_bin
                            AUFSCH.EORI = KTO.kdAkto_eori
                            If KTO.kdAkto_eoriNL IsNot Nothing Then AUFSCH.EORI_Niederlassung = KTO.kdAkto_eoriNL Else AUFSCH.EORI_Niederlassung = "0000"
                            AUFSCH.Hauptzollamt = KTO.kdAkto_hauptzollamt
                            AUFSCH.KontoNr = KTO.kdAkto_kontonummer

                            AKTOLIST.Add(AUFSCH)
                            If AKTOLIST.Count = 2 Then Exit For 'max. 2 Aufschub
                        End If
                    Next
                    If AKTOLIST.Count > 0 Then KD.Aufschubkonten = AKTOLIST
                End If

                XML.KundenDaten.Add(KD)

            Next

            Dim saveDir = path
            If Not System.IO.Directory.Exists(saveDir) Then
                System.IO.Directory.CreateDirectory(saveDir)
            End If
            Dim counter = 1
            While System.IO.File.Exists(saveDir & "VERAG_KD_" & counter.ToString("D4") & ".xml")
                counter += 1
            End While
            saveFile = saveDir & "VERAG_KD_" & counter.ToString("D4") & ".xml"

            XML.SaveToFile(saveFile)

            Return True

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


    Shared Function generateVERAGKdData_V2(dt As DataTable, path As String, ByRef saveFile As String, Optional Dakosy_Mandant As String = "VERG") As Boolean
        Try

            'Dim Interface_VERSION = "003"

            Dim XML As New DAKOSY_Worker.VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORT

            Dim TRANS As New DAKOSY_Worker.VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTTransaktion
            TRANS.Version = "002"
            TRANS.IOPartner = Dakosy_Mandant

            Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                Case "IMEX" : TRANS.IODivision1 = "IMEX"
                Case "UNISPED" : TRANS.IODivision1 = "UNAT" : TRANS.IOPartner = "UNAT"
                Case "ATILLA" : TRANS.IODivision1 = "ATIL"
                Case Else
                    TRANS.IODivision1 = "VERG"
            End Select
            XML.Transaktion = TRANS


            For Each ROW As DataRow In dt.Rows
                Dim KD As New DAKOSY_Worker.VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDaten
                KD.Dakosy_Mandant = Dakosy_Mandant
                KD.KundenNr = ROW("KundenNr")
                KD.EORI = ROW("EORITIN")
                If ROW("EORITIN_NL") Is DBNull.Value OrElse If(ROW("EORITIN_NL"), "") = "" Then
                    KD.EORI_Niederlassung = "0000"
                Else
                    KD.EORI_Niederlassung = ROW("EORITIN_NL")
                End If
                If ROW("Ordnungsbegriff") IsNot DBNull.Value Then KD.Kurzname = ROW("Ordnungsbegriff")
                If ROW("Name 1") IsNot DBNull.Value Then KD.Name1 = ROW("Name 1")

                If ROW("Name 2") IsNot DBNull.Value Then KD.Name2 = ROW("Name 2")
                If ROW("UstIdKz") IsNot DBNull.Value And ("UstIdNr") IsNot DBNull.Value Then KD.UID_Nr = ROW("UstIdKz") & ROW("UstIdNr")

                KD.Adresse = New DAKOSY_Worker.VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenAdresse
                If ROW("Straße") IsNot DBNull.Value Then KD.Adresse.Strasse = ROW("Straße")
                If ROW("PLZ") IsNot DBNull.Value Then KD.Adresse.Plz = ROW("PLZ")
                If ROW("Ort") IsNot DBNull.Value Then KD.Adresse.Ort = ROW("Ort")
                If ROW("LandKz") IsNot DBNull.Value Then KD.Adresse.LandKz = ROW("LandKzISO2")




                KD.Kontakt = New DAKOSY_Worker.VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenKontakt
                If ROW("E-Mail") IsNot DBNull.Value Then KD.Kontakt.EMail = ROW("E-Mail")
                If ROW("Telefon") IsNot DBNull.Value Then KD.Kontakt.Tel = ROW("Telefon")
                If ROW("Telefax") IsNot DBNull.Value Then KD.Kontakt.Fax = ROW("Telefax")
                If ROW("Ansprechpartner") IsNot DBNull.Value Then KD.Kontakt.Ansprechpartner = If(ROW("Anrede") IsNot DBNull.Value, ROW("Anrede") & " ", "") & ROW("Ansprechpartner")


                Dim KD_AKTO = VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten.LOAD_ListAufschubKTOByKdNr(KD.KundenNr)

                If KD_AKTO IsNot Nothing Then
                    Dim AKTOLIST = New List(Of VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenAufschub)

                    For Each KTO In KD_AKTO
                        If If(KTO.kdAkto_bin, "").ToString.Trim <> String.Empty And
                            If(KTO.kdAkto_eori, "").ToString.Trim <> String.Empty And
                            If(KTO.kdAkto_hauptzollamt, "").ToString.Trim <> String.Empty And
                            If(KTO.kdAkto_kontonummer, "").ToString.Trim <> String.Empty Then


                            Dim AUFSCH As New DAKOSY_Worker.VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenAufschub
                            Select Case KTO.kdAkto_art
                                Case "10" : AUFSCH.Art = VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenAufschubArt.Item10
                                Case "15" : AUFSCH.Art = VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenAufschubArt.Item15
                                Case "20" : AUFSCH.Art = VERAG_KundenStamm_Export_V2.VERAG_Kundenstamm_IMPORTKundenDatenAufschubArt.Item20
                            End Select

                            AUFSCH.BIN = KTO.kdAkto_bin
                            AUFSCH.EORI = KTO.kdAkto_eori
                            If KTO.kdAkto_eoriNL IsNot Nothing Then AUFSCH.EORI_Niederlassung = KTO.kdAkto_eoriNL Else AUFSCH.EORI_Niederlassung = "0000"
                            AUFSCH.Hauptzollamt = KTO.kdAkto_hauptzollamt
                            AUFSCH.KontoNr = KTO.kdAkto_kontonummer

                            AKTOLIST.Add(AUFSCH)
                            If AKTOLIST.Count = 2 Then Exit For 'max. 2 Aufschub
                        End If
                    Next
                    If AKTOLIST.Count > 0 Then KD.Aufschubkonten = AKTOLIST
                End If

                XML.KundenDaten.Add(KD)

            Next

            Dim saveDir = path
            If Not System.IO.Directory.Exists(saveDir) Then
                System.IO.Directory.CreateDirectory(saveDir)
            End If
            Dim counter = 1
            While System.IO.File.Exists(saveDir & "VERAG_KD_" & counter.ToString("D4") & ".xml")
                counter += 1
            End While
            saveFile = saveDir & "VERAG_KD_" & counter.ToString("D4") & ".xml"

            XML.SaveToFile(saveFile)

            Return True

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

End Class
