Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Xml
Imports java.util.function
Imports VERAG_PROG_ALLGEMEIN

Public Class frmMDMNachrichtenVerarbeitung
    Dim cntDatenEingelesen As Integer = 0
    Dim dsNichtErkannt As Integer = 0
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Dim allowClose = False
    '  Dim DY_PFAD = "C:\Users\DEVELOPER1\Desktop\test\TEST\"

    Dim TELOTEC_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Einarbeitung\"
    Dim VERARBEITUNGS_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Einarbeitung\"
    Dim ZIEL_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_Ablage\"
    Dim ERROR_PFAD = "" '"C:\Users\DEVELOPER1\Desktop\test\TEST\Nachrichtendaten_ERROR\"
    ' Dim BOX_VERSION = "8.8"

    Dim Dateiname = ""
    Public newFormatTR As Boolean = False
    Public newFormatINV As Boolean = False

    Sub New()

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

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

    End Sub
    Sub New(allowClose) 'autostart

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.allowClose = allowClose
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Sub initPfade()
        Me.TELOTEC_PFAD = MDM_Worker.cMDM_Paramter.GET_PARAM_ByName("PLOSE_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        Me.VERARBEITUNGS_PFAD = MDM_Worker.cMDM_Paramter.GET_PARAM_ByName("VERARBEITUNGS_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\TESTSYSTEM\Nachrichtendaten_Einarbeitung\"
        Me.ZIEL_PFAD = MDM_Worker.cMDM_Paramter.GET_PARAM_ByName("ZIEL_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\TESTSYSTEM\Nachrichtendaten_Ablage\"
        Me.ERROR_PFAD = MDM_Worker.cMDM_Paramter.GET_PARAM_ByName("ERROR_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getRootDir() & "DAKOSY\TESTSYSTEM\Nachrichtendaten_ERROR\"

        If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
            Me.TELOTEC_PFAD = Me.TELOTEC_PFAD.ToString.Replace("ECHTSYSTEM", "TESTSYSTEM")
            Me.VERARBEITUNGS_PFAD = Me.VERARBEITUNGS_PFAD.ToString.Replace("ECHTSYSTEM", "TESTSYSTEM")
            Me.ZIEL_PFAD = Me.ZIEL_PFAD.ToString.Replace("ECHTSYSTEM", "TESTSYSTEM")
            Me.ERROR_PFAD = Me.ERROR_PFAD.ToString.Replace("ECHTSYSTEM", "TESTSYSTEM")


        End If


        If Not System.IO.Directory.Exists(VERARBEITUNGS_PFAD) Then System.IO.Directory.CreateDirectory(VERARBEITUNGS_PFAD)
        If Not System.IO.Directory.Exists(ZIEL_PFAD) Then System.IO.Directory.CreateDirectory(ZIEL_PFAD)
        If Not System.IO.Directory.Exists(ERROR_PFAD) Then System.IO.Directory.CreateDirectory(ERROR_PFAD)



        'Me.BOX_VERSION = MDM_Worker.cDY_Paramter.GET_PARAM_ByName("BOX_VERSION", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)

    End Sub


    Private Sub frmDYNachrichtenVerarbeitung_Load(sender As Object, e As EventArgs) Handles Me.Load
        initPfade()
        For Each d In System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)
            ListBox3.Items.Add(frmStartOptions.cut_file(d))
            Me.Refresh()
        Next
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.Enabled = False
        Try
            Label9.Visible = True
            Dim cnt = getNachrichtenDatenFromMDMServices() ' If(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, getNachrichtenDatenFromMDMServicesTEST(), getNachrichtenDatenFromMDMServices())
            Label9.Text = cnt & " Datensätze empfangen."

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Enabled = True

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Enabled = False
        Try
            Label5.Visible = True
            DatenEinlesen()
            If dsNichtErkannt > 0 Then

                Label6.Text = dsNichtErkannt & " Datensätze nicht " & vbNewLine & "erkannt."
                Label6.Visible = True
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Enabled = True
        Label5.Text = cntDatenEingelesen & " Datensätze verarbeitet."

    End Sub


    Function getNachrichtenDatenFromMDMServices() As Integer
        Dim cnt = 0
        Try

            Dim MDM_server = ""
            Dim MDM_name = ""
            Dim MDM_pwd = ""
            Dim MDM_port = ""
            Dim MDM_PFAD_out = ""

            MDM_Worker.cMDMFunctions.getSFTPLoginData(MDM_server, MDM_name, MDM_pwd, MDM_port, "", MDM_PFAD_out)

            DownloadFtpDirectory(MDM_server & "/"c & MDM_PFAD_out, New NetworkCredential(MDM_name, MDM_pwd), "", cnt, True)
            ' DownloadFtpDirectory("ftp://80.16.102.180" & "/"c & MDM_PFAD_out, New NetworkCredential(MDM_name, MDM_pwd), "", cnt, True)

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return cnt
    End Function


    Sub DownloadFtpDirectory(url As String, credentials As NetworkCredential, localPath As String, ByRef cnt As Integer, deleteAfterDownload As Boolean)
        Dim listRequest As FtpWebRequest = WebRequest.Create(url)
        listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
        listRequest.Credentials = credentials


        Dim lines As List(Of String) = New List(Of String)

        Using listResponse As FtpWebResponse = listRequest.GetResponse(),
          listStream As Stream = listResponse.GetResponseStream(),
          listReader As StreamReader = New StreamReader(listStream)
            While Not listReader.EndOfStream
                lines.Add(listReader.ReadLine())
            End While
        End Using

        For Each line As String In lines
            Dim tokens As String() =
            line.Split(New Char() {" "}, 9, StringSplitOptions.RemoveEmptyEntries)
            Dim name As String = tokens(8)
            Dim permissions As String = tokens(0)

            Dim localFilePath As String = Path.Combine(localPath, name)
            Dim fileUrl As String = url + name

            If permissions(0) = "d" Then 'Ordner
                If Not Directory.Exists(localFilePath) Then
                    Directory.CreateDirectory(localFilePath)
                End If
                DownloadFtpDirectory(fileUrl + "/", credentials, localFilePath, cnt, deleteAfterDownload)

            Else

                If True Then
                    '  Temp.DownloadPfad

                    Dim downloadRequest As FtpWebRequest = WebRequest.Create(fileUrl)
                    downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
                    downloadRequest.Credentials = credentials

                    Dim fileDateTmp As Date = ServerDateFile(credentials, fileUrl)

                    'Dim destFilenameTMP = VERARBEITUNGS_PFAD & "." & If(IO.File.Exists(VERARBEITUNGS_PFAD & "." & name), name.Replace(".csv", "_") & " RGDAT_" & fileDateTmp.ToShortDateString & "_" & Now.ToString("yyMMdd_HHmmss.fff") & ".csv", name)
                    ' Dim FimeNameTmp = If(IO.File.Exists(VERARBEITUNGS_PFAD & "." & name), name.Replace(".csv", "_") & " RGDAT_" & fileDateTmp.ToShortDateString & "_" & Now.ToString("yyMMdd_HHmmss.fff") & ".csv", name)
                    name = name.Replace(".csv", "_RGDAT_" & fileDateTmp.ToShortDateString & ".csv")

                    Dim destFilenameTMP = VERARBEITUNGS_PFAD & "." & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & "." & name), name.Replace(".csv", "_") & Now.ToString("yyMMdd_HHmmss.fff") & ".csv", name)

                    Using downloadResponse As FtpWebResponse = downloadRequest.GetResponse(),
                      sourceStream As Stream = downloadResponse.GetResponseStream(),
                      targetStream As Stream = File.OpenWrite(destFilenameTMP)
                        Dim buffer As Byte() = New Byte(10240 - 1) {}
                        Dim read As Integer
                        Do
                            read = sourceStream.Read(buffer, 0, buffer.Length)
                            If read > 0 Then
                                targetStream.Write(buffer, 0, read)
                            End If
                        Loop While read > 0

                        sourceStream.Dispose()
                        targetStream.Dispose()
                        downloadResponse.Dispose()

                        Dim destFilename = VERARBEITUNGS_PFAD & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & name), name.Replace(".csv", "_") & Now.ToString("yyMMdd_HHmmss.fff") & ".csv", name)

                        System.IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen


                        Dim fi As FileInfo = New FileInfo(destFilename)
                        ListBox3.Items.Add(frmStartOptions.cut_file(fi.Name)) 'zur Liste hinzufügen
                        cnt += 1


                        'Datei nach download löschen
                        If deleteAfterDownload Then
                            Dim ftpReq As FtpWebRequest = WebRequest.Create(fileUrl)
                            ftpReq.Method = WebRequestMethods.Ftp.DeleteFile
                            ftpReq.Credentials = credentials
                            Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
                            ftpResp.Close()
                        End If

                    End Using
                End If
            End If
        Next
    End Sub



    Private Function ServerDateFile(credentials As NetworkCredential, fileUrl As String) As Date
        Dim ServerDate As DateTime
        Try
            Dim request As FtpWebRequest = WebRequest.Create(fileUrl)
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp
            request.Credentials = credentials

            Using response = CType(request.GetResponse(), Net.FtpWebResponse)
                ServerDate = response.LastModified.ToShortDateString
            End Using

            Return ServerDate
        Catch ex As WebException
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "PLOSE GET DATE FILE: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return ServerDate
    End Function



    Function getNachrichtenDatenFromMDMServices_ALTERNATIV() As Integer
        Dim cnt = 0
        Try
            For Each f In System.IO.Directory.GetFiles(TELOTEC_PFAD)
                Dim FI As New FileInfo(f)
                If Not FI.Name.StartsWith(".") Then
                    'Temp. DownloadPfad
                    Dim destFilenameTMP = VERARBEITUNGS_PFAD + "." & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & "." & FI.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & FI.Name

                    'Datei herunterladen
                    System.IO.File.Copy(f, destFilenameTMP)
                    If System.IO.File.Exists(destFilenameTMP) Then System.IO.File.Delete(f) 'Datei nach erfolgreichem Herunterladen vom Server löschen

                    'Gültiger Filename
                    Dim destFilename = VERARBEITUNGS_PFAD & If(System.IO.File.Exists(VERARBEITUNGS_PFAD & FI.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & FI.Name
                    System.IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen

                    Dim fi_dest As FileInfo = New FileInfo(destFilename)
                    ListBox3.Items.Add(frmStartOptions.cut_file(fi_dest.Name)) 'zur Liste hinzufügen
                    cnt += 1
                    lblDatenCnt.Text = cnt
                    Me.Refresh()
                End If
            Next
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return cnt

        'Dim cnt = 0
        'Try
        '    Dim DY_server = ""
        '    Dim DY_name = ""
        '    Dim DY_pwd = ""
        '    Dim DY_port = ""
        '    Dim DY_PFAD_out = ""

        '    DAKOSY_Worker.cDakosyFunftions.getSFTPLoginData(DY_server, DY_name, DY_pwd, DY_port, "", DY_PFAD_out)


        '    Dim ConnectionInfo As New ConnectionInfo(DY_server, DY_port, DY_name, New PasswordAuthenticationMethod(DY_name, DY_pwd))
        '    Using client = New SftpClient(ConnectionInfo)
        '        client.Connect()

        '        For Each f In client.ListDirectory(DY_PFAD_out)
        '            '   MsgBox(f.Name)
        '            If Not f.Name.StartsWith(".") Then
        '                'Temp. DownloadPfad
        '                Dim destFilenameTMP = VERARBEITUNGS_PFAD + "." & If(IO.File.Exists(VERARBEITUNGS_PFAD & "." & f.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & f.Name

        '                'Datei herunterladen
        '                Dim downloadFileStream As Stream = File.OpenWrite(destFilenameTMP)
        '                client.DownloadFile(f.FullName, downloadFileStream)
        '                If IO.File.Exists(destFilenameTMP) Then client.DeleteFile(f.FullName) 'Datei nach erfolgreichem Herunterladen vom Server löschen
        '                downloadFileStream.Dispose()

        '                'Gültiger Filename
        '                Dim destFilename = VERARBEITUNGS_PFAD & If(IO.File.Exists(VERARBEITUNGS_PFAD & f.Name), Now.ToString("yyMMdd_HHmmss.fff_"), "") & f.Name
        '                IO.File.Move(destFilenameTMP, destFilename) 'Datei umbenennen

        '                Dim fi As FileInfo = New FileInfo(destFilename)
        '                ListBox3.Items.Add(frmStartOptions.cut_file(fi.Name)) 'zur Liste hinzufügen
        '                cnt += 1
        '            End If
        '        Next
        '        client.Disconnect()
        '    End Using
        'Catch ex As Exception
        '    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        'End Try

        'Return cnt
    End Function





    ' Dim toEncodeAsBytes() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode)
    '  string returnValue            = System.Convert.ToBase64String(toEncodeAsBytes)
    Public Function stripNonValidXMLCharacters(ByVal textIn As String) As String
        Dim textOut As System.Text.StringBuilder = New System.Text.StringBuilder()
        Dim current As Char
        If textIn Is Nothing OrElse textIn = String.Empty Then Return String.Empty
        For i As Integer = 0 To textIn.Length - 1
            current = textIn(i)
            If (current = "9" OrElse current = "10" OrElse current = "13") OrElse ((current >= "32") AndAlso (current <= "55295")) OrElse ((current >= "57344") AndAlso (current <= "65533")) OrElse ((current >= "65536") AndAlso (current <= "1114111")) Then
                textOut.Append(current)
            End If
        Next

        Return textOut.ToString()
    End Function

    Public Function SanitizeXmlString(ByVal xml As String) As String
        If xml Is Nothing Then
            Throw New ArgumentNullException("xml")
        End If

        Dim buffer As System.Text.StringBuilder = New System.Text.StringBuilder(xml.Length)
        For Each c As Char In xml
            If IsLegalXmlChar(Asc(c)) Then
                buffer.Append(c)
            End If
        Next

        Return buffer.ToString()
    End Function

    Public Function IsLegalXmlChar(ByVal character As Integer) As Boolean
        Return (character = 9 OrElse character = 10 OrElse character = 13 OrElse (character >= 32 AndAlso character <= 55295) OrElse (character >= 57344 AndAlso character <= 65533) OrElse (character >= 65536 AndAlso character <= 1114111))
    End Function



    Sub DatenEinlesen()

        VERAG_PROG_ALLGEMEIN.cAllgemein.ERR_OP_GLOBAL = VERAG_PROG_ALLGEMEIN.ERROR_OP.MAIL

        If ListBox3.Items.Count = 0 Then
            Label6.Text = "Keine Daten zum Einlesen vorhanden."
            Label6.Visible = True
            Exit Sub
        End If

        For i = 1 To 5

            For Each d In System.IO.Directory.GetFiles(VERARBEITUNGS_PFAD)
                Try
                    Dateiname = d
                    cWorker_NCTS.Dateiname = d
                    If System.IO.File.Exists(d) Then
                        Dim found = False
                        Dim fi As FileInfo = New FileInfo(d)

                        '   EDIFACT
                        ' If fi.Extension = ".edi" Then
                        Dim alreadyMoved = False

                        '------------------------------------------------------------------------------------------------------------------------------
                        '                                                                  PLOSE
                        '------------------------------------------------------------------------------------------------------------------------------


                        Select Case i
                            Case 1
                                '------------------------------------------
                                '------------------ DETAIL ------------------
                                '------------------------------------------
                                If fi.Extension.ToLower = ".csv" Then

                                    If Not newFormatTR AndAlso (Not found And cGetMsgType.isPLOSE_Detail(d)) Then
                                        If readPLOSE_Detail(d) <> "" Then found = True

                                    ElseIf newFormatTR AndAlso (Not found And cGetMsgType.isPLOSE_NewFormat_TR(d)) Then
                                        If readPLOSE_Detail_NEW_FORMAT(d) <> "" Then found = True
                                    End If
                                    If found Then cntDatenEingelesen += 1
                                End If
                            Case 2
                                '------------------------------------------
                                '------------------ HEADER ------------------
                                '------------------------------------------
                                If fi.Extension.ToLower = ".csv" Then


                                    If Not found And cGetMsgType.isPLOSE_Header(d) Then
                                        If readPLOSE_Header(d) <> "" Then found = True
                                        ' If bezugsNr <> "" Then addDGVEinarbeitung("NCTS: Versandbestätigung", bezugsNr) : found = True
                                    End If
                                    If found Then cntDatenEingelesen += 1
                                End If
                            Case 3
                                '------------------------------------------
                                '------------------ PLOSE_INVData: neues CSV --> Rechnungen + PDF-Link ------------------
                                '------------------------------------------

                                If fi.Extension.ToLower = ".csv" Then


                                    If Not newFormatINV AndAlso Not found And cGetMsgType.isPLOSE_INVData(d) Then
                                        If readPLOSE_INVData(d) <> "" Then found = True
                                        '    ' If bezugsNr <> "" Then addDGVEinarbeitung("NCTS: Versandbestätigung", bezugsNr) : found = True
                                    ElseIf newFormatINV AndAlso Not found And cGetMsgType.isPLOSE_NewFormat_INV(d) Then
                                        If readPLOSE_INVData_NEW_FORMAT(d) <> "" Then found = True

                                    End If


                                    If found Then cntDatenEingelesen += 1
                                End If

                            Case 4
                                '------------------------------------------
                                '------------------ PDF ------------------
                                '------------------------------------------
                                If fi.Extension.ToLower = ".pdf" Then
                                    found = False

                                    If Not System.IO.Directory.Exists(ZIEL_PFAD & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\") Then System.IO.Directory.CreateDirectory(ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")

                                    'File in Datenarchiv sichern:
                                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("MDM", "MDM_DATEN", "PLOSE", Now.Year, Now.ToString("yyyyMMdd"), frmStartOptions.getFileName(d),)
                                    DS.uploadDataToDATENSERVER(d)
                                    'DatenArchiv-Id in tblPLOSE_Inv_Data Tabelle eintragen (über PDF-Name) :
                                    Dim EintragVorhanden As Integer = CInt(SQL.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM tblPLOSE_Inv_Data where [plInv_PdfFileName] = '" & DS.da_name & "'", "FMZOLL"))
                                    If EintragVorhanden > 0 Then
                                        SQL.doSQL("Update [tblPLOSE_Inv_Data] SET [plInv_daId]='" & DS.da_id & "' where [plInv_PdfFileName] = '" & DS.da_name & "' and [plInv_Einlesedatum] > DATEADD(DAY,-60,getdate()) and [plInv_daId] is null  ", "FMZOLL")
                                    Else

                                        'beispiel 1
                                        '542073_2504495.01_2025-fln-000004495.pdf -> DATEINAME laut DB Eintrag
                                        'b_542073_2504495.01_2025-fln-000004495.pdf -> DATEINAME im Datenarchiv
                                        'alle vorangehenden Buchstaben und Zeichen abschneiden und mit der ersten Zahl beginnen!!

                                        'beispiel 2
                                        '510101-2503740.01_2025-sfc-000003740.pdf -> DATEINAME laut DB Eintrag
                                        'b_510101_2503740.01_2025-sfc-000003740.pdf -> DATEINAME im Datenarchiv

                                        Dim filename = frmStartOptions.getFileName(d)
                                        If Regex.IsMatch(filename, "^[A-Za-z]") Then
                                            Dim match As Match = Regex.Match(filename, "\d+")
                                            If match.Success Then
                                                Dim fileNameNew = filename.Substring(match.Index).Trim
                                                EintragVorhanden = CInt(SQL.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM tblPLOSE_Inv_Data where [plInv_PdfFileName] ='" & fileNameNew & "'", "FMZOLL"))
                                                If EintragVorhanden > 0 Then
                                                    SQL.doSQL("Update [tblPLOSE_Inv_Data] SET [plInv_daId]='" & DS.da_id & "'   where [plInv_PdfFileName] = '" & fileNameNew & "' and [plInv_Einlesedatum] > DATEADD(DAY,-60,getdate()) and [plInv_daId] is null  ", "FMZOLL")

                                                Else
                                                    If filename.Contains("-") Then
                                                        EintragVorhanden = CInt(SQL.getValueTxtBySqlVarList("SELECT isnull(count(*),0) FROM tblPLOSE_Inv_Data where replace([plInv_PdfFileName],'-','_') ='" & fileNameNew.ToString.Replace("-", "_") & "'", "FMZOLL"))
                                                        If EintragVorhanden > 0 Then
                                                            SQL.doSQL("Update [tblPLOSE_Inv_Data] SET [plInv_daId]='" & DS.da_id & "' where replace([plInv_PdfFileName],'-','_') ='" & fileNameNew.ToString.Replace("-", "_") & "' and [plInv_Einlesedatum] > DATEADD(DAY,-60,getdate()) and [plInv_daId] is null  ", "FMZOLL")
                                                        End If
                                                    End If

                                                End If
                                            End If

                                        End If
                                    End If

                                    frmStartOptions.moveFile_DateBack(d, ZIEL_PFAD & "Invoice_PDF\" & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                    addDGVEinarbeitung("PDF", DS.da_name)
                                    dgvEinarbeitung.Refresh()

                                    'Eintrag 
                                End If



                            Case 5
                                frmStartOptions.moveFile_DateBack(d, ERROR_PFAD)
                                dsNichtErkannt += 1
                        End Select


                        If True Then
                            If Not alreadyMoved Then
                                If found Then
                                    If Not System.IO.Directory.Exists(ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\") Then System.IO.Directory.CreateDirectory(ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                    frmStartOptions.moveFile_DateBack(d, ZIEL_PFAD & Now.Year & "\" & Now.ToString("yyyyMMdd") & "\")
                                End If
                            End If
                        End If

                        Me.Refresh()

                    End If
                Catch ex As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                End Try
            Next
        Next

        'Dim sql_setMDMEinarbeitung As String = "UPDATE tblMDMEinarbeitung
        '                                    SET billingdate =
        '                                        CASE
        '                                            WHEN DAY(invoicedate) < 15 THEN
        '                                                EOMONTH(DATEADD(MONTH, -1, invoicedate))
        '                                            ELSE
        '                                                DATEFROMPARTS(YEAR(invoicedate), MONTH(invoicedate), 15)
        '                                        END
        '                                    WHERE supplier = 'PLOSE'
        '                                      AND billingdate IS NULL;"

        'SQL.doSQL(sql_setMDMEinarbeitung, "FMZOLL")

    End Sub



    Function getString(doc As XmlDocument) As Boolean
        If doc.HasChildNodes Then
            '  If doc.GetElementsByTagName("DakosyMessageInternal").Count > 0 Then
            Dim sw = New StringWriter()
            Dim xw = New XmlTextWriter(sw)
            doc.WriteTo(xw)
            Dim XmlString = sw.ToString()
            MsgBox(XmlString)
        End If
        Return False
    End Function



    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        Me.Close()
    End Sub

    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
        Me.Close()
    End Sub



    Sub addDGVEinarbeitung(art, BezugsNr)
        dgvEinarbeitung.Rows.Add(art, BezugsNr)
        Try
            dgvEinarbeitung.FirstDisplayedScrollingRowIndex = dgvEinarbeitung.RowCount - 1
        Catch ex As Exception
        End Try
    End Sub






    Function readPLOSE_Detail(d As String) As String
        Try
            readPLOSE_Detail = ""
            Dim KdnR = ""

            Dim plose_RechnungsJahr = ""
            Dim plose_RechnungsLieferantCode = ""
            Dim plose_RechnungsNr = ""


            Dim counTrans As Integer = 0
            Dim savedTrans As Integer = 0
            Dim MDMEinarb As New cMDMEinarbeitung("PLOSE", Now(), Now())

            Dim plose_RechnungsDat = Nothing
            Dim plose_Lieferant = Nothing

            Dim fi As FileInfo = New FileInfo(d)
            If fi.Name.Length > 8 Then
                'Dim plose_RechnungsNr = fi.Name.Substring(0, 8)

                plose_RechnungsJahr = fi.Name.Substring(0, 2)
                plose_RechnungsLieferantCode = fi.Name.Substring(2, 1)
                ' plose_RechnungsNr = fi.Name.Substring(3, 5)


                '--------> auslesen [tblPLOSE_Lieferant]
                Select Case plose_RechnungsLieferantCode
                    Case "0" : plose_Lieferant = "PLOSE Sistem Service"
                    Case "7" : plose_Lieferant = "Consortio PLOSE"
                    Case "1" : plose_Lieferant = "Plose Union"
                    Case "9" : plose_Lieferant = "PLOSE UNION SOCIETA COOPERATIVA"
                End Select

                'FALSCHE WERTE!!!
                'If fi.FullName.Contains("_RGDAT_") Then
                '    Try
                '        plose_RechnungsDat = CDate(fi.FullName.Substring(fi.FullName.IndexOf("_RGDAT_") + 7, 10))
                '    Catch ex As Exception
                '        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "PLOSE RG DATUM, FILE: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                '    End Try
                'End If
            End If

            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(d, Encoding.UTF8)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(";")
                Dim currentRow As String()

                Dim cnt = 0
                If True Then



                    While Not MyReader.EndOfData
                        Try


                            currentRow = MyReader.ReadFields()


                            If True Then 'fi.Name.Length > 8 Then



                                Select Case currentRow(0)
                                    Case "TR1"
                                        'RECHNUGNSDATUM
                                        If currentRow.Length > 1 AndAlso currentRow(1).ToString.Length = 8 Then
                                            Dim datumParse = DateTime.ParseExact(currentRow(1), "yyyyMMdd", Nothing)
                                            plose_RechnungsDat = datumParse 'Rechnungsdatum aus TR1 Datensatz, überschreibt den Wert aus der Dateierstellung
                                        End If
                                        'RECHNUGNSNR
                                        If currentRow.Length > 2 Then 'AndAlso currentRow(1).ToString.Length = 8 Then
                                            plose_RechnungsNr = SQL.isleernothing(currentRow(2)) 'Rechnungsdatum aus TR1 Datensatz, überschreibt den Wert aus der Dateierstellung
                                        End If

                                    Case "TR5"
                                        If currentRow.Length > 24 AndAlso currentRow(12) <> "839160" Then 'KDNR <> VERAG --> Die Kosten bleiben uns
                                            Dim PLOSE As New MDM_Worker.cPLOSE

                                            PLOSE.plose_Dateiname = fi.Name
                                            PLOSE.plose_RechnungsNr = plose_RechnungsNr
                                            PLOSE.plose_Lieferant = plose_Lieferant
                                            PLOSE.plose_LieferantCode = plose_RechnungsLieferantCode
                                            PLOSE.plose_RechnungsJahr = plose_RechnungsJahr
                                            If plose_RechnungsDat IsNot Nothing Then PLOSE.plose_RechnungsDatum = plose_RechnungsDat
                                            PLOSE.plose_Datensatztyp = SQL.isleernothing(currentRow(0))
                                            PLOSE.plose_KodexMautTankstelle = SQL.isleernothing(currentRow(1))
                                            PLOSE.plose_BeschreibungMautTankstelle = SQL.isleernothing(currentRow(2))
                                            PLOSE.plose_KodexEinfahrt = SQL.isleernothing(currentRow(3))
                                            PLOSE.plose_BeschreibungEinfahrt = SQL.isleernothing(currentRow(4))
                                            PLOSE.plose_KodexAusfahrt = SQL.isleernothing(currentRow(5))
                                            PLOSE.plose_BeschreibungAusfahrt = SQL.isleernothing(currentRow(6))
                                            PLOSE.plose_Kartenkodex = SQL.isleernothing(currentRow(7))
                                            PLOSE.plose_Kontonummer = SQL.isleernothing(currentRow(8))
                                            PLOSE.plose_NummerKarteGeraet = SQL.isleernothing(currentRow(9))
                                            PLOSE.plose_Kennzeichen = SQL.isleernothing(currentRow(10))
                                            PLOSE.plose_InterneNrFahrzeug = SQL.isleernothing(currentRow(11))
                                            PLOSE.plose_POLSEKundennummer = SQL.isleernothing(currentRow(12))
                                            PLOSE.plose_Firmenname = SQL.isleernothing(currentRow(13))
                                            PLOSE.plose_DatumTransaktion = SQL.isleernothingDateFormatstring(currentRow(14))
                                            PLOSE.plose_Produktbeschreibung = SQL.isleernothing(currentRow(15))
                                            PLOSE.plose_Menge = SQL.isNullNothingDbl(currentRow(16))
                                            PLOSE.plose_Preis = SQL.isNullNothingDbl(currentRow(17))
                                            PLOSE.Einheitsrabatt = SQL.isleernothing(currentRow(18))
                                            PLOSE.plose_NettobetragTransaktion = SQL.isNullNothingDbl(currentRow(19))
                                            PLOSE.plose_MWSTBetrag = SQL.isNullNothingDbl(currentRow(20))
                                            PLOSE.plose_BruttobetragTransaktion = SQL.isNullNothingDbl(currentRow(21))
                                            PLOSE.plose_NettobetragWaehrungAbbuchung = SQL.isNullNothingDbl(currentRow(22))
                                            PLOSE.plose_MWSTBetragWaehrungAbbuchung = SQL.isNullNothingDbl(currentRow(23))
                                            PLOSE.plose_BruttobetragWaehrungAbbuchung = SQL.isNullNothingDbl(currentRow(24))
                                            PLOSE.plose_WaehrungLandDiesntleistung = SQL.isleernothing(currentRow(25))
                                            PLOSE.plose_WaehrungAbbuchung = SQL.isleernothing(currentRow(26))
                                            PLOSE.plose_DokumentNrQuittungUhrzeit = SQL.isleernothing(currentRow(27))
                                            PLOSE.plose_ArtTransaktion = SQL.isleernothing(currentRow(28))
                                            PLOSE.plose_Fahrzeugklasse = SQL.isleernothing(currentRow(29))
                                            PLOSE.plose_KlassenidentifikationEURO = SQL.isleernothing(currentRow(30))
                                            PLOSE.plose_ProduktbeschreibungShort = SQL.isleernothing(currentRow(31))
                                            PLOSE.plose_DokumentNrQuittungUhrzeit = SQL.isleernothing(currentRow(32))
                                            PLOSE.plose_Geraetetyp = SQL.isleernothing(currentRow(33))
                                            PLOSE.plose_ProduktCode = SQL.isleernothing(currentRow(34))
                                            PLOSE.plose_ReferenzenBuchungMaut = SQL.isleernothing(currentRow(35))

                                            If currentRow.Length > 36 Then PLOSE.plose_SupplierRechnungsNr = SQL.isleernothing(currentRow(36))
                                            If currentRow.Length > 37 AndAlso currentRow(37).ToString.Length = 8 Then
                                                Dim datumParse = DateTime.ParseExact(currentRow(37), "yyyyMMdd", Nothing)
                                                PLOSE.plose_SupplierRechnungsDatum = datumParse
                                            End If

                                            If If(PLOSE.plose_SupplierRechnungsNr, "").contains("-SFC-") Then ' SOFICO
                                                PLOSE.plose_LieferantCode = "90"
                                                PLOSE.plose_Lieferant = SQL.DLookup("pl_Bezeichnung", "tblPLOSE_Lieferant", " [pl_LieferantCode]='" & PLOSE.plose_LieferantCode & "' ", "FMZOLL", "")
                                            End If

                                            ''''''''''''
                                            If PLOSE.SAVE() Then
                                                savedTrans += 1
                                            End If

                                            counTrans += 1

                                        End If
                                End Select

                                cnt += 1
                            End If


                            'For Each currentField In currentRow
                            'Next
                        Catch ex As Exception
                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                        End Try
                    End While


                    'Label30.Text = (cnt + 1) & " / " & LineCount
                    'Label31.Visible = True
                    readPLOSE_Detail = "Zeilen: " & cnt
                Else
                    ' MsgBox("FEHLER beim Löschen der vorhandenen OP-Liste.")
                End If
            End Using




            Try
                '  System.IO.File.Delete(p)
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            addDGVEinarbeitung("PLOSE: Detail" & KdnR, readPLOSE_Detail)


            MDMEinarb.ds_total = counTrans
            MDMEinarb.ds_count = savedTrans
            MDMEinarb.importfilename = fi.Name
            MDMEinarb.import_date = Now()

            If MDMEinarb.ds_total = MDMEinarb.ds_count Then
                MDMEinarb.completed = True
                MDMEinarb.completed_date = Now()
            End If

            MDMEinarb.SAVE()

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            readPLOSE_Detail = ""
        End Try
    End Function

    Function readPLOSE_Detail_NEW_FORMAT(d As String) As String 'neues Format der Transaktion-Files
        Try
            readPLOSE_Detail_NEW_FORMAT = ""
            Dim KdnR = ""

            Dim plose_RechnungsJahr = ""
            Dim plose_RechnungsLieferantCode = ""
            Dim plose_RechnungsNr = ""


            Dim counTrans As Integer = 0
            Dim savedTrans As Integer = 0
            Dim MDMEinarb As New cMDMEinarbeitung("PLOSE", Now(), Now())

            Dim plose_RechnungsDat = Nothing
            Dim plose_Lieferant = Nothing

            Dim fi As FileInfo = New FileInfo(d)

            Dim fileName As String = System.IO.Path.GetFileNameWithoutExtension(fi.Name)

            ' _RGDAT_... entfernen
            fileName = fileName.Split("_"c)(0)

            'File Name: {company}-{country}-{document type}-{document number}-{document year-month}-{document year-month-day}-{customercode}-{partner/reseller customer code}

            Dim parts() As String = fileName.Split("-"c)

            If parts.Length >= 8 Then
                Dim company As String = parts(0)
                Dim country As String = parts(1)
                Dim documentType As String = parts(2)
                Dim documentNumber As String = parts(3)
                Dim documentYear As String = parts(4)
                Dim documentMonth As String = parts(5)
                Dim documentDay As String = parts(6)
                Dim customerCode As String = parts(7)
                Dim partnerCustomerCode As String = parts(8)
                plose_RechnungsJahr = documentYear
                plose_RechnungsLieferantCode = company
            End If

            '--------> auslesen [tblPLOSE_Lieferant]
            Select Case plose_RechnungsLieferantCode
                Case "0" : plose_Lieferant = "PLOSE Sistem Service"
                Case "7" : plose_Lieferant = "Consortio PLOSE"
                Case "1" : plose_Lieferant = "Plose Union"
                Case "9" : plose_Lieferant = "PLOSE UNION SOCIETA COOPERATIVA"
            End Select



            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(d, Encoding.UTF8)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(";")
                Dim currentRow As String()

                Dim cnt = 0
                If True Then

                    While Not MyReader.EndOfData
                        Try

                            currentRow = MyReader.ReadFields()

                            If cnt = 0 Then
                                cnt += 1
                                Continue While ' erste Zeile überspringen
                            End If


                            If currentRow.Length < 45 Then Continue While

                            'RECHNUGNSDATUM
                            If currentRow.Length > 1 AndAlso currentRow(36).ToString.Length = 19 Then
                                Dim datumParse = DateTime.ParseExact(currentRow(36).ToString(), "dd/MM/yyyy HH:mm:ss", Globalization.CultureInfo.InvariantCulture)
                                plose_RechnungsDat = datumParse
                            End If
                            'RECHNUGNSNR
                            If currentRow.Length > 2 Then
                                plose_RechnungsNr = SQL.isleernothing(currentRow(35))
                            End If

                            If currentRow.Length > 24 AndAlso currentRow(0) <> "839160" Then 'KDNR <> VERAG --> Die Kosten bleiben uns
                                    Dim PLOSE As New MDM_Worker.cPLOSE

                                PLOSE.plose_Dateiname = fi.Name
                                PLOSE.plose_RechnungsNr = plose_RechnungsNr
                                PLOSE.plose_Lieferant = plose_Lieferant
                                PLOSE.plose_LieferantCode = plose_RechnungsLieferantCode
                                PLOSE.plose_RechnungsJahr = plose_RechnungsJahr
                                If plose_RechnungsDat IsNot Nothing Then PLOSE.plose_RechnungsDatum = plose_RechnungsDat
                                PLOSE.plose_Datensatztyp = "NEW"
                                PLOSE.plose_KodexMautTankstelle = SQL.isleernothing(currentRow(15))

                                Dim BeschreibungMaut = SQL.isleernothing(currentRow(16))
                                If BeschreibungMaut IsNot Nothing AndAlso BeschreibungMaut <> "" AndAlso BeschreibungMaut.ToString.Length > 12 Then
                                    BeschreibungMaut = BeschreibungMaut.ToString.Substring(0, 12)
                                End If

                                PLOSE.plose_BeschreibungMautTankstelle = BeschreibungMaut
                                PLOSE.plose_KodexEinfahrt = SQL.isleernothing(currentRow(17))
                                PLOSE.plose_BeschreibungEinfahrt = SQL.isleernothing(currentRow(18))
                                PLOSE.plose_KodexAusfahrt = SQL.isleernothing(currentRow(19))
                                PLOSE.plose_BeschreibungAusfahrt = SQL.isleernothing(currentRow(20))
                                PLOSE.plose_Kartenkodex = SQL.isleernothing(currentRow(8))
                                PLOSE.plose_Kontonummer = SQL.isleernothing(currentRow(7))
                                PLOSE.plose_NummerKarteGeraet = SQL.isleernothing(currentRow(12))
                                PLOSE.plose_Kennzeichen = SQL.isleernothing(currentRow(13))
                                'PLOSE.plose_InterneNrFahrzeug = SQL.isleernothing(currentRow(11))
                                PLOSE.plose_POLSEKundennummer = SQL.isleernothing(currentRow(0))
                                Dim Firmenname = SQL.isleernothing(currentRow(1))
                                If Firmenname IsNot Nothing AndAlso Firmenname <> "" AndAlso Firmenname.ToString.Length > 35 Then
                                    Firmenname = Firmenname.ToString.Substring(0, 35)
                                End If

                                PLOSE.plose_Firmenname = Firmenname
                                PLOSE.plose_DatumTransaktion = SQL.isleernothingDateFormatstring(currentRow(23))


                                Dim ProduktBeschreibung = SQL.isleernothing(currentRow(22))
                                If ProduktBeschreibung IsNot Nothing AndAlso ProduktBeschreibung <> "" AndAlso ProduktBeschreibung.ToString.Length > 15 Then
                                    ProduktBeschreibung = ProduktBeschreibung.ToString.Substring(0, 15)
                                End If
                                PLOSE.plose_Produktbeschreibung = ProduktBeschreibung

                                'PLOSE.plose_Menge = SQL.isNullNothingDbl(currentRow(24))
                                'PLOSE.plose_Preis = SQL.isNullNothingDbl(currentRow(26))

                                PLOSE.plose_Menge = CDbl(SQL.isNullReturnValue(currentRow(24), 0).replace(".", ","))
                                PLOSE.plose_Preis = CDbl(SQL.isNullReturnValue(currentRow(26), 0).replace(".", ","))

                                PLOSE.Einheitsrabatt = SQL.isleernothing(0) 'gibts nicht mehr?? in neuer Datei!
                                    PLOSE.plose_NettobetragTransaktion = CDbl(SQL.isNullReturnValue(currentRow(27), 0).replace(".", ","))
                                    PLOSE.plose_MWSTBetrag = CDbl(CDbl(SQL.isNullReturnValue(currentRow(29), 0).replace(".", ",")) - CDbl(SQL.isNullReturnValue(currentRow(27), 0).replace(".", ","))) 'selbst ausrechnen!!!
                                    PLOSE.plose_BruttobetragTransaktion = CDbl(SQL.isNullReturnValue(currentRow(29), 0).replace(".", ","))
                                    PLOSE.plose_NettobetragWaehrungAbbuchung = CDbl(SQL.isNullReturnValue(currentRow(31), 0).replace(".", ","))
                                    PLOSE.plose_MWSTBetragWaehrungAbbuchung = CDbl(CDbl(SQL.isNullReturnValue(currentRow(32), 0).replace(".", ",")) - CDbl(SQL.isNullReturnValue(currentRow(31), 0).replace(".", ","))) 'selbst ausrechnen!!!
                                    PLOSE.plose_BruttobetragWaehrungAbbuchung = CDbl(SQL.isNullReturnValue(currentRow(32), 0).replace(".", ","))
                                    PLOSE.plose_WaehrungLandDiesntleistung = SQL.isleernothing(currentRow(25))
                                    PLOSE.plose_WaehrungAbbuchung = SQL.isleernothing(currentRow(30))
                                    PLOSE.plose_ProduktCode = SQL.isleernothing(currentRow(21))
                                'PLOSE.plose_ProduktbeschreibungShort = SQL.isleernothing(currentRow(22))
                                PLOSE.plose_KlassenidentifikationEURO = SQL.isleernothing(currentRow(39))
                                PLOSE.plose_Fahrzeugklasse = SQL.isleernothing(currentRow(40))

                                'das stimmt nicht so.....
                                'PLOSE.plose_DokumentNrQuittungUhrzeit = SQL.isleernothing(currentRow(27)) '???
                                'PLOSE.plose_ArtTransaktion = SQL.isleernothing(currentRow(39))  -> Gibt nicht mehr!
                                'PLOSE.plose_Geraetetyp = SQL.isleernothing(currentRow(33)) -> Gibt nicht mehr!
                                ' PLOSE.plose_ReferenzenBuchungMaut = SQL.isleernothing(currentRow(35)) -> Gibt nicht mehr!

                                PLOSE.plose_SupplierRechnungsNr = SQL.isleernothing(currentRow(37))
                                If currentRow(38).ToString.Length = 19 Then
                                    Dim datumParse = DateTime.ParseExact(currentRow(38).ToString(), "dd/MM/yyyy HH:mm:ss", Globalization.CultureInfo.InvariantCulture)
                                    PLOSE.plose_SupplierRechnungsDatum = datumParse 'ItalianDocDate -> vom Lieferanten!
                                End If

                                If If(PLOSE.plose_SupplierRechnungsNr, "").contains("-SFC-") Then ' SOFICO
                                        PLOSE.plose_LieferantCode = "90"
                                        PLOSE.plose_Lieferant = SQL.DLookup("pl_Bezeichnung", "tblPLOSE_Lieferant", " [pl_LieferantCode]='" & PLOSE.plose_LieferantCode & "' ", "FMZOLL", "")
                                    End If

                                    ''''''''''''
                                    If PLOSE.SAVE() Then
                                        savedTrans += 1
                                    End If

                                    counTrans += 1

                                End If


                            cnt += 1



                        Catch ex As Exception
                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                        End Try
                    End While


                    'Label30.Text = (cnt + 1) & " / " & LineCount
                    'Label31.Visible = True
                    readPLOSE_Detail_NEW_FORMAT = "Zeilen: " & cnt
                Else
                    ' MsgBox("FEHLER beim Löschen der vorhandenen OP-Liste.")
                End If
            End Using




            Try
                '  System.IO.File.Delete(p)
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            addDGVEinarbeitung("PLOSE: Detail" & KdnR, readPLOSE_Detail_NEW_FORMAT)


            MDMEinarb.ds_total = counTrans
            MDMEinarb.ds_count = savedTrans
            MDMEinarb.importfilename = fi.Name
            MDMEinarb.import_date = Now()

            If MDMEinarb.ds_total = MDMEinarb.ds_count Then
                MDMEinarb.completed = True
                MDMEinarb.completed_date = Now()
            End If

            MDMEinarb.SAVE()

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            readPLOSE_Detail_NEW_FORMAT = ""
        End Try
    End Function


    Function readPLOSE_Header(d As String) As String
        Try
            Return "" ' Keine Übernahme der Daten (RgDatum) --> Falsches Format!!!




            readPLOSE_Header = ""
            Dim KdnR = ""

            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(d, Encoding.UTF8)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(";")
                Dim currentRow As String()

                Dim cnt = 0
                If True Then

                    While Not MyReader.EndOfData
                        Try
                            currentRow = MyReader.ReadFields()

                            Dim fi As FileInfo = New FileInfo(d)
                            If fi.Name.Length > 8 Then
                                Dim plose_RechnungsNr = fi.Name.Substring(0, 8)
                                If IsNumeric(plose_RechnungsNr) AndAlso IsNumeric(currentRow(12)) Then
                                    If currentRow.Length > 24 AndAlso currentRow(12) <> "839160" Then 'KDNR <> VERAG --> Die Kosten bleiben uns
                                        Dim plose_RechnungsDatum = SQL.isleernothingDateFormatstring(currentRow(14))

                                        If plose_RechnungsDatum IsNot Nothing AndAlso IsDate(plose_RechnungsDatum) Then
                                            MDM_Worker.cPLOSE.UPDATE_RGDatum(plose_RechnungsDatum, plose_RechnungsNr, currentRow(12))
                                            cnt += 1
                                        End If
                                    End If
                                End If
                            End If



                        Catch ex As Exception
                            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                        End Try
                    End While


                    'Label30.Text = (cnt + 1) & " / " & LineCount
                    'Label31.Visible = True
                    readPLOSE_Header = "Zeilen: " & cnt
                Else
                    MsgBox("FEHLER beim Löschen der vorhandenen OP-Liste.")
                End If
            End Using




            Try
                '  System.IO.File.Delete(p)
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            addDGVEinarbeitung("PLOSE: Header" & KdnR, readPLOSE_Header)

            '    End Using

            'End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            MsgBox(ex.StackTrace & ex.Message)
            readPLOSE_Header = ""
        End Try
    End Function



    Function readPLOSE_INVData(d As String) As String
        Try
            Dim cnt = 0
            readPLOSE_INVData = ""


            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(d, Encoding.UTF8)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(";")
                Dim currentRow As String()


                Dim fi As FileInfo = New FileInfo(d)

                While Not MyReader.EndOfData
                    Try
                        currentRow = MyReader.ReadFields()

                        If currentRow(0) <> "PloseCode" Then ' Header
                            If currentRow.Length >= 15 Then
                                Dim PLOSE_INV As New MDM_Worker.cPLOSE_Inv_Data
                                PLOSE_INV.plInv_SupplierRechnungsDatum = SQL.isleernothingDateFormatstring(currentRow(7))
                                PLOSE_INV.plInv_SupplierRechnungsNr = SQL.isleernothing(currentRow(8))
                                PLOSE_INV.plInv_SupplierCountry = SQL.isleernothing(currentRow(6))
                                PLOSE_INV.plInv_Lieferant = SQL.isleernothing(currentRow(4))
                                PLOSE_INV.plInv_LieferantCode = SQL.isleernothing(currentRow(3))
                                PLOSE_INV.plInv_LieferantUID = SQL.isleernothing(currentRow(5))
                                PLOSE_INV.plInv_PdfFileName = SQL.isleernothing(currentRow(14))
                                If If(PLOSE_INV.plInv_PdfFileName, "") <> "" Then
                                    If Not PLOSE_INV.plInv_PdfFileName.ToString.ToLower.EndsWith(".pdf") Then PLOSE_INV.plInv_PdfFileName += ".pdf" ' Falls Endung nciht .pdf --> anfügen
                                End If


                                If currentRow.Length >= 16 Then
                                    PLOSE_INV.plInv_Currency = SQL.isleernothing(currentRow(15))
                                End If


                                PLOSE_INV.plInv_Einlesedatum = Now.ToShortDateString
                                PLOSE_INV.plInv_Datensatztyp = "PDF"
                                PLOSE_INV.plInv_PLOSEKundennummer = SQL.isleernothing(currentRow(0))
                                PLOSE_INV.plInv_Firmenname = SQL.isleernothing(currentRow(1))
                                '                                    PLOSE_INV.plInv_DatumTransaktion = SQL.isleernothing(currentRow(0))
                                '                                   PLOSE_INV.plInv_Produktbeschreibung = SQL.isleernothing(currentRow(0))
                                PLOSE_INV.plInv_Services = SQL.isleernothing(currentRow(13))

                                PLOSE_INV.plInv_Nettobetrag = CDbl(CDbl(SQL.isNullReturnValue(currentRow(9), 0).replace(".", ",")) + CDbl(SQL.isNullReturnValue(currentRow(11), 0).replace(".", ",")))
                                PLOSE_INV.plInv_MWSTBetrag = CDbl(SQL.isNullReturnValue(currentRow(10), 0).replace(".", ","))
                                PLOSE_INV.plInv_Bruttobetrag = CDbl(SQL.isNullReturnValue(currentRow(12), 0).replace(".", ","))

                                ' [plInv_daId]  

                                'If If(PLOSE_INV.plInv_PdfFileName, "") <> "" Then 'And PLOSE_INV.plInv_daId Is Nothing Then
                                '    PLOSE_INV.plInv_daId = SQL.getValueTxtBySql("SELECT TOP (1) [da_id]  FROM [tblDatenarchiv]  where da_kategorie = 'MDM' AND da_ordner='MDM_DATEN' and da_name='" & PLOSE_INV.plInv_PdfFileName & "' order by da_id desc", "FMZOLL",,, Nothing)
                                'End If


                                PLOSE_INV.plInv_Dateiname = fi.Name

                                ''''''''''''
                                If PLOSE_INV.SAVEUNQIUE() Then

                                    ' UPDATE tblPLOSE_Details:
                                    SQL.doSQL("UPDATE [tblPLOSE_Details] SET [plose_plInvId] ='" & PLOSE_INV.plInv_Id & "'  where plose_SupplierRechnungsNr='" & PLOSE_INV.plInv_SupplierRechnungsNr & "' AND plose_SupplierRechnungsDatum='" & PLOSE_INV.plInv_SupplierRechnungsDatum & "'", "FMZOLL")
                                End If

                            End If
                        End If

                        cnt += 1

                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                    End Try
                End While


                readPLOSE_INVData = "Zeilen: " & cnt

            End Using




            Try
                '  System.IO.File.Delete(p)
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            addDGVEinarbeitung("PLOSE: INV_DATA (" & cnt & ")", readPLOSE_INVData)

            '    End Using

            'End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            MsgBox(ex.StackTrace & ex.Message)
            readPLOSE_INVData = ""
        End Try
    End Function

    Function readPLOSE_INVData_NEW_FORMAT(d As String) As String
        Try
            Dim cnt = 0
            readPLOSE_INVData_NEW_FORMAT = ""


            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(d, Encoding.UTF8)
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters(";")
                Dim currentRow As String()


                Dim fi As FileInfo = New FileInfo(d)

                Dim fileName As String = System.IO.Path.GetFileNameWithoutExtension(fi.Name)

                'Alles ab "_RGDAT_" entfernen
                fileName = fileName.Split("_"c)(0)

                Dim parts() As String = fileName.Split("-"c)

                If parts.Length >= 10 Then
                    Dim company As String = parts(0)
                    Dim documentType As String = parts(1)            'rdoc
                    Dim documentNumber As String = parts(2)
                    Dim documentYearMonth As String = parts(3) & "-" & parts(4)
                    Dim documentYearMonthDay As String = parts(5) & "-" & parts(6) & "-" & parts(7)
                    Dim customerCode As String = parts(8)
                    Dim partnerCustomerCode As String = parts(9)

                End If


                While Not MyReader.EndOfData
                    Try
                        currentRow = MyReader.ReadFields()


                        If cnt = 0 Then
                            cnt += 1
                            Continue While ' erste Zeile überspringen
                        End If

                        If currentRow.Length >= 28 Then
                            Dim PLOSE_INV As New MDM_Worker.cPLOSE_Inv_Data
                            PLOSE_INV.plInv_SupplierRechnungsDatum = SQL.isleernothingDateFormatstring(currentRow(8))
                            PLOSE_INV.plInv_SupplierRechnungsNr = SQL.isleernothing(currentRow(9))
                            PLOSE_INV.plInv_SupplierCountry = SQL.isleernothing(currentRow(7))
                            PLOSE_INV.plInv_Lieferant = SQL.isleernothing(currentRow(5))
                            PLOSE_INV.plInv_LieferantCode = SQL.isleernothing(currentRow(3))
                            PLOSE_INV.plInv_LieferantUID = SQL.isleernothing(currentRow(6))
                            PLOSE_INV.plInv_PdfFileName = SQL.isleernothing(currentRow(22))
                            If If(PLOSE_INV.plInv_PdfFileName, "") <> "" Then
                                If Not PLOSE_INV.plInv_PdfFileName.ToString.ToLower.EndsWith(".pdf") Then PLOSE_INV.plInv_PdfFileName += ".pdf" ' Falls Endung nciht .pdf --> anfügen
                            End If

                            Dim origCurrency = SQL.isleernothing(currentRow(11))


                            PLOSE_INV.plInv_Einlesedatum = Now.ToShortDateString
                            PLOSE_INV.plInv_Datensatztyp = "PDF"
                            PLOSE_INV.plInv_PLOSEKundennummer = SQL.isleernothing(currentRow(0))
                            PLOSE_INV.plInv_Firmenname = SQL.isleernothing(currentRow(1))
                            PLOSE_INV.plInv_Services = SQL.isleernothing(currentRow(21))

                            Select Case origCurrency 'HUF immer in Fremdwährung abpeichern...
                                Case "HUF"
                                    PLOSE_INV.plInv_Currency = "HUF"
                                    PLOSE_INV.plInv_Nettobetrag = CDbl(CDbl(SQL.isNullReturnValue(currentRow(12), 0).replace(".", ",")))
                                    PLOSE_INV.plInv_MWSTBetrag = CDbl(SQL.isNullReturnValue(currentRow(13), 0).replace(".", ","))
                                    PLOSE_INV.plInv_Bruttobetrag = CDbl(SQL.isNullReturnValue(currentRow(15), 0).replace(".", ","))

                                Case Else
                                    PLOSE_INV.plInv_Currency = "EUR"
                                    PLOSE_INV.plInv_Nettobetrag = CDbl(CDbl(SQL.isNullReturnValue(currentRow(16), 0).replace(".", ",")))
                                    PLOSE_INV.plInv_MWSTBetrag = CDbl(SQL.isNullReturnValue(currentRow(17), 0).replace(".", ","))
                                    PLOSE_INV.plInv_Bruttobetrag = CDbl(SQL.isNullReturnValue(currentRow(19), 0).replace(".", ","))
                            End Select



                            ' [plInv_daId]  

                            'If If(PLOSE_INV.plInv_PdfFileName, "") <> "" Then 'And PLOSE_INV.plInv_daId Is Nothing Then
                            '    PLOSE_INV.plInv_daId = SQL.getValueTxtBySql("SELECT TOP (1) [da_id]  FROM [tblDatenarchiv]  where da_kategorie = 'MDM' AND da_ordner='MDM_DATEN' and da_name='" & PLOSE_INV.plInv_PdfFileName & "' order by da_id desc", "FMZOLL",,, Nothing)
                            'End If


                            PLOSE_INV.plInv_Dateiname = fi.Name

                            ''''''''''''
                            If PLOSE_INV.SAVEUNQIUE() Then

                                ' UPDATE tblPLOSE_Details:
                                SQL.doSQL("UPDATE [tblPLOSE_Details] SET [plose_plInvId] ='" & PLOSE_INV.plInv_Id & "'  where plose_SupplierRechnungsNr='" & PLOSE_INV.plInv_SupplierRechnungsNr & "' AND plose_SupplierRechnungsDatum='" & PLOSE_INV.plInv_SupplierRechnungsDatum & "'", "FMZOLL")
                            End If

                        End If


                        cnt += 1

                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                    End Try
                End While


                readPLOSE_INVData_NEW_FORMAT = "Zeilen: " & cnt

            End Using




            Try
                '  System.IO.File.Delete(p)
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            addDGVEinarbeitung("PLOSE: INV_DATA (" & cnt & ")", readPLOSE_INVData_NEW_FORMAT)

            '    End Using

            'End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            MsgBox(ex.StackTrace & ex.Message)
            readPLOSE_INVData_NEW_FORMAT = ""
        End Try
    End Function





    Private Sub dgvEinarbeitung_SelectionChanged(sender As Object, e As EventArgs) Handles dgvEinarbeitung.SelectionChanged
        dgvEinarbeitung.ClearSelection()

    End Sub






    Private Sub frmTCNachrichtenVerarbeitung_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If allowClose Then
            Me.Refresh()

            Button2.PerformClick()
            Button1.PerformClick()

            System.Threading.Thread.Sleep(2000)

            Me.Close()
        End If
    End Sub

    Private Sub pnl_Paint(sender As Object, e As PaintEventArgs) Handles pnl.Paint

    End Sub
End Class

