' 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.Xml
Imports System.IO
Imports System.IO.Compression


Public Class ScanOrdo
    Declare Function TWAIN_EasyVersion Lib "EZTW32.DLL" Alias "TWAIN_EasyVersion" () As Long
    Declare Function TWAIN_AcquireToClipboard Lib "EZTW32.DLL" (ByVal hwndApp&, ByVal wPixTypes&) As Long
    Declare Function Twain_IsAvailable Lib "EZTW32.DLL" Alias "Twain_IsAvailable" () As Long
    Declare Function TWAIN_SetHideUI Lib "Eztw32.dll" Alias "TWAIN_SetHideUI" (ByVal ui As Long) As Long
    Declare Function TWAIN_OpenDefaultSource Lib "Eztw32.DLL" Alias "TWAIN_OpenDefaultSource" (ByVal hwnd As Long) As Integer
    Declare Function TWAIN_SetCurrentResolution Lib "Eztw32.dll" Alias "TWAIN_SetCurrentResolution" (ByVal neufdix As Double) As Long
    Declare Function TWAIN_SetCurrentPixelType Lib "Eztw32.dll" Alias "TWAIN_SetCurrentPixelType" (ByVal deux As Long) As Long ' Scan format 0 = B&W, 1 Grey, 2 RGB
    Declare Function TWAIN_LoadSourceManager Lib "Eztw32.dll" Alias "TWAIN_LoadSourceManager" () As Long
    Declare Function TWAIN_SetCurrentUnits Lib "Eztw32.dll" Alias "TWAIN_SetCurrentUnits" (ByVal zero As Long) As Long ' DPI
    Declare Function TWAIN_SetBitDepth Lib "Eztw32.dll" Alias "TWAIN_SetBitDepth" (ByVal zero As Long) As Long ' Bit Depth 1, 2, 4, 8 but depends on Pixeltype
    Declare Function TWAIN_OpenSourceManager Lib "EZTW32.DLL" Alias "TWAIN_OpenSourceManager" (ByVal hwnd As Long) As Long
    Declare Function TWAIN_CloseSource Lib "EZTW32.DLL" Alias "TWAIN_CloseSource" () As Long
    Declare Function TWAIN_SelectImageSource Lib "EZTW32.DLL" Alias "TWAIN_SelectImageSource" (ByVal hwnd As Long) As Long
    Declare Function TWAIN_State Lib "EZTW32.DLL" Alias "TWAIN_State" () As Long

    Declare Function TWAIN_AcquireToFilename Lib "Eztwain3.dll" (ByVal hwndApp As Long, ByVal sFile As String) As Long
    Declare Function TWAIN_SelectFeeder Lib "EZTW32.DLL" (ByVal fYes As Long) As Long
    Declare Function TWAIN_SetCurrentResolution Lib "EZTW32.DLL" (ByVal nRes As Long) As Long

    Declare Function TWAIN_LogFile Lib "EZTW32.DLL" (ByVal fLog As Long) As Long
    Declare Function TWAIN_SetAutoScan Lib "EZTW32.DLL" (ByVal fYes As Long) As Long
    Declare Function TWAIN_SetRegion Lib "EZTW32.DLL" (ByVal L As Double, ByVal T As Double, ByVal R As Double, ByVal B As Double) As Long

    Declare Function TWAIN_AcquireMultipageFile Lib "EZTW32.DLL" (ByVal hwndApp As Long, ByVal FileName As String) As Long
    Declare Function TWAIN_LastErrorCode Lib "EZTW32.DLL" () As Long
    Declare Function TWAIN_ReportLastError Lib "EZTW32.DLL" (ByVal pzMsg As String) As Long

    Declare Function TWAIN_GetCurrentResolution Lib "EZTW32.DLL" () As Long



    Public Alter_Mode_Fonctionement As String

    Public Sub scan(ByVal TWAIN_SetHideUI As Long)
        'TWAIN_SetHideUI=1 to hide 0 to show

        Dim r As Long

        Try
            r = ScanOrdo.TWAIN_OpenDefaultSource(Me.Handle.ToInt32)
        Catch ex As Exception
            r = ScanOrdo.TWAIN_SelectImageSource(0)
        End Try

        r = ScanOrdo.TWAIN_SetHideUI(TWAIN_SetHideUI)

        'r = ScanOrdo.TWAIN_SelectImageSource(Me.Handle.ToInt32)


        'Dim res As Double = 75
        'r = ScanOrdo.TWAIN_SetCurrentResolution(CDbl(res))
        'Dim TypDoc As Long = 1
        'TypDoc = 0  'Noir et Blanc
        'TypDoc = 1  'Nuance de gris
        'TypDoc = 2  'Couleur
        'r = ScanOrdo.TWAIN_SetCurrentPixelType(CLng(TypDoc))
        r = ScanOrdo.TWAIN_AcquireToClipboard(Me.Handle.ToInt32, 0)
        PictureBox1.Image = Clipboard.GetDataObject.GetData(DataFormats.Bitmap)
        PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage

    End Sub

    Private Sub PictureBoxScanOrdo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBoxScanOrdo.Click
        Warning_Label.Text = ""
        Warning_Label.Visible = False
        Validate_Button.Visible = True
        If Config.typedriverscan = "TWAIN" Then
            scan(0)
        Else
            If Not WIA_GetDevices() Is Nothing Then
                PictureBox1.Image = WIA_scan(WIA_GetDevices(0), True)
            End If
        End If

    End Sub

    Private Sub Validate_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Validate_Button.Click

        If Alter_Mode_Fonctionement Is Nothing Then
            Alter_Mode_Fonctionement = ""
        End If



        If A10_1_ListBox.SelectedItem Is Nothing Then
            MyMsg_Box.Presentation("Officine !", "CHOISIR TYPE DOCUMENT", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        'PostScript file
        PrintDocument_Bitmap.PrinterSettings.PrinterName = "Postscript"
        If My.Computer.FileSystem.FileExists(Application.StartupPath + "\GS\scantemp.ps") Then
            My.Computer.FileSystem.DeleteFile(Application.StartupPath + "\GS\scantemp.ps")
        End If
        PrintDocument_Bitmap.PrinterSettings.PrintFileName = Application.StartupPath + "\GS\scantemp.ps"
        PrintDocument_Bitmap.PrinterSettings.PrintToFile = True
        PrintDocument_Bitmap.Print()
        '--------------------------------------------------
        Dim FileName = ""
        Dim compteur As Integer = 1

        If Alter_Mode_Fonctionement = "" Or Alter_Mode_Fonctionement = "debile" Then
            If CurrentFactureVitale.G1110C1 = "" Then
                FileName = "PreScan" & Config.Idposte
            Else
                FileName = CurrentFactureVitale.G1110C1
            End If
            'compteur
            While Dir(Config.LocalNetwork_ServerName & "\scor\doc\" + FileName + "_" + compteur.ToString + "*.pdf") <> ""
                compteur = compteur + 1
            End While
            FileName = FileName + "_" + compteur.ToString
            'A10-1 Nature de pièces justificatives
            FileName = FileName + "_" + Mid(A10_1_ListBox.SelectedItem.ToString, InStrRev(A10_1_ListBox.SelectedItem.ToString, " ") + 1)




        ElseIf Alter_Mode_Fonctionement = "Chronique" Then
            FileName = Mid(A10_1_ListBox.SelectedItem.ToString, InStrRev(A10_1_ListBox.SelectedItem.ToString, " ") + 1) & Format(Now, "yyyyMMddHHmmssfff")
        End If

            'convert Postscript to pdf
            FileName = FileName + ".pdf"
            'convert PostScript to PDF
            Teletransmission_MAIN.ShellandWait(Application.StartupPath + "\GS", "gswin32c.exe", "-sDEVICE=pdfwrite -o " + FileName + " scantemp.ps") '-dPDFSETTINGS=/screen -sPAPERSIZE=a4
            '--------------------------------------------------
            'controle taille pdf
            If My.Computer.FileSystem.GetFileInfo(Application.StartupPath + "\GS\" + FileName).Length > 250000 Then
                Warning_Label.Visible = True
                Validate_Button.Visible = False
                Warning_Label.Text = "La taille du document numérisé" & Chr(10) & "est trop grande (" + My.Computer.FileSystem.GetFileInfo(Application.StartupPath + "\GS\" + FileName).Length.ToString + _
                       " octets)" & Chr(10) & ",le document n'est pas conservé." + Chr(10) + "reduire taille/qualité." + Chr(10) + "(Taille Maximum 250 Ko)"
                My.Computer.FileSystem.DeleteFile(Application.StartupPath + "\GS\" + FileName)
                Exit Sub
            End If
            '--------------------------------------------------
        'move PDF file
        If Alter_Mode_Fonctionement = "" Or Alter_Mode_Fonctionement = "debile" Then


            Dim new_file_name As String
            Select Case Mode_Trans_ComboBox.Text
                Case "papier", "cd-rom"
                    new_file_name = Config.LocalNetwork_ServerName & "\scor\doc\" + Mode_Trans_ComboBox.Text + "\" + FileName

                Case Else
                    new_file_name = Config.LocalNetwork_ServerName & "\scor\doc\" + FileName
            End Select
            My.Computer.FileSystem.MoveFile(Application.StartupPath + "\GS\" + FileName, new_file_name, True)
            Dim VenteForm_WebBrowser_SCOR_file As String = Application.StartupPath + "\temp\VenteForm_WebBrowser_SCOR" + Format(Now, "yyyyMMddHHmmssfff") + ".pdf"
            My.Computer.FileSystem.CopyFile(new_file_name, VenteForm_WebBrowser_SCOR_file, True)
            If Config.Scor_hide_VenteForm_WebBrowser_SCOR = False Then
                VenteForm.WebBrowser_SCOR.Visible = True
                VenteForm.WebBrowser_SCOR.Navigate(VenteForm_WebBrowser_SCOR_file)
            End If
            '--------------------------------------------------  

            'save to Bdd
            While Me.SCOR_PJTableAdapter.GetDataBy_Fichier(FileName).Rows.Count = 0
                If CurrentFactureVitale.G1110C1 <> "" Then
                    Me.SCOR_PJTableAdapter.Insert(FileName, ID_PJ(compteur.ToString, Mid(A10_1_ListBox.SelectedItem.ToString, InStrRev(A10_1_ListBox.SelectedItem.ToString, " ") + 1)), "A FINALISER", CurrentFactureVitale.G1110C1)
                Else
                    Me.SCOR_PJTableAdapter.Insert(FileName, ID_PJ(compteur.ToString, Mid(A10_1_ListBox.SelectedItem.ToString, InStrRev(A10_1_ListBox.SelectedItem.ToString, " ") + 1)), "A FINALISER", "PreScan" & Config.Idposte)
                End If
                System.Threading.Thread.Sleep(1000)
            End While
            VenteForm.ListBox_scanordo.Items.Add(FileName)

            'TT02.01 Préparer le fichier d'index ScanOrdo
            If CurrentFactureVitale.G1110C1 <> "" Then
                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\index\" & CurrentFactureVitale.G1110C1 & ".xml") = False Then
                    TT02()
                End If
            End If
        ElseIf Alter_Mode_Fonctionement = "Chronique" Then
            MyInptBox.my_showdialog("Nombre de délivrances prévues ?" & vbCrLf & vbCrLf & "délivrance initiale + renouvellements", VarType(New Integer), 2, "1")
            Dim nombre_delivrance = CInt(MyInptBox.result)
            Dim IdOrdo = BDD.OrdoTableAdapter.SelectMax_Idordo + 1
            Dim type As String
            If COMPTOIR_MAIN.SCOR_Location_CheckBox.Checked Then
                type = "LOCATION"
            Else
                type = "MEDICAMENT"
            End If
            Dim prescrID = ""
            Try
                prescrID = CurrentBenéficiaire.Prescripteur_ID
            Catch ex As Exception

            End Try
            facilEpharm.OrdoTableAdapter.Insert(IdOrdo, Now, Now, prescrID, "", "", "", "", "", "", "", "", CurrentBenéficiaire.Num, nombre_delivrance, DatePrescr_DateTimePicker.Value, type)
            facilEpharm.Ordo_FichiersTableAdapter.Insert(IdOrdo, FileName, "")
            My.Computer.FileSystem.MoveFile(Application.StartupPath + "\GS\" + FileName, Config.LocalNetwork_ServerName & "\scor\Ordo\" & FileName, True)
            ' BDD.ChroniqueTableAdapter.Update_IdOrdo_By_VitaleNum(IdOrdo, CurrentBenéficiaire.Num)
        End If






        Me.Close()
    End Sub

    Private Sub PrintDocument_Bitmap_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument_Bitmap.PrintPage
        Try

     
        Dim i = PictureBox1.Image

        'i.HorizontalResolution = pixels per inch of the image 
        'i.VerticalResoulutin = ppi of image again 
        'e.MarginBounds.Width = printable width in 100 ppi 
        'e.MarginBounds.Height = printable height in 100 ppi 

        Dim newWidth As Decimal = i.Width * 100 / i.HorizontalResolution 'Convert to same units (100 ppi) as e.MarginBounds.Width 
        Dim newHeight As Decimal = i.Height * 100 / i.VerticalResolution 'Convert to same units (100 ppi) as e.MarginBounds.Height 
        Dim widthFactor As Decimal = newWidth / e.MarginBounds.Width
        Dim heightFactor As Decimal = newHeight / e.MarginBounds.Height


        If (widthFactor > 1 Or heightFactor > 1) Then ' if the image is wider or taller than the printable area then adjust... 
            If (widthFactor > heightFactor) Then
                newWidth = newWidth / widthFactor
                newHeight = newHeight / widthFactor
            Else
                newWidth = newWidth / heightFactor
                newHeight = newHeight / heightFactor

            End If
            e.Graphics.DrawImage(i, 0, 0, Int(newWidth), Int(newHeight))
        Else
            e.Graphics.DrawImage(i, 0, 0)
        End If
            'e.Graphics.DrawImage(PictureBox1.Image, 0, 0)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ScanOrdo_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Warning_Label.Text = ""
        If Alter_Mode_Fonctionement = "Chronique" Then
            DatePrescr_DateTimePicker.Visible = True
            DatePrescr_Label.Visible = True
        Else
            DatePrescr_DateTimePicker.Visible = False
            DatePrescr_Label.Visible = False
        End If
        If CurrentFactureVitale.G1110C1 = "" Then
            Me.Text = "Scan Ordo"
        Else
            Me.Text = "Scan Ordo     Facture SV n°" + CurrentFactureVitale.G1110C1
        End If
        If Alter_Mode_Fonctionement <> "debile" Then
            If Config.typedriverscan = "TWAIN" Then
                scan(0)
            Else
                If Not WIA_GetDevices() Is Nothing Then
                    PictureBox1.Image = WIA_scan(WIA_GetDevices(0), SCOR_show_scanner_interface)
                Else
                    Me.Close()
                End If
            End If
        End If

    End Sub
    Public Sub Rename_PreScaned_Docs()

        VenteForm.ListBox_scanordo.Items.Clear()
        If CurrentFactureVitale.G1110C1 <> "" Then
            Dim PreScanFile = Dir(Config.LocalNetwork_ServerName & "\scor\doc\PreScan" & Config.Idposte & "*")
            Dim NumOdre As Integer = 1
            While PreScanFile <> ""
                'Dim PreScanFilerenamed = Replace(PreScanFile, "PreScan" & Config.Idposte, CurrentFactureVitale.G1110C1)
                'PreScanFilerenamed = Mid(PreScanFilerenamed, 1, InStr(PreScanFilerenamed, "_")) & NumOdre.ToString & Mid(PreScanFilerenamed, InStrRev(PreScanFilerenamed, "_"))
                Dim PreScanFilerenamed = CurrentFactureVitale.G1110C1 & "_" & NumOdre.ToString & Mid(PreScanFile, InStrRev(PreScanFile, "_"))
                My.Computer.FileSystem.RenameFile(Config.LocalNetwork_ServerName & "\scor\doc\" & PreScanFile, PreScanFilerenamed)
                'My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\scor\doc\" & PreScanFilerenamed, Config.LocalNetwork_ServerName & "\scor\doc\" & PreScanFilerenamed, True)
                Dim numordrestrg = NumOdre.ToString

                While numordrestrg.Length < 9
                    numordrestrg = "0" & numordrestrg
                End While

                Dim oldID = Me.SCOR_PJTableAdapter.GetDataBy_Fichier(PreScanFile).Item(0).ID
                oldID = Mid(oldID, 2)
                Dim NewID As String = ""
                If CurrentFactureVitale.G1211C1 <> "" Then
                    NewID = CurrentFactureVitale.G1211C1 + "." + Mid(oldID, 1, InStr(oldID, ".")) + CurrentFactureVitale.G1120C1 + "." + CurrentFactureVitale.G1310C1 + CurrentFactureVitale.G1310C2 + CurrentFactureVitale.G1310C3 _
                                                 + "." + Format(Now, "yyyyMMddHHmmss") + "." + numordrestrg
                ElseIf CurrentFactureVitale.G1213C1 <> "" Then
                    NewID = CurrentFactureVitale.G1213C1 + "." + Mid(oldID, 1, InStr(oldID, ".")) + CurrentFactureVitale.G1120C1 + "." + CurrentFactureVitale.G1310C1 + CurrentFactureVitale.G1310C2 + CurrentFactureVitale.G1310C3 _
                                           + "." + Format(Now, "yyyyMMddHHmmss") + "." + numordrestrg
                Else
                    NewID = CurrentFactureVitale.G1214C1 + "." + Mid(oldID, 1, InStr(oldID, ".")) + CurrentFactureVitale.G1120C1 + "." + CurrentFactureVitale.G1310C1 + CurrentFactureVitale.G1310C2 + CurrentFactureVitale.G1310C3 _
                                                   + "." + Format(Now, "yyyyMMddHHmmss") + "." + numordrestrg
                End If


                Me.SCOR_PJTableAdapter.UpdatePresScan(CurrentFactureVitale.G1110C1, PreScanFilerenamed, NewID, PreScanFile)

                VenteForm.ListBox_scanordo.Items.Add(PreScanFilerenamed)
                NumOdre = NumOdre + 1
                PreScanFile = Dir()
            End While
            If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\index\" & CurrentFactureVitale.G1110C1 & ".xml") = False Then
                TT02()
            End If
        Else
            Dim PreScanFile = Dir(Config.LocalNetwork_ServerName & "\scor\doc\*PreScan" & Config.Idposte & "*")
            While PreScanFile <> ""
                VenteForm.ListBox_scanordo.Items.Add(PreScanFile)
                PreScanFile = Dir()
            End While
        End If
    End Sub



    Public Function ID_PJ(ByVal compteur As String, ByVal Type_pièce As String) As String
        '[RG_TT057]
        Dim out As String
        If InStr(Type_pièce, "ORD") <> 0 Then
            If CurrentFactureVitale.G1211C1 <> "" Then
                out = CurrentFactureVitale.G1211C1 + "." + Type_pièce
            ElseIf CurrentFactureVitale.G1213C1 <> "" Then
                out = CurrentFactureVitale.G1213C1 + "." + Type_pièce
            Else
                out = CurrentFactureVitale.G1214C1 + "." + Type_pièce
            End If
        Else
            out = CurrentFactureVitale.G1120C1 + "." + Type_pièce
        End If

        '--------------------------------------------------
        'N° de facturation de PS émetteur de la PJ + Code_régime_Code_caisse_gestionnaire_Code_centre_gestionnaire
        out = out + "." + CurrentFactureVitale.G1120C1 + "." + CurrentFactureVitale.G1310C1 + CurrentFactureVitale.G1310C2 + CurrentFactureVitale.G1310C3
        '--------------------------------------------------
        'Date_constitution_PJ (AAAAMMJJHHMMSS)
        out = out + "." + Format(Now, "yyyyMMddHHmmss")
        '--------------------------------------------------
        'Compteur
        While compteur.Length < 9
            compteur = "0" + compteur
        End While
        out = out + "." + compteur

        Return out

    End Function

    Public Sub TT02()
        'TT02.01 Préparer le fichier d'index ScanOrdo
        'xml file:Instance_SCANORDO_V02_03
        Dim My_Xml_Doc As New XmlDocument
        My_Xml_Doc.Load(Config.LocalNetwork_ServerName & "\scor\XML\Instance_SCANORDO.xml")
        Dim XMLelementliste As XmlNodeList

        XMLelementliste = My_Xml_Doc.GetElementsByTagName("SCANORDO")
        XMLelementliste.Item(0).Item("Identifiant").InnerText = "" 'Ce champ sera renseigné lors de la mise en lot des justificatifs
        XMLelementliste.Item(0).Item("Temps").InnerText = Format(Now, "yyyy-MM-dd") & "T" & Format(Now, "HH:mm:ss")

        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Facture")
        XMLelementliste.Item(0).Item("Identifiant").InnerText = CurrentFactureVitale.G1110C1
        While XMLelementliste.Item(0).Item("Identifiant").InnerText.Length < 9
            XMLelementliste.Item(0).Item("Identifiant").InnerText = "0" & XMLelementliste.Item(0).Item("Identifiant").InnerText
        End While
        If Val(CurrentFactureVitale.TabLigneFacture(1).G1850C2) > 0 Then
            XMLelementliste.Item(0).Item("Renouvellement").InnerText = "1"
        Else
            XMLelementliste.Item(0).Item("Renouvellement").InnerText = "0"
        End If
        XMLelementliste.Item(0).Item("MtTotal").InnerText = Replace((CurrentFactureVitale.G1910C2 / 100).ToString, ",", ".")
        XMLelementliste.Item(0).Item("MtCaisse").InnerText = Replace((CurrentFactureVitale.G1910C3 / 100).ToString, ",", ".")
        XMLelementliste.Item(0).Item("MtComplementaire").InnerText = "000000.00"

        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Beneficiaire")
        If CurrentFactureVitale.G1160C1 <> "" Then
            XMLelementliste.Item(0).Item("NIR").InnerText = CurrentFactureVitale.G1160C1 & CurrentFactureVitale.G1160C2
        End If
        XMLelementliste.Item(0).Item("NIRAssure").InnerText = CurrentFactureVitale.G1130C2 & CurrentFactureVitale.G1130C3
        XMLelementliste.Item(0).Item("DateNai").InnerText = Mid(CurrentFactureVitale.G1130C4, 1, 4) & "-" & Mid(CurrentFactureVitale.G1130C4, 5, 2) & "-" & Mid(CurrentFactureVitale.G1130C4, 7, 2)
        XMLelementliste.Item(0).Item("RangNai").InnerText = CurrentFactureVitale.G1130C5

        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Organisme")
        XMLelementliste.Item(0).Item("Identite").InnerText = CurrentFactureVitale.G1310C1 & CurrentFactureVitale.G1310C2 & CurrentFactureVitale.G1310C3

        My_Xml_Doc.Save(Config.LocalNetwork_ServerName & "\scor\index\" & CurrentFactureVitale.G1110C1 & ".xml")


        'TT02.02 Regrouper les fichiers PDF à transmettre
        'TT02.03 Identifier les fichiers PDF déjà transmis
        'TT02.04 Finaliser le dossier de pièces justificatives
        'TT02.05 Finaliser les pièces justificatives




    End Sub

    Public Sub TT02_Debug()
        Bandeau_info_bas_show("TT02_Debug")


        Dim factures As New List(Of Decimal)
        Dim factures_bdd = BDD.FacturesTableAdapter.GetData
        For r = 0 To factures_bdd.Rows.Count - 1
            Bandeau_info_bas_change_text("examen en cours... " & (r + 1).ToString & "/" & factures_bdd.Rows.Count.ToString)
            If Not factures_bdd(r).IsBénéficiaireNull Then
                If Dir(Config.LocalNetwork_ServerName & "\scor\index\" & factures_bdd(r).Num.ToString & ".xml") = "" Then
                    If Dir(Config.LocalNetwork_ServerName & "\scor\doc\" & factures_bdd(r).Num.ToString & "_*.pdf") <> "" Then
                        factures.Add(factures_bdd(r).Num)
                    End If
                End If
            End If
        Next

        Dim erreur As Integer = 0
        Dim compteur As Integer = 0

        For Each num_facture As Decimal In factures
            compteur = compteur + 1
            Bandeau_info_bas_change_text("construction index... " & compteur.ToString & "/" & factures.Count.ToString & "   (" & erreur.ToString & " erreur(s) )")
            If Not My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\index\" & num_facture.ToString & ".xml") Then
                Try
                    Dim facture = BDD.FacturesTableAdapter.GetFactureDataByNum1(num_facture).Item(0)
                    Dim une_ligne_facture = COMPTOIR_MAIN.Facture_LigneFactureTableAdapter1.GetDataByNumFacture(num_facture.ToString).Item(0)



                    'TT02.01 Préparer le fichier d'index ScanOrdo
                    'xml file:Instance_SCANORDO_V02_03
                    Dim My_Xml_Doc As New XmlDocument
                    My_Xml_Doc.Load(Config.LocalNetwork_ServerName & "\scor\XML\Instance_SCANORDO.xml")
                    Dim XMLelementliste As XmlNodeList

                    XMLelementliste = My_Xml_Doc.GetElementsByTagName("SCANORDO")
                    XMLelementliste.Item(0).Item("Identifiant").InnerText = "" 'Ce champ sera renseigné lors de la mise en lot des justificatifs
                    XMLelementliste.Item(0).Item("Temps").InnerText = Format(Now, "yyyy-MM-dd") & "T" & Format(Now, "HH:mm:ss")

                    XMLelementliste = My_Xml_Doc.GetElementsByTagName("Facture")
                    XMLelementliste.Item(0).Item("Identifiant").InnerText = facture.G1110C1
                    While XMLelementliste.Item(0).Item("Identifiant").InnerText.Length < 9
                        XMLelementliste.Item(0).Item("Identifiant").InnerText = "0" & XMLelementliste.Item(0).Item("Identifiant").InnerText
                    End While
                    If Val(une_ligne_facture.G1850C2) > 0 Then
                        XMLelementliste.Item(0).Item("Renouvellement").InnerText = "1"
                    Else
                        XMLelementliste.Item(0).Item("Renouvellement").InnerText = "0"
                    End If
                    XMLelementliste.Item(0).Item("MtTotal").InnerText = Replace((facture.G1910C2 / 100).ToString, ",", ".")
                    XMLelementliste.Item(0).Item("MtCaisse").InnerText = Replace((facture.G1910C3 / 100).ToString, ",", ".")
                    XMLelementliste.Item(0).Item("MtComplementaire").InnerText = "000000.00"

                    XMLelementliste = My_Xml_Doc.GetElementsByTagName("Beneficiaire")
                    If facture.G1160C1 <> "" Then
                        XMLelementliste.Item(0).Item("NIR").InnerText = facture.G1160C1 & facture.G1160C2
                    End If
                    XMLelementliste.Item(0).Item("NIRAssure").InnerText = facture.G1130C2 & facture.G1130C3
                    XMLelementliste.Item(0).Item("DateNai").InnerText = Mid(facture.G1130C4, 1, 4) & "-" & Mid(facture.G1130C4, 5, 2) & "-" & Mid(facture.G1130C4, 7, 2)
                    XMLelementliste.Item(0).Item("RangNai").InnerText = facture.G1130C5

                    XMLelementliste = My_Xml_Doc.GetElementsByTagName("Organisme")
                    XMLelementliste.Item(0).Item("Identite").InnerText = facture.G1310C1 & facture.G1310C2 & facture.G1310C3

                    My_Xml_Doc.Save(Config.LocalNetwork_ServerName & "\scor\index\" & facture.G1110C1 & ".xml")


                    'TT02.02 Regrouper les fichiers PDF à transmettre
                    'TT02.03 Identifier les fichiers PDF déjà transmis
                    'TT02.04 Finaliser le dossier de pièces justificatives
                    'TT02.05 Finaliser les pièces justificatives
                Catch ex As Exception
                    erreur = erreur + 1
                    trace_log(ex.Message)
                End Try
            End If
        Next


    End Sub

    Private Sub PictureBoxScanOrdo_MouseHover(sender As Object, e As EventArgs) Handles PictureBoxScanOrdo.MouseHover
        ToolTip1.SetToolTip(PictureBoxScanOrdo, "Nouveau Scan")
        PictureBoxScanOrdo.BackgroundImage = officine.My.Resources.SCANORDO2
    End Sub

    Private Sub PictureBoxScanOrdo_MouseLeave(sender As Object, e As EventArgs) Handles PictureBoxScanOrdo.MouseLeave
        PictureBoxScanOrdo.BackgroundImage = officine.My.Resources.SCANORDO
    End Sub


    Private Sub Validate_Button_MouseHover(sender As Object, e As EventArgs) Handles Validate_Button.MouseHover
        ToolTip1.SetToolTip(Validate_Button, "Enregistre le document")

    End Sub

#Region "Selection picturebox"
    Dim XStart As Integer
    Dim YStart As Integer
    Dim BM As Bitmap
    Private Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        XStart = e.X
        YStart = e.Y
    End Sub

    Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        If e.X > XStart AndAlso e.Y > YStart Then
            BM = New Bitmap(e.X - XStart, e.Y - YStart, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            Dim BR As Brush = Brushes.White
            Dim G As Graphics = Graphics.FromImage(BM)
            G.FillRectangle(BR, 0, 0, BM.Width, BM.Height)
            PictureBox1.Invalidate()
        Else
            BM = Nothing
        End If
    End Sub

    Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
        If Not BM Is Nothing Then
            e.Graphics.DrawImage(BM, XStart, YStart)
        End If
    End Sub




#End Region


End Class