' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
Imports System.IO
Imports System.Xml
Imports System.Net.Sockets
Imports System.Text
Imports System

Public Class ConstitutionLots


    Private OCT_TypeDestinataire As String = "CP" 'G12C6
    Private Type_émetteur_fichier As String = "TP" 'TP Professionnel de Santé hors établissement, TE Etablissement ou Centre de Soin, SI Autre : Société Civile Professionnelle ou Société Civile de Moyens

    Private Structure facture
        Dim NumFacture As String
        Dim file As String
        Dim CRL As String
        Dim traitée As Boolean
        Dim à_traiter As Boolean
        Dim BaseRemboursement As Integer
        Dim MontantAMO As Integer
        Dim MontantAMC As Integer
        Dim Datef As String
        Dim CodeRégime As String
        Dim CaisseGestionnaire As String
        Dim CentreGestionnaire As String
        Dim NomPrénom As String
    End Structure
    Private FacturesTab() As facture
    Private Structure Lot
        Dim CRL As String
        Dim NbreFactures As Integer
        Dim Total As Double
        Dim Organisme As String
        Dim Constitution As Boolean
    End Structure
    Private LotsTab() As Lot

    Private Sub ConstitutionLots_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        LoadFactures()
        LoadLots()
        Affiche_Lots_à_constituer()
        Afficher_lots_à_transmettre()
    End Sub

    Private Sub LoadFactures()
        ReDim FacturesTab(0)
        Dim file As String = Dir("c:\factures\*.fse")
        Dim compteurfactures As Integer = 0
        Do Until file = ""
            ReDim Preserve FacturesTab(FacturesTab.Length)
            FacturesTab(compteurfactures).file = file
            FacturesTab(compteurfactures).traitée = False
            FacturesTab(compteurfactures).à_traiter = True
            FacturesTab(compteurfactures).CRL = Mid(file, 1, 40)
            file = Mid(file, InStr(file, "@") + 1)
            FacturesTab(compteurfactures).NumFacture = Val(Mid(file, 1, InStr(file, "@") - 1)).ToString
            FacturesTab(compteurfactures).CodeRégime = Mid(FacturesTab(compteurfactures).CRL, InStr(FacturesTab(compteurfactures).CRL, "PH") + 2, 2)
            FacturesTab(compteurfactures).CaisseGestionnaire = Mid(FacturesTab(compteurfactures).CRL, InStr(FacturesTab(compteurfactures).CRL, "PH") + 4, 3)
            FacturesTab(compteurfactures).CentreGestionnaire = Me.FacturesTableAdapter1.SelectCentreGestionnairebyNumFacture(FacturesTab(compteurfactures).NumFacture)
            FacturesTab(compteurfactures).BaseRemboursement = Me.Facture_LigneFactureTableAdapter1.SelectSUMBaseRemboursementByNumFacture(FacturesTab(compteurfactures).NumFacture)
            FacturesTab(compteurfactures).MontantAMO = Me.Facture_LigneFactureTableAdapter1.SelectSUMMontantAMOByNumFacture(FacturesTab(compteurfactures).NumFacture)
            FacturesTab(compteurfactures).MontantAMC = Me.Facture_LigneFactureTableAdapter1.SelectSUMMonstantAMCByNumFacture(FacturesTab(compteurfactures).NumFacture)
            FacturesTab(compteurfactures).Datef = Me.FacturesTableAdapter1.SelectDatebyNum(FacturesTab(compteurfactures).NumFacture)
            Dim IdBenef As String = Me.FacturesTableAdapter1.SelectIdBenef(FacturesTab(compteurfactures).NumFacture)
            Dim G101C8, G101C9, G104C12, G104C13, G104C14 As String
            G101C8 = Mid(IdBenef, 1, InStr(IdBenef, "@/@/@") - 1)
            IdBenef = Mid(IdBenef, InStr(IdBenef, "@/@/@") + 5)
            G101C9 = Mid(IdBenef, 1, InStr(IdBenef, "@/@/@") - 1)
            IdBenef = Mid(IdBenef, InStr(IdBenef, "@/@/@") + 5)
            G104C12 = Mid(IdBenef, 1, InStr(IdBenef, "@/@/@") - 1)
            IdBenef = Mid(IdBenef, InStr(IdBenef, "@/@/@") + 5)
            G104C13 = Mid(IdBenef, 1, InStr(IdBenef, "@/@/@") - 1)
            IdBenef = Mid(IdBenef, InStr(IdBenef, "@/@/@") + 5)
            G104C14 = IdBenef
            FacturesTab(compteurfactures).NomPrénom = Me.VitaleTableAdapter1.SelectNomPrénom(G101C8, G101C9, G104C12, G104C13, G104C14)
            file = Dir()
            compteurfactures = compteurfactures + 1
        Loop
        ReDim Preserve FacturesTab(FacturesTab.Length - 2)
    End Sub
    Private Sub LoadLots()
        ReDim LotsTab(0)
        For i = 0 To FacturesTab.Length - 1
            If FacturesTab(i).à_traiter = True Then
                Dim Found As Boolean = False
                For j = 0 To LotsTab.Length - 1
                    If FacturesTab(i).CRL = LotsTab(j).CRL Then 'si il y a déja une ligne créée dans LotsTab poue ce CRL
                        Found = True
                        LotsTab(j).NbreFactures = LotsTab(j).NbreFactures + 1
                        LotsTab(j).Total = LotsTab(j).Total + FacturesTab(i).MontantAMO + FacturesTab(i).MontantAMC
                    End If
                    If Found = False Then 'si il n'y a pas déja une ligne créée dans LotsTab poue ce CRL
                        ReDim Preserve LotsTab(j + 1)
                        LotsTab(j).CRL = FacturesTab(i).CRL
                        LotsTab(j).Constitution = True
                        LotsTab(j).NbreFactures = 1
                        LotsTab(j).Total = FacturesTab(i).MontantAMO + FacturesTab(i).MontantAMC
                        For k = 0 To taborgdest.Length - 1
                            If (FacturesTab(i).CodeRégime = taborgdest(k).Coderégime) And (FacturesTab(i).CaisseGestionnaire = taborgdest(k).CaisseGestionnaire) And (FacturesTab(i).CentreGestionnaire = taborgdest(k).CentreGestionnaire) Then
                                LotsTab(j).Organisme = taborgdest(k).Intitulé
                            End If
                        Next

                    End If
                Next
            End If
        Next
    End Sub

    Private Sub Affiche_Lots_à_constituer()
        LotDataGridView.Rows.Clear()
        Dim j = 0
        For i = 0 To LotsTab.Length - 2
            LotDataGridView.Rows.Add()
            If LotsTab(i).Constitution = False Then
                LotDataGridView(Constitution.Index, j).Value = False
            Else
                LotDataGridView(Constitution.Index, j).Value = True
            End If
            LotDataGridView(Organisme.Index, j).Value = LotsTab(i).Organisme
            LotDataGridView(FacturesNombre.Index, j).Value = LotsTab(i).NbreFactures
            LotDataGridView(Total.Index, j).Value = (LotsTab(i).Total / 100).ToString + "€"
            LotDataGridView(CRL.Index, j).Value = LotsTab(i).CRL
            j = j + 1
        Next
    End Sub
    Private Sub Affiche_Factures(ByVal CRL As String, ByVal Organisme As String)
        Label1.Text = Organisme + " (détail)"
        FacturesDataGridView.Rows.Clear()
        Dim j = 0
        For i = 0 To FacturesTab.Length - 1
            If FacturesTab(i).CRL = CRL Then
                FacturesDataGridView.Rows.Add()
                If FacturesTab(i).à_traiter = False Then
                    FacturesDataGridView(à_traiter.Index, j).Value = False
                Else
                    FacturesDataGridView(à_traiter.Index, j).Value = True
                End If
                FacturesDataGridView(NumFacture.Index, j).Value = FacturesTab(i).NumFacture
                FacturesDataGridView(NomPrénom.Index, j).Value = FacturesTab(i).NomPrénom
                FacturesDataGridView(Datef.Index, j).Value = Mid(FacturesTab(i).Datef, 7, 2) + "/" + Mid(FacturesTab(i).Datef, 5, 2) + "/" + Mid(FacturesTab(i).Datef, 1, 4)
                FacturesDataGridView(BaseRemboursement.Index, j).Value = FacturesTab(i).BaseRemboursement / 100
                FacturesDataGridView(MontantAMO.Index, j).Value = FacturesTab(i).MontantAMO / 100
                FacturesDataGridView(MontantAMC.Index, j).Value = FacturesTab(i).MontantAMC / 100
                j = j + 1
            End If
        Next

    End Sub
    Private Sub Afficher_lots_à_transmettre()
        LotàTransmettreDataGridView.Rows.Clear()
        LotàTransmettreDataGridView.AutoGenerateColumns = False
        Dim fichierlot As String = Dir("C:\Factures\Lots\*.lotFSE")
        Dim RéférenceLot As String
        Dim nombrelots As Integer = 0
        Do Until fichierlot = ""
            LotàTransmettreDataGridView.Rows.Add()
            RéférenceLot = Mid(fichierlot, 1, InStr(fichierlot, ".lotFSE") - 1)
            Dim myDataTable As DataTable
            myDataTable = Me.LotsTableAdapter.GetDataByRéférence(Val(RéférenceLot))
            For c = 0 To myDataTable.Columns.Count - 1
                Select Case myDataTable.Columns.Item(c).ColumnName
                    ' Référence, CRL, CRL, Date, NombreDeFSE, Taille, Montant, Organisme, FichierLots 
                    Case "Référence"
                        LotàTransmettreDataGridView(Référence.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "Organisme"
                        LotàTransmettreDataGridView(Organismet.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "Montant"
                        LotàTransmettreDataGridView(Montant.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "NombreDeFSE"
                        LotàTransmettreDataGridView(NombreDeFSE.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "Date"
                        LotàTransmettreDataGridView(Datet.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "Taille"
                        LotàTransmettreDataGridView(Taille.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "CRL"
                        LotàTransmettreDataGridView(CRLt.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    Case "CRF"
                        LotàTransmettreDataGridView(CRF.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                End Select
            Next
            nombrelots = nombrelots + 1
            fichierlot = Dir()
        Loop
    End Sub

    Private Sub LotDataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles LotDataGridView.CellContentClick

        Select Case LotDataGridView.CurrentCellAddress.X

            Case Détail.Index
                Affiche_Factures(LotDataGridView(CRL.Index, LotDataGridView.CurrentRow.Index).Value, LotDataGridView(Organisme.Index, LotDataGridView.CurrentRow.Index).Value)

            Case Constitution.Index
                If LotsTab(LotDataGridView.CurrentCellAddress.Y).Constitution = True Then
                    LotsTab(LotDataGridView.CurrentCellAddress.Y).Constitution = False
                Else
                    LotsTab(LotDataGridView.CurrentCellAddress.Y).Constitution = True

                End If
        End Select

    End Sub

    Private Sub FacturesDataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles FacturesDataGridView.CellContentClick

        Select Case FacturesDataGridView.CurrentCellAddress.X

            Case à_traiter.Index
                If FacturesTab(FacturesDataGridView.CurrentCellAddress.Y).à_traiter = True Then
                    FacturesTab(FacturesDataGridView.CurrentCellAddress.Y).à_traiter = False
                Else
                    FacturesTab(FacturesDataGridView.CurrentCellAddress.Y).à_traiter = True
                End If
                LoadLots()
                Affiche_Lots_à_constituer()

            Case EditionFacture.Index

        End Select
    End Sub

    'Constitution Lots
    Private Sub ConstitutionLotsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConstitutionLotsButton.Click
        For i = 0 To LotsTab.Length - 2
            If LotsTab(i).Constitution = True Then


                SGD_ReserverSession(10000000, NumeroSessionLot)

                'Groupe7
                SGD_AjouterGroupe(NumeroSessionLot, 7)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "", "7")

                'Champ1
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 9, ValeurChamp, 8)
                SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")

                'Champ2
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 10, ValeurChamp, 1)
                SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")

                'Groupe8
                SGD_AjouterGroupe(NumeroSessionLot, 8)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "", "8")

                'Champ1
                SGD_AjouterChamp(NumeroSessionLot, "TESTCNDA1407")
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "TESTCNDA1407", "")

                'Champ2
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 9, ValeurChamp, 8)
                SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")

                'Champ3
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 10, ValeurChamp, 1)
                SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")

                'Champ4
                ValeurChamp = "1234567890123456789012345678901234567890"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 8, ValeurChamp, 40)
                SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")

                'Champ5
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 1, ValeurChamp, 1)
                SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")

                'Champ6
                SGD_AjouterChamp(NumeroSessionLot, "TP") 'Professionnel de Santé hors établissement
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "TP", "")

                'Champ7
                Dim numemetteur As String
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 9, ValeurChamp, 8)
                numemetteur = ValeurChamp
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 10, ValeurChamp, 1)
                numemetteur = "00000" + numemetteur + ValeurChamp
                SGD_AjouterChamp(NumeroSessionLot, numemetteur)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", numemetteur, "")

                'Champ8
                Dim datelot As String = Format(Now, "yyyyMMdd") + "0000"
                SGD_AjouterChamp(NumeroSessionLot, datelot)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", datelot, "")

                'Champ9
                SGD_AjouterChamp(NumeroSessionLot, "7") 'Lot unique à formater
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "7", "")

                'champ10
                Dim RéférenceLotFSE As Integer = Me.LotsTableAdapter.SelectMaxRéférence + 1
                SGD_AjouterChamp(NumeroSessionLot, RéférenceLotFSE.ToString)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", RéférenceLotFSE.ToString, "")

                'champ11
                SGD_AjouterChamp(NumeroSessionLot, LotsTab(i).NbreFactures.ToString)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", LotsTab(i).NbreFactures.ToString, "")

                'champ12,13,14
                ValeurChamp = "XXXXXXXXXXXXXX"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 6, ValeurChamp, 14)
                If ValeurChamp <> "XXXXXXXXXXXXXX" Then
                    ValeurChamp = "X"
                    SGD_LireChamp(NumeroSessionCPS, 2, 1, 5, ValeurChamp, 1)
                    SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")
                    ValeurChamp = "XXXXXXXXXXXXXX"
                    SGD_LireChamp(NumeroSessionCPS, 2, 1, 6, ValeurChamp, 14)
                    SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")
                    ValeurChamp = "X"
                    SGD_LireChamp(NumeroSessionCPS, 2, 1, 7, ValeurChamp, 1)
                    SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")
                Else
                    SGD_AjouterChamp(NumeroSessionLot, "9")
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "9", "")
                    SGD_AjouterChamp(NumeroSessionLot, "9")
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "9", "")
                    ValeurChamp = "X"
                    SGD_LireChamp(1, 2, 1, 10, ValeurChamp, 1)
                    SGD_AjouterChamp(NumeroSessionLot, ValeurChamp)
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", ValeurChamp, "")
                End If

                'groupe6
                SGD_AjouterGroupe(NumeroSessionLot, 6)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "", "6")
                SGD_AjouterChamp(NumeroSessionLot, LotsTab(i).CRL)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", LotsTab(i).CRL, "")

                'groupe9
                SGD_AjouterGroupe(NumeroSessionLot, 9)
                For j = 0 To FacturesTab.Length - 1
                    If FacturesTab(j).CRL = LotsTab(i).CRL And FacturesTab(j).traitée = False And FacturesTab(j).à_traiter = True Then
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes("c:\factures\" + FacturesTab(j).file)
                        My.Computer.FileSystem.WriteAllBytes("c:\factures\lots\temp", bytes, True)
                        FacturesTab(j).traitée = True
                        'deplacement fichier FSE apres traitement
                        My.Computer.FileSystem.MoveFile("c:\factures\" + FacturesTab(j).file, "C:\Factures\Traitées\" + FacturesTab(j).file)
                        If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Lot_in.txt", "fichier facture " + FacturesTab(j).file, "")
                    End If
                Next
                SGD_AjouterChampFichier(NumeroSessionLot, "c:\factures\lots\temp")
                My.Computer.FileSystem.DeleteFile("c:\factures\lots\temp")


                '____________________________________________________________________________________________________

                'SIS_FormaterLot
                Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, "", NumeroSessionLot)
                If out <> 0 Then
                    MsgBox("erreur constitution lot " + LotsTab(i).Organisme + Chr(10) + out.ToString)
                    Exit Sub
                End If

                '____________________________________________________________________________________________________
                'Visu_API agrement CNDA
                If Visu_API = True Then
                    Technique_MAIN.LireSession_Out_VersFichier(NumeroSessionLot, "Formater_Lot_out.txt")
                End If
                '____________________________________________________________________________________________________
                'enregistrement lot dans bdd
                Dim CRF As String = "123456789012345678901234567890"
                SGD_LireChamp(NumeroSessionLot, 10, 1, 1, CRF, 30)
                Dim TailleLot = 0
                SGD_LireChampBin(NumeroSessionLot, 11, 1, 1, ValeurChamp, TailleLot)
                Dim G13C1 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 1, G13C1, 1)
                If G13C1 = "@" Then G13C1 = ""
                Dim G13C2 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 2, G13C2, 1)
                If G13C2 = "@" Then G13C2 = ""
                Dim G13C3 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 3, G13C3, 14)
                If G13C3 = "@@@@@@@@@@@@@@" Then G13C3 = ""
                Dim G13C4 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 4, G13C4, 14)
                If G13C4 = "@@@@@@@@@@@@@@" Then G13C4 = ""
                Dim G13C5 As String = "@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 5, G13C5, 3)
                If G13C5 = "@@@" Then G13C5 = ""
                Dim G13C6 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 6, G13C6, 1)
                If G13C6 = "@" Then G13C6 = ""
                Dim G13C7 As String = "@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 7, G13C7, 8)
                If G13C7 = "@@@@@@@@" Then G13C7 = ""
                Dim G93C1 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 1, G93C1, 14)
                If G93C1 = "@@@@@@@@@@@@@@" Then G93C1 = ""
                Dim G93C2 As String = "@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 2, G93C2, 10)
                If G93C2 = "@@@@@@@@@@" Then G93C2 = ""
                Dim G93C3 As String = "@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 3, G93C3, 3)
                If G93C3 = "@@@" Then G93C3 = ""
                Dim G93C4 As String = "@@@@@@@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 4, G93C4, 20)
                If G93C4 = "@@@@@@@@@@@@@@@@@@@@" Then G93C4 = ""
                Dim G93C5 As String = "@@@@@@@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 5, G93C5, 1)
                If G93C5 = "@@@@@@@@@@@@@@@@@@@@" Then G93C5 = ""
                Dim G93C6 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 6, G93C6, 8)
                If G93C6 = "@" Then G93C6 = ""
                Dim G93C7 As String = "@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 7, G93C7, 8)
                If G93C7 = "@@@@@@@@" Then G93C7 = ""
                Me.LotsTableAdapter.Insert1(RéférenceLotFSE, LotsTab(i).CRL, CRF, datelot, LotsTab(i).NbreFactures, LotsTab(i).Total, TailleLot, LotsTab(i).Organisme, G13C1, G13C2, G13C3, G13C4, G13C5, G13C6, G13C7, G93C1, G93C2, G93C3, G93C4, G93C5, G93C6, G93C7, "A TRANSMETTRE")
                'enregistrement lot dans fichier
                SGD_LireChampFichier(NumeroSessionLot, 11, 1, 1, "C:\Factures\Lots\" + RéférenceLotFSE.ToString + ".lotFSE")
                SGD_LireChampFichier(NumeroSessionLot, 91, 1, 1, "C:\Factures\Lots\" + RéférenceLotFSE.ToString + ".lotDRE")
            End If
        Next

        LoadFactures()
        LoadLots()
        Affiche_Lots_à_constituer()
        FacturesDataGridView.Rows.Clear()
        Afficher_lots_à_transmettre()
    End Sub

    Private Sub FormaterFichiers()

        Dim NombreTotalLotsDansFichier As Integer = 0
        Dim LongueurTotaleLotsDansFichier As Integer = 0
        Dim NombreTotalFacturessDansFichier As Integer = 0
        Dim fichierlot As String
        Dim lots_traités(LotàTransmettreDataGridView.RowCount) As Boolean

        For i = 0 To LotàTransmettreDataGridView.RowCount - 1
            If LotàTransmettreDataGridView(Transmission.Index, i).Value = True And lots_traités(i) = False Then
                For j = i To LotàTransmettreDataGridView.RowCount - 1
                    If LotàTransmettreDataGridView(Transmission.Index, j).Value = True And lots_traités(j) = False And LotàTransmettreDataGridView(CRF.Index, i).Value = LotàTransmettreDataGridView(CRF.Index, j).Value Then
                        NombreTotalLotsDansFichier = NombreTotalLotsDansFichier + 1
                        LongueurTotaleLotsDansFichier = LongueurTotaleLotsDansFichier + Val(LotàTransmettreDataGridView(Taille.Index, j).Value)
                        NombreTotalFacturessDansFichier = NombreTotalFacturessDansFichier + Val(LotàTransmettreDataGridView(NombreDeFSE.Index, j).Value)
                    End If
                Next


                SGD_ReserverSession(10000000, NumeroSessionFichier)
                'groupe10
                SGD_AjouterGroupe(NumeroSessionFichier, 10)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "", "10")
                'champ1
                SGD_AjouterChamp(NumeroSessionFichier, LotàTransmettreDataGridView(CRF.Index, i).Value)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "LotàTransmettreDataGridView(CRF.Index, i).Value", "")

                'groupe12
                SGD_AjouterGroupe(NumeroSessionFichier, 12)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "", "12")
                'champ1
                Dim DateFichier As String = Format(Now, "yyyyMMdd") + "0000"
                SGD_AjouterChamp(NumeroSessionFichier, DateFichier)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", DateFichier, "")
                'champ2
                Dim NomFichier As String
                NomFichier = (Val(Me.FichiersSVTableAdapter1.SelectMaxNomFichier) + 1).ToString
                SGD_AjouterChamp(NumeroSessionFichier, NomFichier)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", NomFichier, "")
                'champ3
                SGD_AjouterChamp(NumeroSessionFichier, NombreTotalLotsDansFichier.ToString)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", NombreTotalLotsDansFichier.ToString, "")
                'champ4
                SGD_AjouterChamp(NumeroSessionFichier, LongueurTotaleLotsDansFichier.ToString)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", LongueurTotaleLotsDansFichier.ToString, "")
                'champ5
                If OCT = True Then
                    SGD_AjouterChamp(NumeroSessionFichier, "TO")
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "TO", "")
                Else
                    SGD_AjouterChamp(NumeroSessionFichier, "TR")
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "TR", "")
                End If
                'champ6
                If OCT = True Then
                    SGD_AjouterChamp(NumeroSessionFichier, OCT_TypeDestinataire)
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", OCT_TypeDestinataire, "")
                Else
                    SGD_AjouterChamp(NumeroSessionFichier, "")
                    If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "", "")
                End If
                'champ7
                Dim CodeRégimeFichier As String
                Dim CodeOrgDestFichier As String
                Dim NumDestinataire As String
                Dim CodeCentreInfo As String = "000"
                CodeRégimeFichier = Mid(LotàTransmettreDataGridView(CRF.Index, i).Value, InStr(LotàTransmettreDataGridView(CRF.Index, i).Value, "PH") - 2, 2)
                CodeOrgDestFichier = Mid(LotàTransmettreDataGridView(CRF.Index, i).Value, InStr(LotàTransmettreDataGridView(CRF.Index, i).Value, "PH") + 2, 3)
                For j = 0 To taborgdest.Length - 1
                    If CodeRégimeFichier = taborgdest(j).Coderégime And CodeOrgDestFichier = taborgdest(j).Codeorganismedestinataire Then
                        CodeCentreInfo = taborgdest(j).CodeCentreInformatique
                    End If
                Next
                NumDestinataire = "000000" + CodeRégimeFichier + CodeCentreInfo + CodeOrgDestFichier
                SGD_AjouterChamp(NumeroSessionFichier, NumDestinataire)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", NumDestinataire, "")

                'groupe14
                SGD_AjouterGroupe(NumeroSessionFichier, 14)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "", "14")
                'champ1
                SGD_AjouterChamp(NumeroSessionFichier, Type_émetteur_fichier)
                'champ2
                Dim numemetteur As String
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 9, ValeurChamp, 8).ToString()
                numemetteur = ValeurChamp
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, 1, 10, ValeurChamp, 1)
                numemetteur = "00000" + numemetteur + ValeurChamp
                SGD_AjouterChamp(NumeroSessionFichier, numemetteur)
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", numemetteur, "")
                'champ3
                SGD_AjouterChamp(NumeroSessionFichier, "")
                If Visu_API = True Then Technique_MAIN.LireSession_In_VersFichier(NumeroSessionLot, "Formater_Fichier_in.txt", "", "")



       
                '____________________________________________________________________________________________________

                'formaterfichier
                Dim out As Integer = SIS_FormaterFichier(NumeroSessionFichier)
                If out <> 0 Then
                    MsgBox("Erreur de Formatage du fichier pour les lots avec" + Chr(10) + "CRF=" + LotàTransmettreDataGridView(CRF.Index, i).Value + Chr(10) + "ERREUR N°:" + out.ToString)
                    Exit Sub
                End If

                '____________________________________________________________________________________________________

                'Visu_API agrement CNDA
                If Visu_API = True Then
                    Technique_MAIN.LireSession_Out_VersFichier(NumeroSessionFichier, "Formater_Fichier_out.txt")
                End If
                '____________________________________________________________________________________________________

                'création fichier  à envoyer
                Dim fichierFSE As String = "C:\Factures\Fichiers\" + NomFichier + ".fichierFSE"
                Dim fictemp As String = "C:\Factures\Fichiers\temp.txt"
                Dim bytes() As Byte
                'En-tête de fichier de FSE
                ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
                TailleMax = 128
                SGD_LireChampFichier(NumeroSessionFichier, 20, 1, 1, fichierFSE)
                SGD_LireChamp(NumeroSessionFichier, 20, 1, 1, ValeurChamp, TailleMax)

                'ecrit les Lot de FSE dans le fichier 
                For j = i To LotàTransmettreDataGridView.RowCount - 1
                    If LotàTransmettreDataGridView(Transmission.Index, j).Value = True And lots_traités(j) = False And LotàTransmettreDataGridView(CRF.Index, i).Value = LotàTransmettreDataGridView(CRF.Index, j).Value Then
                        fichierlot = LotàTransmettreDataGridView(Référence.Index, j).Value.ToString + ".lotFSE"
                        bytes = My.Computer.FileSystem.ReadAllBytes("C:\Factures\Lots\" + fichierlot)
                        My.Computer.FileSystem.WriteAllBytes(fichierFSE, bytes, True)
                        Me.LotsTableAdapter.Update_Fichier(fichierFSE, Val(LotàTransmettreDataGridView(Référence.Index, j).Value)) 'update nom de fichier dans lequel est mis le lot
                        Me.LotsTableAdapter.Update_Etat("ATTENTE ARL", Val(LotàTransmettreDataGridView(Référence.Index, j).Value)) 'update état
                        My.Computer.FileSystem.MoveFile("C:\Factures\Lots\" + fichierlot, "C:\Factures\Lots\transmis\" + fichierlot)
                        lots_traités(j) = True
                    End If
                Next

                'Fin de fichier de FSE
                ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
                TailleMax = 128
                SGD_LireChampFichier(NumeroSessionFichier, 21, 1, 1, fictemp)
                bytes = My.Computer.FileSystem.ReadAllBytes(fictemp)
                My.Computer.FileSystem.WriteAllBytes(fichierFSE, bytes, True)
                My.Computer.FileSystem.DeleteFile(fictemp)
                SGD_LireChamp(NumeroSessionFichier, 21, 1, 1, ValeurChamp, TailleMax)

                'enregistre info fichier dans bdd
                Me.FichiersSVTableAdapter1.Insert(Val(NomFichier), LotàTransmettreDataGridView(CRF.Index, i).Value, DateFichier, LongueurTotaleLotsDansFichier, NombreTotalLotsDansFichier, NombreTotalFacturessDansFichier)

            End If
        Next
    End Sub

    Private Sub SendMail()
        Dim fichieràtransmettre As String

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("RepertoireFichiers")
        Dim chemin As String = XMLelementliste.Item(0).InnerText
        fichieràtransmettre = Dir(chemin + "*.fichierFSE")
        If fichieràtransmettre = "" Then
            MsgBox("PAS DE FICHIER A TRANSMETTRE", MsgBoxStyle.Information)
            Exit Sub
        End If
        Using swtrace As New StreamWriter(Format(Now, "yyyyMMdd") + "TraceMail.txt", True) 'TRACE
            Do
                Dim fichiermail As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1) + ".mail"
                Using sw As New StreamWriter(chemin + fichiermail, True)
                    sw.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                    XMLelementliste = ConfigXml.GetElementsByTagName("From")
                    sw.WriteLine("From: " + XMLelementliste.Item(0).InnerText)
                    If TracerCheckBox.Checked = True Then swtrace.WriteLine("From: " + XMLelementliste.Item(0).InnerText) 'TRACE

                    Dim CNDAXml As New XmlDocument 'forçage adresse CNDA 
                    CNDAXml.Load("CNDA.xml")
                    Dim CNDAXmlelementliste As XmlNodeList 'forçage adresse CNDA 
                    CNDAXmlelementliste = CNDAXml.GetElementsByTagName("Adr_CNDA") 'forçage adresse CNDA 
                    If CNDAXmlelementliste.Item(0).InnerText = "oui" Then 'forçage adresse CNDA 
                        Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).CRF 'forçage adresse CNDA 
                        Dim pos As Integer = InStr(CRF, "PH") 'forçage adresse CNDA 
                        sw.WriteLine("To:" + Mid(CRF, pos - 2, 2) + "349@349." + Mid(CRF, pos - 2, 2) + ".rss.fr") 'forçage adresse CNDA 
                        If TracerCheckBox.Checked = True Then swtrace.WriteLine("To:" + Mid(CRF, pos - 2, 2) + "349@349." + Mid(CRF, pos - 2, 2) + ".rss.fr") 'TRACE
                    Else
                        Select Case OCT
                            Case True
                                XMLelementliste = ConfigXml.GetElementsByTagName("AdressemailOCT")
                                sw.WriteLine("To: " + XMLelementliste.Item(0).InnerText)
                                If TracerCheckBox.Checked = True Then swtrace.WriteLine("To: " + XMLelementliste.Item(0).InnerText) 'TRACE
                            Case False
                                Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).CRF
                                Dim pos As Integer = InStr(CRF, "PH")
                                sw.WriteLine("To:" + Mid(CRF, pos - 2, 2) + Mid(CRF, pos + 2, 3) + "@" + Mid(CRF, pos + 2, 3) + "." + Mid(CRF, pos - 2, 2) + ".rss.fr")
                                If TracerCheckBox.Checked = True Then swtrace.WriteLine("To:" + Mid(CRF, pos - 2, 2) + Mid(CRF, pos + 2, 3) + "@" + Mid(CRF, pos + 2, 3) + "." + Mid(CRF, pos - 2, 2) + ".rss.fr") 'TRACE

                        End Select
                    End If
                    XMLelementliste = ConfigXml.GetElementsByTagName("Message-ID")
                    sw.WriteLine("Message-ID: <" + XMLelementliste.Item(0).InnerText + " " + fichieràtransmettre + ">")
                    Dim numemetteur As String
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, 1, 9, ValeurChamp, 8)
                    numemetteur = ValeurChamp
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, 1, 10, ValeurChamp, 1)
                    numemetteur = "00000" + numemetteur + ValeurChamp
                    Dim compteur As Integer = SmtpTableAdapter1.SelectMaxCompteur + 1

                    Dim compteurstring As String = compteur.ToString
                    While compteurstring.Length < 5
                        compteurstring = "0" + compteurstring
                    End While
                    Dim NombreFactures As Integer = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).NombresFactures
                    Dim NombreFacturesstring As String = NombreFactures.ToString
                    While NombreFacturesstring.Length < 5
                        NombreFacturesstring = "0" + NombreFacturesstring
                    End While
                    sw.WriteLine("Subject: SV140401/" + numemetteur + "/" + Format(Now, "yyyyMMddhhmmss") + compteurstring + "/" + NombreFacturesstring)
                    Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, "SV140401/" + numemetteur + "/" + Format(Now, "yyyyMMddhhmmss") + compteurstring + "/" + NombreFacturesstring)
                    If TracerCheckBox.Checked = True Then swtrace.WriteLine("Subject: SV140401/" + numemetteur + "/" + Format(Now, "yyyyMMddhhmmss") + compteurstring + "/" + NombreFacturesstring) 'TRACE
                    sw.WriteLine("MIME-Version: 1.0")
                    sw.WriteLine("Content-Type: Application/EDI-consent")
                    If TracerCheckBox.Checked = True Then swtrace.WriteLine("Content-Type: Application/EDI-consent") 'TRACE
                    sw.WriteLine("Content-Transfer-Encoding: base64")
                    Select Case ModeFonctionnement
                        Case "Test"
                            sw.WriteLine("Content-Description: FSETEST/B2")
                            If TracerCheckBox.Checked = True Then swtrace.WriteLine("Content-Description: FSETEST/B2") 'TRACE
                        Case "Réel"
                            sw.WriteLine("Content-Description: FSE/B2")
                            If TracerCheckBox.Checked = True Then swtrace.WriteLine("Content-Description: FSE/B2") 'TRACE
                        Case "Demonstration"
                            sw.WriteLine("Content-Description: FSE/B2")
                            If TracerCheckBox.Checked = True Then swtrace.WriteLine("Content-Description: FSE/B2") 'TRACE
                    End Select
                    sw.WriteLine()
                End Using
                Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre)
                Dim base64String As String
                base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                My.Computer.FileSystem.WriteAllText(chemin + fichiermail, base64String, True)
                Using sw As New StreamWriter(chemin + fichiermail, True)
                    sw.WriteLine()
                    sw.WriteLine()
                End Using
                My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre)
                XMLelementliste = ConfigXml.GetElementsByTagName("RepertoirePickup")
                'My.Computer.FileSystem.MoveFile(chemin + fichiermail, XMLelementliste.Item(0).InnerText + fichiermail)
                My.Computer.FileSystem.MoveFile(chemin + fichiermail, "c:\" + fichiermail)
                '____________________________________________________________________________________________________
                'TRACE
                Dim stringtace As String
                If TracerCheckBox.Checked = True Then
                    Dim datatableLots = Me.LotsTableAdapter.GetDataByFichierLots(fichieràtransmettre)
                    For r = 0 To datatableLots.Rows.Count - 1
                        stringtace = ""
                        For c = 0 To datatableLots.Columns.Count - 1
                            Select Case datatableLots.Columns.Item(c).ColumnName
                                Case "Référence"
                                    stringtace = stringtace + "Référence lot:" + datatableLots(r).Item(c).ToString
                                Case "Date"
                                    stringtace = stringtace + "Date lot:" + datatableLots(r).Item(c).ToString
                            End Select
                        Next
                        swtrace.WriteLine(stringtace)
                    Next
                End If
                stringtace = Nothing
                '____________________________________________________________________________________________________

                fichieràtransmettre = Dir(chemin + "*.fichierFSE")


            Loop Until fichieràtransmettre = ""

        End Using
    End Sub

    Private Sub tempo(ByVal minute As Double)
        LabelReception.Text = "TEMPORISATION EN COURS AVANT RECEPTION RETOURS NOEMI"
        LabelReception.Visible = True
        Me.Refresh()

        'temporisation
        Dim mydate = Now
        While Now < DateAdd(DateInterval.Minute, minute, mydate)
            LabelReception.Text = "TEMPORISATION EN COURS AVANT RECEPTION RETOURS NOEMI, " + DateDiff(DateInterval.Second, Now, DateAdd(DateInterval.Minute, minute, mydate)).ToString + " SECONDES"
            Me.Refresh()
        End While
    End Sub

    Private Sub Getmail()

        Try
            Dim Server As TcpClient
            Dim NetStrm As System.Net.Sockets.NetworkStream
            Dim RdStrm As System.IO.StreamReader
            Dim Data As String
            Dim szData As Byte()

            Dim ConfigXml As New XmlDocument
            ConfigXml.Load("config.xml")
            Dim nodeliste As XmlNodeList
            nodeliste = ConfigXml.GetElementsByTagName("Pop3")
            Dim Serveur As String = nodeliste.Item(0).Item("Serveur").InnerText
            Dim Port As Integer = Val(nodeliste.Item(0).Item("Port").InnerText)
            Dim User As String = nodeliste.Item(0).Item("User").InnerText
            Dim Password As String = nodeliste.Item(0).Item("Password").InnerText





            'create server POP3 with port 110
            LabelReception.Text = "CONNECTION"
            Server = New TcpClient(Serveur, Port)
            NetStrm = Server.GetStream()
            RdStrm = New StreamReader(NetStrm)
            RichTextBox1.Visible = True
            RichTextBox1.AppendText(RdStrm.ReadLine() + vbCrLf)
            RichTextBox1.AppendText("connected:" + Server.Connected.ToString + vbCrLf)


            'Login Process
            LabelReception.Text = "LOGIN"
            Data = "USER " + User & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            RichTextBox1.AppendText(RdStrm.ReadLine + vbCrLf)
            Data = "PASS " + Password & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            RichTextBox1.AppendText(RdStrm.ReadLine + vbCrLf)


            'Send STAT command to get information ie: number of mail
            LabelReception.Text = "STAT"
            Data = "STAT" & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            Data = RdStrm.ReadLine
            RichTextBox1.AppendText(Data + vbCrLf)
            Dim NumberOfMail As Integer = Val(Trim(Mid(Data, 5, 2)))
            RichTextBox1.AppendText("Nombre de Message:" + NumberOfMail.ToString + vbCrLf)


            ''retrieve mail with number mail parameter
            'LabelReception.Text = "NumberOfMail:" + NumberOfMail.ToString
            'If NumberOfMail <> 0 Then
            '    For i = 1 To NumberOfMail
            '        RichTextBox1.AppendText("_________________________________________________" + vbCrLf)
            '        RichTextBox1.AppendText("Message " + i.ToString + vbCrLf)
            '        Data = "retr " + i.ToString & vbCrLf
            '        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            '        NetStrm.Write(szData, 0, szData.Length)
            '        Dim line As String = RdStrm.ReadLine
            '        'While line <> "" And line <> "."
            '        While line <> "."
            '            RichTextBox1.AppendText(line + vbCrLf)
            '            line = RdStrm.ReadLine
            '        End While
            '        RichTextBox1.AppendText("_________________________________________________" + vbCrLf)
            '    Next
            'End If

            'download mail with number mail parameter

            If NumberOfMail <> 0 Then

                For i = 1 To NumberOfMail
                    LabelReception.Text = "Telechargement message " + i.ToString
                    Dim MessageId As String = ""
                    Dim InReplyTo As String = ""
                    Dim Subject As String = ""
                    Dim From_ As String = ""
                    Dim Content_Description As String = ""
                    Dim FichierPieceJointe As Integer
                    Data = "retr " + i.ToString & vbCrLf
                    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                    NetStrm.Write(szData, 0, szData.Length)
                    Dim line As String = RdStrm.ReadLine

                    While line <> "."

                        If InStr(line, "Message-Id:") = 1 Then
                            MessageId = Trim(Mid(line, "Message-Id:".Length + 1))
                        End If

                        If InStr(line, "In-Reply-To:") = 1 Then
                            InReplyTo = Trim(Mid(line, "In-Reply-To:".Length + 1))
                        End If

                        If InStr(line, "Subject:") = 1 Then
                            Subject = Trim(Mid(line, "Subject:".Length + 1))
                        End If

                        If InStr(line, "From:") = 1 Then
                            From_ = Trim(Mid(line, "From:".Length + 1))
                        End If

                        If InStr(line, "Content-Description:") = 1 Then
                            Content_Description = Trim(Mid(line, "Content-Description:".Length + 1))
                            While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                line = RdStrm.ReadLine
                            End While

                            'sauvegarde pièce jointe dans fichier
                            FichierPieceJointe = Me.ARLTableAdapter.SelectMaxFichierPieceJointe + 1
                            line = RdStrm.ReadLine 'debut pièce jointe
                            While line <> ""
                                My.Computer.FileSystem.WriteAllText("C:\Factures\ARL\" + FichierPieceJointe.ToString + ".arl", line, True)
                                line = RdStrm.ReadLine
                            End While

                        End If
                        line = RdStrm.ReadLine
                    End While

                    'sauvegarde données ARL dans bdd
                    Me.ARLTableAdapter.Insert1(MessageId, InReplyTo, Subject, From_, FichierPieceJointe, Content_Description, "", "", "", "", "", "", "", "", "", "")

                    'suppression message
                    LabelReception.Text = "SUPPRESSION MESSAGE " + i.ToString
                    Data = "DELE " + i.ToString & vbCrLf
                    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                    NetStrm.Write(szData, 0, szData.Length)
                    RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                Next

            End If

            'Send QUIT command to close session from POP server
            LabelReception.Text = "DECONNECTION"
            Data = "QUIT" & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            RichTextBox1.AppendText("SESSION FERMEE" & vbCrLf)

        Catch ex As Exception
            MsgBox(ex.ToString)
            LabelReception.Visible = False
        End Try

    End Sub

    Private Sub TransmettreButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransmettreButton.Click
        FormaterFichiers()
        SendMail()
        Afficher_lots_à_transmettre()
        tempo(0)
        Getmail()
        'MsgBox("stop")
        Dim FichierARL As String = Dir("C:\Factures\ARL\*.arl")
        While FichierARL <> ""
            'MsgBox(FichierARL)
            Traitement_ARL(FichierARL, NumeroSessionARL)
            FichierARL = Dir("C:\Factures\ARL\*.arl")
        End While
    End Sub

    Private Sub ConstitutionLots_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        MENU_PRINCIPAL.Enabled = True
    End Sub

    Private Sub Traitement_ARL(ByVal FichierARL As String, ByVal NumeroSession As Integer)
        SGD_ReserverSession(10000, NumeroSession)
        SGD_AjouterGroupe(NumeroSession, 30)
        Dim arlbase64 As String = My.Computer.FileSystem.ReadAllText("C:\Factures\ARL\" + FichierARL)
        Dim bytes As Byte() = Convert.FromBase64String(arlbase64)
        Dim arl = System.Text.Encoding.UTF8.GetString(bytes)
        SGD_AjouterChamp(NumeroSession, arl)
        SIS_TraduireARL(NumeroSession)
        ValeurChamp = "123456789012"
        Dim i = 1
        While SGD_LireChamp(NumeroSession, 31, i, 2, ValeurChamp, 12) = 0
            'MsgBox(i.ToString)
            Dim G31C1 As String = "@@@"
            Dim G31C2 As String = "@@@@@@@@@@@@"
            Dim G31C3 As String = "@"
            Dim G31C4 As String = "@@@@@@@@@@@@@@"
            Dim G31C5 As String = "@@@@@@@@@@@@@@"
            Dim G31C6 As String = "@@@"
            Dim G31C7 As String = "@@@@@@@@@@@@"
            Dim G31C8 As String = "@"
            Dim G31C9 As String = "@@@@@@@@@@"
            Dim G31C10 As String = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            SGD_LireChamp(NumeroSession, 31, i, 1, G31C1, 3)
            SGD_LireChamp(NumeroSession, 31, i, 2, G31C2, 12)
            SGD_LireChamp(NumeroSession, 31, i, 3, G31C3, 1)
            SGD_LireChamp(NumeroSession, 31, i, 4, G31C4, 14)
            SGD_LireChamp(NumeroSession, 31, i, 5, G31C5, 14)
            SGD_LireChamp(NumeroSession, 31, i, 6, G31C6, 3)
            SGD_LireChamp(NumeroSession, 31, i, 7, G31C7, 12)
            SGD_LireChamp(NumeroSession, 31, i, 8, G31C8, 1)
            SGD_LireChamp(NumeroSession, 31, i, 9, G31C9, 10)
            SGD_LireChamp(NumeroSession, 31, i, 10, G31C10, 80)
            'MsgBox(G31C1)
            'MsgBox(G31C2)
            'MsgBox(G31C3)
            'MsgBox(G31C4)
            'MsgBox(G31C5)
            'MsgBox(G31C6)
            'MsgBox(G31C7)
            'MsgBox(G31C8)
            'MsgBox(G31C9)
            'MsgBox(G31C10)
            Me.LotsTableAdapter.Update_ARL("ARL RECU", G31C1, G31C2, G31C3, G31C4, G31C5, G31C6, G31C7, G31C8, G31C9, G31C10, Val(G31C6))
            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + Val(G31C6).ToString + ".lotFSE", "C:\Factures\Lots\traités\" + Val(G31C6).ToString + ".lotFSE")
            i = i + 1
        End While
        My.Computer.FileSystem.MoveFile("C:\Factures\ARL\" + FichierARL, "C:\Factures\ARL\Traités\" + FichierARL) '
    End Sub


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Traitement_ARL("C:\Factures\ARL\13.arl", NumeroSessionARL)

    End Sub
End Class