' 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.Text
Imports System.Xml
Public Class PRODUITS_bdd

    Public produit As String
    Public chkbox_can_be_changed As Boolean

    Private Sub PRODUITS_MAIN_Load(sender As Object, e As EventArgs) Handles Me.Load

        Recherche_Produit(produit)
    End Sub


    Public Sub Recherche_Produit(ByVal produit As String)
        For Each c In Panel1.Controls
            If c.GetType.ToString = "System.Windows.Forms.TextBox" Then
                c.text = ""
            End If
        Next
        If produit = "" Then
            Exit Sub
        End If

        Dim produits As DataTable = Me.ProduitsTableAdapter.GetDataProduits(produit, produit, produit, produit)
        ProduitsDataGridView.DataSource = produits
        For c = 0 To ProduitsDataGridView.Columns.Count - 1
            Select Case ProduitsDataGridView.Columns.Item(c).Name
                Case "CIP", "EAN13", "Designation", "nomExploitant"
                Case Else
                    ProduitsDataGridView.Columns.Item(c).Visible = False

            End Select
        Next
        Select Case produits.Rows.Count
            Case 0
                ProduitsDataGridView.Visible = False
                For Each c In Controls
                    If c.GetType.ToString = "System.Windows.Forms.TextBox" Then
                        c.text = ""
                    End If
                Next
                Exit Sub
            Case 1
                ProduitsDataGridView.Visible = True
                ProduitsDataGridView.CurrentCell = ProduitsDataGridView.Item(0, 0)
                ProduitsDataGridView_CellClick(Nothing, Nothing)

            Case Else
                ProduitsDataGridView.Visible = True
                Panel1.Visible = False
        End Select




    End Sub

    Private Sub ProduitsDataGridView_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles ProduitsDataGridView.CellClick
        chkbox_can_be_changed = False
        ProduitsDataGridView.Visible = False

        For c = 0 To ProduitsDataGridView.ColumnCount - 1
            For cc = 0 To Panel1.Controls.Count - 1

                If Panel1.Controls.Item(cc).Name = ProduitsDataGridView.Columns.Item(c).Name Then
                    If ProduitsDataGridView.Item(c, ProduitsDataGridView.CurrentRow.Index).Value IsNot DBNull.Value Then

                        If TypeOf (Panel1.Controls.Item(cc)) Is System.Windows.Forms.TextBox Then
                            Dim txtbx As TextBox = CType(Panel1.Controls.Item(cc), TextBox)
                            txtbx.Text = ProduitsDataGridView.Item(c, ProduitsDataGridView.CurrentRow.Index).Value
                            txtbx.ReadOnly = True
                            'Panel1.Controls.Item(cc).Text = ProduitsDataGridView.Item(c, ProduitsDataGridView.CurrentRow.Index).Value

                            Exit For
                        ElseIf TypeOf (Panel1.Controls.Item(cc)) Is System.Windows.Forms.CheckBox Then
                            Dim chkbx As CheckBox = CType(Panel1.Controls.Item(cc), CheckBox)
                            chkbx.Checked = ProduitsDataGridView.Item(c, ProduitsDataGridView.CurrentRow.Index).Value
                            Exit For
                        End If

                    End If
                End If
            Next
        Next
        TrackBar1.Value = 11
        track_bar_GroupBox.Text = (TrackBar1.Value + 1).ToString + " mois"
        affiche_graphique_vente(CIP.Text, EAN13.Text, Designation.Text, TrackBar1.Value)
        Chart1.ChartAreas(0).AxisX.Interval = 1
        Panel1.Visible = True

    End Sub

    Private Sub affiche_graphique_vente(ByVal CIP As String, EAN13 As String, Désignation As String, Nombre_Mois As Integer)
        Dim TabDate() As String
        ReDim TabDate(Nombre_Mois)
        Dim année As String = Now.Year.ToString
        Dim mois As String = Now.Month.ToString
        If mois.Length < 2 Then
            mois = "0" & mois
        End If
        TabDate(0) = année & mois
        For nbrM = 1 To Nombre_Mois
            If mois = "01" Then
                mois = "12"
                année = (Val(année) - 1).ToString
            Else
                mois = (Val(mois) - 1).ToString
                If mois.Length < 2 Then
                    mois = "0" & mois
                End If
            End If
            TabDate(nbrM) = année & mois
        Next

        If Chart1.Series.IndexOf("maSérie") = -1 Then 'series does not exist
            Chart1.Series.Add("maSérie")
        Else
            Chart1.Series.Remove(Chart1.Series("maSérie"))
            Chart1.Series.Add("maSérie")
        End If
        Chart1.Series("maSérie").Color = Color.YellowGreen
        Chart1.Series("maSérie").LabelForeColor = Color.FromArgb(224, 224, 224)
        Dim total As Integer = 0
        For nbrM = 0 To Nombre_Mois
            Chart1.Series("maSérie").Points.Add()
        Next
        For nbrM = 0 To Nombre_Mois
            Dim nbreparmoi As Integer = Me.ActesTableAdapter1.Select_Sum_YearMonth(CIP, EAN13, Désignation, Mid(TabDate(nbrM), 1, 4), Mid(TabDate(nbrM), 5, 2))
            total = total + nbreparmoi
            Chart1.Series("maSérie").Points.Item(Nombre_Mois - nbrM).AxisLabel = Mid(TabDate(nbrM), 5, 2) + "/" + Mid(TabDate(nbrM), 1, 4)
            Chart1.Series("maSérie").Points.Item(Nombre_Mois - nbrM).IsValueShownAsLabel = True
            Chart1.Series("maSérie").Points.Item(Nombre_Mois - nbrM).SetValueY(nbreparmoi)
        Next
        Chart1.Series("maSérie").LegendText = total.ToString + " (total)"
    End Sub



    Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
        track_bar_GroupBox.Text = (TrackBar1.Value + 1).ToString + " mois"
        affiche_graphique_vente(CIP.Text, EAN13.Text, Designation.Text, TrackBar1.Value)
        Chart1.ChartAreas(0).AxisX.Interval = 1
    End Sub



#Region "CEPS"




    Public Sub CEPS_import_xml_quotidien(ByVal CEPS_File As String)

        Dim file_trace = Application.StartupPath & "\CEPS\" & "import_CEPS_quotidien.txt"
        Dim Vidal_PackService As New Vidal_PackService.PackService
        Vidal_PackService.Timeout = 60000 '3000
        OpenFileDialog1.InitialDirectory = Application.StartupPath + "\CEPS"

        My.Computer.FileSystem.WriteAllText(file_trace, vbCrLf & CEPS_File & " " & Now.ToLongDateString & " " & Now.ToLongTimeString & vbCrLf, True)

        BDD.Produits_Médicaments_SpécifiqueTableAdapter.Delete_All()

        Dim cip_actuel As String = ""
        Bandeau_info_bas_show("Debut importation")
        Try

            Dim CEPS_xml As New XmlDocument
            CEPS_xml.Load(CEPS_File)
            Dim presentations = CEPS_xml.ChildNodes.Item(1).ChildNodes

            Dim compteur As Integer = 0
            Dim compteur_insert = 0
            Dim compteur_update = 0

            For Each presentation As XmlNode In presentations
                compteur = compteur + 1



                cip_actuel = presentation.SelectSingleNode("en_vigueur/info_cip_actuel/cip_actuel").InnerText
                Dim libelle = presentation.SelectSingleNode("en_vigueur/info_libelle/libelle").InnerText
                Dim nomExploitant = presentation.SelectSingleNode("en_vigueur/info_exploitant/nomExploitant").InnerText
                Dim pfht = Val(presentation.SelectSingleNode("en_vigueur/info_pfht/pfht").InnerText)

                Dim pfht_dateEffet
                If Not presentation.SelectSingleNode("en_vigueur/info_pfht/dateEffet") Is Nothing Then
                    pfht_dateEffet = CDate(presentation.SelectSingleNode("en_vigueur/info_pfht/dateEffet").InnerText)
                Else
                    pfht_dateEffet = Now
                    'My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\CEPS\trace.txt", cip_actuel + " : pfht_dateEffet = Now" + vbCrLf, True)
                End If
                Dim pght = Val(presentation.SelectSingleNode("en_vigueur/info_pght/pght").InnerText)
                Dim pght_dateEffet
                If Not presentation.SelectSingleNode("en_vigueur/info_pght/dateApplication") Is Nothing Then
                    pght_dateEffet = CDate(presentation.SelectSingleNode("en_vigueur/info_pght/dateApplication").InnerText)
                Else
                    pght_dateEffet = Now
                    'My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\CEPS\trace.txt", cip_actuel + " : pght_dateEffet = Now" + vbCrLf, True)
                End If
                Dim ppttc = Val(presentation.SelectSingleNode("en_vigueur/info_ppttc/ppttc").InnerText)

                Dim ppttc_dateEffet
                If Not presentation.SelectSingleNode("en_vigueur/info_ppttc/dateEffet") Is Nothing Then
                    ppttc_dateEffet = CDate(presentation.SelectSingleNode("en_vigueur/info_ppttc/dateEffet").InnerText)
                Else
                    ppttc_dateEffet = Now
                    'My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\CEPS\trace.txt", cip_actuel + " : ppttc_dateEffet = Now" + vbCrLf, True)
                End If
                Dim ppttc_dateOpposabilite
                If Not presentation.SelectSingleNode("en_vigueur/info_ppttc/dateOpposabilite") Is Nothing Then
                    ppttc_dateOpposabilite = CDate(presentation.SelectSingleNode("en_vigueur/info_ppttc/dateOpposabilite").InnerText)
                ElseIf Not presentation.SelectSingleNode("en_vigueur/info_ppttc/dateEffet") Is Nothing Then
                    ppttc_dateOpposabilite = CDate(presentation.SelectSingleNode("en_vigueur/info_ppttc/dateEffet").InnerText)
                Else
                    ppttc_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
                    'My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\CEPS\trace.txt", cip_actuel + " : ppttc_dateOpposabilite = Now" + vbCrLf, True)
                End If
                Dim tauxPriseEnCharge As Double = 0
                If Not presentation.SelectSingleNode("en_vigueur/info_taux_priseEnCharge/tauxPriseEnCharge") Is Nothing Then
                    tauxPriseEnCharge = Val(presentation.SelectSingleNode("en_vigueur/info_taux_priseEnCharge/tauxPriseEnCharge").InnerText)
                End If
                Dim tauxPriseEnCharge_dateEffet
                If Not presentation.SelectSingleNode("en_vigueur/info_taux_priseEnCharge/dateEffet") Is Nothing Then
                    tauxPriseEnCharge_dateEffet = CDate(presentation.SelectSingleNode("en_vigueur/info_taux_priseEnCharge/dateEffet").InnerText)
                Else
                    tauxPriseEnCharge_dateEffet = Now
                    'My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\CEPS\trace.txt", cip_actuel + " : tauxPriseEnCharge_dateEffet = Now" + vbCrLf, True)
                End If
                Dim tauxParticipation As Double = 0
                If Not presentation.SelectSingleNode("en_vigueur/info_tauxParticipation/tauxParticipation") Is Nothing Then
                    tauxParticipation = Val(presentation.SelectSingleNode("en_vigueur/info_tauxParticipation/tauxParticipation").InnerText)
                End If
                Dim tauxParticipation_dateEffet
                If Not presentation.SelectSingleNode("en_vigueur/info_tauxParticipation/dateEffet") Is Nothing Then
                    tauxParticipation_dateEffet = CDate(presentation.SelectSingleNode("en_vigueur/info_tauxParticipation/dateEffet").InnerText)
                Else
                    tauxParticipation_dateEffet = Now
                    'My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\CEPS\trace.txt", cip_actuel + " : tauxParticipation_dateEffet = Now" + vbCrLf, True)
                End If
                Dim type = presentation.SelectSingleNode("en_vigueur/type").InnerText
                Dim conditionnementTrimestriel As Boolean
                If UCase(presentation.SelectSingleNode("en_vigueur/conditionnementTrimestriel").InnerText) = "OUI" Then
                    conditionnementTrimestriel = True
                Else
                    conditionnementTrimestriel = False
                End If
                Dim statutException = presentation.SelectSingleNode("en_vigueur/statutException").InnerText
                Dim statutException_bool = False
                If UCase(statutException) = "OUI" Then statutException_bool = True

                If Not presentation.SelectSingleNode("en_vigueur/medicamentSpecifique") Is Nothing Then
                    BDD.Produits_Médicaments_SpécifiqueTableAdapter.Insert(cip_actuel, presentation.SelectSingleNode("en_vigueur/medicamentSpecifique").InnerText)
                End If

                'If Me.CEPS_mensuelTableAdapter.GetDataBy_cip_actuel(cip_actuel).Rows.Count = 0 Then
                '    Me.CEPS_mensuelTableAdapter.Insert(cip_actuel, libelle, nomExploitant, pfht, pfht_dateEffet, pght, pght_dateEffet, ppttc, ppttc_dateEffet, ppttc_dateOpposabilite, tauxPriseEnCharge, _
                '                                       tauxParticipation_dateEffet, tauxParticipation, Nothing, type, conditionnementTrimestriel, statutException)
                'Else
                '    Me.CEPS_mensuelTableAdapter.Update_by_cip_actuel(libelle, nomExploitant, pfht, pfht_dateEffet, pght, pght_dateEffet, ppttc, ppttc_dateEffet, ppttc_dateOpposabilite, tauxPriseEnCharge, _
                '                                                     tauxParticipation_dateEffet, tauxParticipation, tauxParticipation_dateEffet, type, conditionnementTrimestriel, statutException, cip_actuel)
                'End If


                'BdM_Prix
                Dim BDM_Prix_table = Me.BDM_PrixTableAdapter.GetDataBy_CIP_date(cip_actuel, Format(ppttc_dateOpposabilite, "yyyyMMdd"))
                If BDM_Prix_table.Rows.Count > 0 Then
                    Me.BDM_PrixTableAdapter.Update_By_CIP_Date(BDM_Prix_table(0).CIP13, Mid(BDM_Prix_table(0).CIP13, 6, 7), ppttc * 100, pfht * 100, Format(ppttc_dateOpposabilite, "yyyyMMdd"))
                Else
                    Me.BDM_PrixTableAdapter.Insert(cip_actuel, Mid(cip_actuel, 6, 7), ppttc * 100, pfht * 100, Format(ppttc_dateOpposabilite, "yyyyMMdd"))
                End If

                'BdM_TFR

                If Not presentation.SelectSingleNode("en_vigueur/info_tfr/tfr") Is Nothing Then
                    Dim tfr = CDec(Replace(presentation.SelectSingleNode("en_vigueur/info_tfr/tfr").InnerText, ".", ","))

                    Dim tfr_dateOpposabilite As Date
                    If Not presentation.SelectSingleNode("en_vigueur/info_tfr/dateOpposabilite") Is Nothing Then
                        tfr_dateOpposabilite = CDate(presentation.SelectSingleNode("en_vigueur/info_tfr/dateOpposabilite").InnerText)
                    Else
                        If Not presentation.SelectSingleNode("en_vigueur/info_tfr/dateEffet") Is Nothing Then
                            tfr_dateOpposabilite = CDate(presentation.SelectSingleNode("en_vigueur/info_tfr/dateEffet").InnerText)
                        Else
                            tfr_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
                        End If
                    End If

                    CEPS_TFR_import_data(cip_actuel, tfr, tfr_dateOpposabilite)
                End If



                '<decisions>
                If Not presentation.SelectSingleNode("decisions") Is Nothing Then
                    CEPS_Traitements_decision(presentation.SelectSingleNode("decisions"), cip_actuel)
                End If

                'VIDAL   
                Dim Vidal_id As Integer
                Dim CIP As String = ""
                Dim EAN13 As String = ""
                Dim désignation As String = ""
                Dim TVA As Single
                Dim Contenance As String = ""
                Dim Unitecontenance As String = ""
                Dim Assimilestupefiant = "0"
                Dim Prestation As String = ""
                Dim liste As String = ""
                Dim Prestation_actCodeValue As String = ""
                Dim CIS As String = ""
                Dim communityAgrement As Boolean
                Dim dispensationPlace As String = ""
                Dim drugInSport As Boolean
                Dim maxPrescriptionDuration As String = ""
                Dim prescriptionName As String = ""
                Dim offMarketDate As Date
                Dim onFreeAccess As Boolean
                Dim onMarketDate As Date
                Dim otc As Boolean
                Dim vidal_productId As Integer
                Dim withoutPrescr As Boolean
                Dim vidal = Vidal_PackService.searchByCip(cip_actuel)
                If Not vidal Is Nothing Then
                    Vidal_id = vidal.id
                    If Not vidal.cip Is Nothing Then CIP = vidal.cip
                    If Not vidal.cip13 Is Nothing Then EAN13 = vidal.cip13
                    If Not vidal.name Is Nothing Then désignation = vidal.name
                    If Not vidal.vatRateValue Is Nothing Then
                        TVA = vidal.vatRateValue
                    Else
                        My.Computer.FileSystem.WriteAllText(file_trace, "Pas de données TVA dans vidal pour " & cip_actuel & " (fixée à 2,1)" & vbCrLf, True)
                        TVA = (2.1)
                    End If

                    If Not vidal.dose Is Nothing Then Contenance = vidal.dose
                    If Not vidal.doseUnit Is Nothing Then Unitecontenance = vidal.doseUnit
                    If vidal.narcoticPrescription = True Then Assimilestupefiant = "1"
                    'End If
                    If Not vidal.actCode Is Nothing Then Prestation = vidal.actCode.ToString
                    If Not vidal.listValue Is Nothing Then If Not vidal.listValue.ToString = "False" Then liste = vidal.listValue.ToString
                    'If Not vidal.listValue.ToString = "False" Then liste = vidal.listValue.ToString
                    ' End If
                    If Not vidal.actCodeValue Is Nothing Then Prestation_actCodeValue = vidal.actCodeValue
                    If Not vidal.cis Is Nothing Then CIS = vidal.cis
                    communityAgrement = vidal.communityAgrement
                    If Not vidal.dispensationPlace Is Nothing Then dispensationPlace = vidal.dispensationPlace.ToString
                    drugInSport = vidal.drugInSport
                    If Not vidal.maxPrescriptionDuration Is Nothing Then maxPrescriptionDuration = vidal.maxPrescriptionDuration.ToString
                    If Not vidal.prescriptionName Is Nothing Then prescriptionName = vidal.prescriptionName
                    If Not vidal.offMarketDate Is Nothing Then offMarketDate = vidal.offMarketDate
                    onFreeAccess = vidal.onFreeAccess
                    If Not vidal.onMarketDate Is Nothing Then onMarketDate = vidal.onMarketDate
                    otc = vidal.otc
                    If Not vidal.productId Is Nothing Then vidal_productId = vidal.productId
                    withoutPrescr = vidal.withoutPrescr

                    'BDD
                    Select Case Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Rows.Count
                        Case 0
                            Me.ProduitsTableAdapter.Insert(CIP, EAN13, EAN13, désignation, ppttc, TVA, 0, "", Contenance, Unitecontenance, Now, Assimilestupefiant, liste, Prestation, "0", "0", 0, "", 100, conditionnementTrimestriel, 0, CIS, Prestation_actCodeValue, type, Vidal_id, communityAgrement, dispensationPlace, drugInSport, maxPrescriptionDuration, offMarketDate, onFreeAccess, onMarketDate, otc, prescriptionName, vidal_productId, withoutPrescr, nomExploitant, statutException_bool, False, 0, 0, "", "", False, False, False, EAN13, "", 0, False, True, False, New Date(3000, 1, 1))
                            compteur_insert = compteur_insert + 1
                        Case 1
                            Dim prod = Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Item(0)
                            Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB(CIP, EAN13, EAN13, désignation, ppttc, TVA, prod.Stock, "", "", 0, False, Contenance, _
                                                                                  Unitecontenance, prod.DateDernièrevente, Assimilestupefiant, Prestation, liste, "0", "0", prod.G1610C8, _
                                                                                  conditionnementTrimestriel, prod.en_commande, Prestation_actCodeValue, CIS, communityAgrement, dispensationPlace, drugInSport, type, Vidal_id, maxPrescriptionDuration, prescriptionName, offMarketDate, onFreeAccess, onMarketDate, otc, vidal_productId, withoutPrescr, statutException_bool, nomExploitant, prod.Réassort_auto, prod.Réassort_auto_seuil_min, prod.Réassort_auto_seuil_max, prod.Répartiteur_principal, prod.Répartiteur_secondaire, cip_actuel)
                            compteur_update = compteur_update + 1
                        Case Else
                            My.Computer.FileSystem.WriteAllText(file_trace, "Plusieurs enregistrements pour " & cip_actuel & vbCrLf, True)
                            Dim prod = Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Item(0)
                            Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB(CIP, EAN13, EAN13, désignation, ppttc, TVA, prod.Stock, "", "", 0, False, Contenance, Unitecontenance, prod.DateDernièrevente, Assimilestupefiant, Prestation, liste, "0", "0", prod.G1610C8, conditionnementTrimestriel, prod.en_commande, Prestation_actCodeValue, CIS, communityAgrement, dispensationPlace, drugInSport, type, Vidal_id, maxPrescriptionDuration, prescriptionName, offMarketDate, onFreeAccess, onMarketDate, otc, vidal_productId, withoutPrescr, statutException_bool, nomExploitant, prod.Réassort_auto, prod.Réassort_auto_seuil_min, prod.Réassort_auto_seuil_max, prod.Répartiteur_principal, prod.Répartiteur_secondaire, cip_actuel)
                            compteur_update = compteur_update + Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Rows.Count
                    End Select

                Else
                    'My.Computer.FileSystem.WriteAllText(file_trace, "Pas de données VIDAL pour " & cip_actuel & vbCrLf, True)  
                    Select Case Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Rows.Count
                        Case 0
                            Me.ProduitsTableAdapter.Insert("", cip_actuel, cip_actuel, libelle, ppttc, TVA, 0, "", Contenance, Unitecontenance, Now, Assimilestupefiant, liste, Prestation, "0", "0", 0, "", 100, conditionnementTrimestriel, 0, CIS, Prestation_actCodeValue, type, Vidal_id, communityAgrement, dispensationPlace, drugInSport, maxPrescriptionDuration, offMarketDate, onFreeAccess, onMarketDate, otc, prescriptionName, vidal_productId, withoutPrescr, nomExploitant, statutException_bool, False, 0, 0, "", "", False, False, False, cip_actuel, "", 0, False, True, False, New Date(3000, 1, 1))
                            compteur_insert = compteur_insert + 1
                        Case 1
                            Dim prod = Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Item(0)
                            Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB("", cip_actuel, cip_actuel, libelle, ppttc, TVA, prod.Stock, "", "", 0, False, Contenance, Unitecontenance, prod.DateDernièrevente, Assimilestupefiant, Prestation, liste, "0", "0", prod.G1610C8, conditionnementTrimestriel, prod.en_commande, Prestation_actCodeValue, CIS, communityAgrement, dispensationPlace, drugInSport, type, Vidal_id, maxPrescriptionDuration, prescriptionName, offMarketDate, onFreeAccess, onMarketDate, otc, vidal_productId, withoutPrescr, statutException_bool, nomExploitant, prod.Réassort_auto, prod.Réassort_auto_seuil_min, prod.Réassort_auto_seuil_max, prod.Répartiteur_principal, prod.Répartiteur_secondaire, cip_actuel)
                            compteur_update = compteur_update + 1
                        Case Else
                            My.Computer.FileSystem.WriteAllText(file_trace, "Plusieurs enregistrements pour " & cip_actuel & vbCrLf, True)
                            Dim prod = Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Item(0)
                            Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB("", cip_actuel, cip_actuel, libelle, ppttc, TVA, prod.Stock, "", "", 0, False, Contenance, Unitecontenance, prod.DateDernièrevente, Assimilestupefiant, Prestation, liste, "0", "0", prod.G1610C8, conditionnementTrimestriel, prod.en_commande, Prestation_actCodeValue, CIS, communityAgrement, dispensationPlace, drugInSport, type, Vidal_id, maxPrescriptionDuration, prescriptionName, offMarketDate, onFreeAccess, onMarketDate, otc, vidal_productId, withoutPrescr, statutException_bool, nomExploitant, prod.Réassort_auto, prod.Réassort_auto_seuil_min, prod.Réassort_auto_seuil_max, prod.Répartiteur_principal, prod.Répartiteur_secondaire, cip_actuel)
                            compteur_update = compteur_update + Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(cip_actuel).Rows.Count
                    End Select
                End If

                Bandeau_info_bas_change_text("CEPS QUOTIDIEN " + compteur.ToString + "/" + presentations.Count.ToString + " (import:" & compteur_insert.ToString & " update:" & compteur_update.ToString & ")")


            Next

            My.Computer.FileSystem.WriteAllText(file_trace, "INSERT : " + compteur_insert.ToString + "   UPDATE : " + compteur_update.ToString + vbCrLf & vbCrLf, True)
            CEPS_xml = Nothing
            My.Computer.FileSystem.DeleteFile(CEPS_File)

   
            Bandeau_info_bas_hide()'Bandeau_info_bas_show_thread)

        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(file_trace, "PROCESUS INTERROMPU:" & cip_actuel & ": " & ex.ToString & vbCrLf, True)
            MyMsg_Box.Presentation("Officine", cip_actuel & ": " & ex.Message, False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Bandeau_info_bas_hide()'Bandeau_info_bas_show_thread)
        End Try

    End Sub

    Public Sub CEPS_import_xml_mensuel(ByVal CEPS_File As String, ByVal show_message As Boolean)
        Bandeau_info_bas_show("Debut importation CEPS MENSUEL")
        Dim file_trace = Application.StartupPath & "\CEPS\" & "import_CEPS_mensuel.txt"
        My.Computer.FileSystem.WriteAllText(file_trace, Now.ToLongDateString & " " & Now.ToLongTimeString & vbCrLf, True)

        Dim cip_actuel As String = ""
        Try

            'While CEPS_File <> ""
            My.Computer.FileSystem.WriteAllText(file_trace, Now.ToLongDateString & " " & Now.ToLongTimeString & " " & CEPS_File & vbCrLf, True)


            Dim CEPS_xml As New XmlDocument
            CEPS_xml.Load(CEPS_File)
            Dim presentations = CEPS_xml.ChildNodes.Item(1).ChildNodes

            Dim compteur As Integer = 0

            For Each presentation As XmlNode In presentations
                compteur = compteur + 1


                'recherche d'anciens prix dans  <archive><info_ppttc> (l'import de CEPS quotidien ne contient pas les anciens prix)
                cip_actuel = presentation.SelectSingleNode("archive/info_cip_actuel/cip_actuel").InnerText
                If Not presentation.SelectSingleNode("archive/info_ppttc/ppttc") Is Nothing Then
                    Dim old_ppttc = Replace(presentation.SelectSingleNode("archive/info_ppttc/ppttc").InnerText, ".", ",")
                    Dim old_ppttc_dateOpposabilite As Date
                    If Not presentation.SelectSingleNode("archive/info_ppttc/dateOpposabilite") Is Nothing Then
                        old_ppttc_dateOpposabilite = CDate(presentation.SelectSingleNode("archive/info_ppttc/dateOpposabilite").InnerText)
                    ElseIf Not presentation.SelectSingleNode("archive/info_ppttc/dateEffet") Is Nothing Then
                        old_ppttc_dateOpposabilite = CDate(presentation.SelectSingleNode("archive/info_ppttc/dateEffet").InnerText)
                    Else
                        old_ppttc_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
                    End If


                    Dim old_BDM_Prix_table = Me.BDM_PrixTableAdapter.GetDataBy_CIP_date(cip_actuel, Format(old_ppttc_dateOpposabilite, "yyyyMMdd"))
                    If old_BDM_Prix_table.Rows.Count > 0 Then
                        Me.BDM_PrixTableAdapter.Update_By_CIP_Date(old_BDM_Prix_table(0).CIP13, Mid(old_BDM_Prix_table(0).CIP13, 6, 7), old_ppttc * 100, old_BDM_Prix_table(0).Prix_Fabricant_HT, Format(old_ppttc_dateOpposabilite, "yyyyMMdd"))
                    Else
                        Me.BDM_PrixTableAdapter.Insert(cip_actuel, Mid(cip_actuel, 6, 7), old_ppttc * 100, 0, Format(old_ppttc_dateOpposabilite, "yyyyMMdd"))
                    End If
                End If


                'TFR <archive><info_tfr>
                If Not presentation.SelectSingleNode("archive/info_tfr/tfr") Is Nothing Then
                    Dim old_tfr = CDec(Replace(presentation.SelectSingleNode("archive/info_tfr/tfr").InnerText, ".", ","))
                    Dim old_tfr_dateOpposabilite As Date
                    If Not presentation.SelectSingleNode("archive/info_tfr/dateOpposabilite") Is Nothing Then
                        old_tfr_dateOpposabilite = CDate(presentation.SelectSingleNode("archive/info_tfr/dateOpposabilite").InnerText)
                    ElseIf Not presentation.SelectSingleNode("archive/info_tfr/dateEffet") Is Nothing Then
                        old_tfr_dateOpposabilite = CDate(presentation.SelectSingleNode("archive/info_tfr/dateEffet").InnerText)
                    Else
                        old_tfr_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
                    End If

                    CEPS_TFR_import_data(cip_actuel, old_tfr, old_tfr_dateOpposabilite)

                End If

                '<decisions>
                If Not presentation.SelectSingleNode("decisions") Is Nothing Then
                    CEPS_Traitements_decision(presentation.SelectSingleNode("decisions"), cip_actuel)

                End If

                Bandeau_info_bas_change_text("Importation " & Mid(CEPS_File, InStrRev(CEPS_File, "\") + 1) & " " & compteur.ToString & "/" & presentations.Count.ToString)

                Application.DoEvents()







            Next


            My.Computer.FileSystem.WriteAllText(file_trace, vbCrLf & compteur.ToString & vbCrLf & vbCrLf, True)
            CEPS_xml = Nothing
            If My.Computer.FileSystem.FileExists(Application.StartupPath & "\CEPS\old\" & Mid(CEPS_File, InStrRev(CEPS_File, "\") + 1)) Then
                My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\CEPS\old\" & Mid(CEPS_File, InStrRev(CEPS_File, "\") + 1))
                System.Threading.Thread.Sleep(2000)
            End If
            My.Computer.FileSystem.MoveFile(CEPS_File, Application.StartupPath & "\CEPS\old\" & Mid(CEPS_File, InStrRev(CEPS_File, "\") + 1), True)

            Bandeau_info_bas_hide()'Bandeau_info_bas_show_thread)


            'Dim rep As String = Mid(CEPS_File, 1, InStrRev(CEPS_File, "\"))
            'Dim file = Mid(CEPS_File, InStrRev(CEPS_File, "\") + 1)
            'If InStr(file, "CEPS_mensuel_") = 1 And file.Length = ("CEPS_mensuel_yyyyMM.xml").Length Then
            '    Dim year = CInt(Mid(file, ("CEPS_mensuel_").Length + 1, 4))
            '    Dim month = CInt(Mid(file, ("CEPS_mensuel_yyyy").Length + 1, 2))

            '    If month = 12 Then
            '        year = year + 1
            '        month = 1
            '    Else
            '        month = month + 1
            '    End If
            '    Dim year_strg = year.ToString
            '    Dim month_strg = month.ToString
            '    If month_strg.Length = 1 Then
            '        month_strg = "0" & month_strg
            '    End If
            '    Dim fichiersuivant = "CEPS_mensuel_" & year_strg & month_strg & ".xml"

            '    If My.Computer.FileSystem.FileExists(rep & fichiersuivant) Then
            '        CEPS_File = rep & fichiersuivant
            '    ElseIf show_message = True Then
            '        MyMsg_Box.Presentation("Officine", "dernier fichier importé: " & Mid(CEPS_File, InStrRev(CEPS_File, "\") + 1), False, "", False, "", True, "OK")
            '        MyMsg_Box.ShowDialog()
            '        CEPS_File = ""


            '    End If

            'End If

            'End While
        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(file_trace, vbCrLf & "PROCESUS INTERROMPU:" & vbCrLf & cip_actuel & ": " & vbCrLf & ex.ToString & vbCrLf, True)
            MyMsg_Box.Presentation("Officine", cip_actuel & ": " & ex.Message, False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()

            Bandeau_info_bas_hide()'Bandeau_info_bas_show_thread)
        End Try

    End Sub


    Public Sub CEPS_Traitements_decision(ByVal Decisions As XmlNode, ByVal cip_actuel As String)
        For Each decision As XmlNode In Decisions.ChildNodes

            Select Case decision.SelectSingleNode("natureDecision").InnerText

                Case "Modification de prix", "Réforme des marges"
                    CEPS_Modification_Prix(decision, cip_actuel)

                Case "Création de TFR", "Modification de TFR"
                    If Not decision.SelectSingleNode("info_tfr/tfr") Is Nothing Then
                        Dim tfr = CDec(Replace(decision.SelectSingleNode("info_tfr/tfr").InnerText, ".", ","))
                        Dim tfr_dateOpposabilite As Date
                        If Not decision.SelectSingleNode("info_tfr/dateOpposabilite") Is Nothing Then
                            tfr_dateOpposabilite = CDate(decision.SelectSingleNode("info_tfr/dateOpposabilite").InnerText)
                        ElseIf Not decision.SelectSingleNode("info_tfr/dateEffet") Is Nothing Then
                            tfr_dateOpposabilite = CDate(decision.SelectSingleNode("info_tfr/dateEffet").InnerText)
                        Else
                            tfr_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
                        End If
                        CEPS_TFR_import_data(cip_actuel, tfr, tfr_dateOpposabilite)
                        My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\import_de_TFR.txt", cip_actuel & vbCrLf, True)
                    End If
                Case "Rectification"
                    If Not decision.SelectSingleNode("decisionRectifiee") Is Nothing Then
                        Select Case decision.SelectSingleNode("decisionRectifiee").InnerText
                            Case "Modification de prix", "Réforme des marges"
                                CEPS_Modification_Prix(decision, cip_actuel)
                            Case Else
                                My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\rectification_inconnues.csv", cip_actuel & ";" & decision.SelectSingleNode("decisionRectifiee").InnerText & vbCrLf, True)
                        End Select
                    Else
                        My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\rectification_inconnues.csv", cip_actuel & ";pas de node decisionRectifiee" & vbCrLf, True)
                    End If

                Case "Modification de laboratoire exploitant"
                    My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\Decisions_non_traitées.csv", cip_actuel & ";" & decision.SelectSingleNode("natureDecision").InnerText & vbCrLf, True)
                Case "Modification du libellé de la présentation"
                    My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\Decisions_non_traitées.csv", cip_actuel & ";" & decision.SelectSingleNode("natureDecision").InnerText & vbCrLf, True)
                Case "Radiation"
                    Me.CEPS_DécisionsTableAdapter.Insert(cip_actuel, "Radiation", "PHN", CDate(decision.SelectSingleNode("dateEffetRadiation").InnerText))
                Case "Primo-inscription"
                    CEPS_Modification_Prix(decision, cip_actuel)
                    CEPS_TFR_import_Decision(decision, cip_actuel)
                Case "Modification de code CIP"
                    My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\Decisions_non_traitées.csv", cip_actuel & ";" & decision.SelectSingleNode("natureDecision").InnerText & vbCrLf, True)
                Case "Modification de taux de prise en charge"
                    If Me.CEPS_DécisionsTableAdapter.GetDataBy_Cip_actuel_natureDecision_Date(cip_actuel, "Modification de taux de prise en charge", _
                                        CDate(decision.SelectSingleNode("info_taux_priseEnCharge/dateEffet").InnerText)).Rows.Count > 0 Then
                        Me.CEPS_DécisionsTableAdapter.Update_By_Cip_actuel_natureDecision_Date(decision.SelectSingleNode("info_taux_priseEnCharge/tauxPriseEnCharge").InnerText, cip_actuel, "Modification de taux de prise en charge", CDate(decision.SelectSingleNode("info_taux_priseEnCharge/dateEffet").InnerText))
                    Else
                        Me.CEPS_DécisionsTableAdapter.Insert(cip_actuel, "Modification de taux de prise en charge", decision.SelectSingleNode("info_taux_priseEnCharge/tauxPriseEnCharge").InnerText, CDate(decision.SelectSingleNode("info_taux_priseEnCharge/dateEffet").InnerText))
                    End If



                Case Else
                    My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\natureDecision_inconnues.csv", cip_actuel & ";" & decision.SelectSingleNode("natureDecision").InnerText & vbCrLf, True)
            End Select




        Next
    End Sub


    Public Sub CEPS_Modification_Prix(ByVal decision As XmlNode, ByVal cip_actuel As String)
        'nouveaux prix date
        Dim new_ppttc As String = ""
        Dim new_ppttc_dateOpposabilite As Date
        If Not decision.SelectSingleNode("info_ppttc/ppttc") Is Nothing Then
            new_ppttc = Replace(decision.SelectSingleNode("info_ppttc/ppttc").InnerText, ".", ",")
            If Not decision.SelectSingleNode("info_ppttc/dateOpposabilite") Is Nothing Then
                new_ppttc_dateOpposabilite = CDate(decision.SelectSingleNode("info_ppttc/dateOpposabilite").InnerText)
            ElseIf Not decision.SelectSingleNode("info_ppttc/dateEffet") Is Nothing Then
                new_ppttc_dateOpposabilite = CDate(decision.SelectSingleNode("info_ppttc/dateEffet").InnerText)
            Else
                new_ppttc_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
            End If


            'BdM_Prix
            Dim new_BDM_Prix_table = Me.BDM_PrixTableAdapter.GetDataBy_CIP_date(cip_actuel, Format(new_ppttc_dateOpposabilite, "yyyyMMdd"))
            If new_BDM_Prix_table.Rows.Count > 0 Then
                Me.BDM_PrixTableAdapter.Update_By_CIP_Date(new_BDM_Prix_table(0).CIP13, Mid(new_BDM_Prix_table(0).CIP13, 6, 7), new_ppttc * 100, new_BDM_Prix_table(0).Prix_Fabricant_HT, Format(new_ppttc_dateOpposabilite, "yyyyMMdd"))
            Else
                Me.BDM_PrixTableAdapter.Insert(cip_actuel, Mid(cip_actuel, 6, 7), new_ppttc * 100, 0, Format(new_ppttc_dateOpposabilite, "yyyyMMdd"))
            End If
            My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\CEPS\modification_de_prix.txt", cip_actuel & vbCrLf, True)
        End If
    End Sub
    Public Sub CEPS_TFR_import_data(ByVal cip_actuel As String, ByVal tfr As Decimal, ByVal tfr_dateOpposabilite As Date)
        If Me.BdM_TFRTableAdapter1.GetDataBy_CIP_Date(cip_actuel, tfr_dateOpposabilite).Rows.Count = 0 Then
            Me.BdM_TFRTableAdapter1.Insert(cip_actuel, tfr, tfr_dateOpposabilite)
        Else
            Me.BdM_TFRTableAdapter1.Update_TFR_by_CIP_Date(tfr, cip_actuel, tfr_dateOpposabilite)
        End If
    End Sub
    Public Sub CEPS_TFR_import_Decision(ByVal decision As XmlNode, ByVal cip_actuel As String)
        If Not decision.SelectSingleNode("info_tfr/tfr") Is Nothing Then
            Dim tfr = CDec(Replace(decision.SelectSingleNode("info_tfr/tfr").InnerText, ".", ","))
            Dim tfr_dateOpposabilite As Date
            If Not decision.SelectSingleNode("info_tfr/dateOpposabilite") Is Nothing Then
                tfr_dateOpposabilite = CDate(decision.SelectSingleNode("info_tfr/dateOpposabilite").InnerText)
            ElseIf Not decision.SelectSingleNode("info_tfr/dateEffet") Is Nothing Then
                tfr_dateOpposabilite = CDate(decision.SelectSingleNode("info_tfr/dateEffet").InnerText)
            Else
                tfr_dateOpposabilite = DateAdd(DateInterval.Year, -100, Now)
            End If
            If Me.BdM_TFRTableAdapter1.GetDataBy_CIP_Date(cip_actuel, tfr_dateOpposabilite).Rows.Count = 0 Then
                Me.BdM_TFRTableAdapter1.Insert(cip_actuel, tfr, tfr_dateOpposabilite)
            Else
                Me.BdM_TFRTableAdapter1.Update_TFR_by_CIP_Date(tfr, cip_actuel, tfr_dateOpposabilite)
            End If
        End If
    End Sub
#End Region

    Private Sub recherche_TextBox_KeyDown(sender As Object, e As KeyEventArgs) Handles recherche_TextBox.KeyDown
        If e.KeyCode = Keys.Enter Then
            Recherche_Produit(recherche_TextBox.Text)
        End If
    End Sub

    Private Sub recherche_TextBox_Validated(sender As Object, e As EventArgs) Handles recherche_TextBox.Validated
        Recherche_Produit(recherche_TextBox.Text)
    End Sub





    Private Sub CheckedChanged(sender As Object, e As EventArgs) Handles statutException.Click, conditionnement_trimestriel.Click, withoutPrescr.Click, otc.Click, onFreeAccess.Click, drugInSport.Click, communityAgrement.Click, Réassort_auto.Click
        If chkbox_can_be_changed = False Then
            If DirectCast(sender, CheckBox).Checked = True Then
                DirectCast(sender, CheckBox).Checked = False
            Else
                DirectCast(sender, CheckBox).Checked = True
            End If
        End If
    End Sub

    Private Sub modifier_LinkLabel_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles modifier_LinkLabel.LinkClicked
        If modifier_LinkLabel.Text = "Modifier" Then
            For cc = 0 To Panel1.Controls.Count - 1
                If TypeOf (Panel1.Controls.Item(cc)) Is System.Windows.Forms.TextBox Then
                    Dim txtbx As TextBox = CType(Panel1.Controls.Item(cc), TextBox)
                    txtbx.ReadOnly = False
                End If
            Next
            chkbox_can_be_changed = True
            modifier_LinkLabel.Text = "Enregistrer"

        Else
            If CIP.Text <> "" And EAN13.Text <> "" Then
                If CIP.Text.Length <> 7 Or EAN13.Text.Length <> 13 Or InStr(EAN13.Text, CIP.Text) <> 6 Then
                    MyMsg_Box.Presentation("Officine", "incohérence CIP", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Exit Sub
                End If
            End If
            Dim existants = Me.ProduitsTableAdapter.GetDataByInfo(CIP.Text, EAN13.Text, Designation.Text)

            If existants.Rows.Count > 0 Then
                Dim thestring As String = "Attention Produit(s) existant(s):" + Chr(10)
                For r = 0 To existants.Rows.Count - 1
                    thestring = thestring + existants(r).Designation + " " + existants(r).EAN13 + " " + existants(r).CIP + Chr(10)
                Next
                MyMsg_Box.Presentation("Officine", thestring + "VOULEZ VOUS CONTINUER?", True, "OUI", True, "NON", False, "")
                If MyMsg_Box.ShowDialog() = MsgBoxResult.No Then Exit Sub
            End If

            If Stock.Text = "" Or Not IsNumeric(Stock.Text) Then
                MyMsg_Box.Presentation("Officine", "Stock?", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()

                Exit Sub
            End If
            If G1610C8.Text = "" Or Not IsNumeric(G1610C8.Text) Then
                G1610C8.Text = "100"
            End If

            If Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(EAN13.Text).Rows.Count = 1 Then
                Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB(CIP.Text, EAN13.Text, CAB.Text, Designation.Text, PrixventeTTC.Text, TVA.Text, Val(Stock.Text), LPP.Text, LPP_Type_Service.Text, _
                                                               Val(LPP_Quantité.Text), False, Contenance.Text, Unitecontenance.Text, DateDernièrevente.Text, Assimilestupefiant.Text, Prestation.Text, _
                                                               Liste.Text, TFRtype.Text, TFRprix.Text, Val(G1610C8.Text), conditionnement_trimestriel.Checked, Val(en_commande.Text), _
                                                               Prestation_actCodeValue.Text, CIS.Text, communityAgrement.Checked, dispensationPlace.Text, drugInSport.Checked, Type_générique.Text, _
                                                               Vidal_id.Text, maxPrescriptionDuration.Text, prescriptionName.Text, offMarketDate.Text, onFreeAccess.Checked, onMarketDate.Text, otc.Checked, _
                                                               vidal_productId.Text, withoutPrescr.Checked, statutException.Checked, nomExploitant.Text, Réassort_auto.Checked, _
                                                              Val(Réassort_auto_seuil_min.Text), Val(Réassort_auto_seuil_max.Text), Répartiteur_principal.Text, Répartiteur_secondaire.Text, EAN13.Text)
            ElseIf Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(CIP.Text).Rows.Count = 1 Then
                Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB(CIP.Text, EAN13.Text, CAB.Text, Designation.Text, PrixventeTTC.Text, TVA.Text, Val(Stock.Text), LPP.Text, LPP_Type_Service.Text, _
                                                               Val(LPP_Quantité.Text), False, Contenance.Text, Unitecontenance.Text, DateDernièrevente.Text, Assimilestupefiant.Text, Prestation.Text, _
                                                               Liste.Text, TFRtype.Text, TFRprix.Text, Val(G1610C8.Text), conditionnement_trimestriel.Checked, Val(en_commande.Text), _
                                                               Prestation_actCodeValue.Text, CIS.Text, communityAgrement.Checked, dispensationPlace.Text, drugInSport.Checked, Type_générique.Text, _
                                                               Vidal_id.Text, maxPrescriptionDuration.Text, prescriptionName.Text, offMarketDate.Text, onFreeAccess.Checked, onMarketDate.Text, otc.Checked, _
                                                               vidal_productId.Text, withoutPrescr.Checked, statutException.Checked, nomExploitant.Text, Réassort_auto.Checked, _
                                                              Val(Réassort_auto_seuil_min.Text), Val(Réassort_auto_seuil_max.Text), Répartiteur_principal.Text, Répartiteur_secondaire.Text, CIP.Text)
            ElseIf Me.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(CAB.Text).Rows.Count = 1 Then
                Me.ProduitsTableAdapter.Update_By_CIP_or_EAN13_or_CAB(CIP.Text, EAN13.Text, CAB.Text, Designation.Text, PrixventeTTC.Text, TVA.Text, Val(Stock.Text), LPP.Text, LPP_Type_Service.Text, _
                                                             Val(LPP_Quantité.Text), False, Contenance.Text, Unitecontenance.Text, DateDernièrevente.Text, Assimilestupefiant.Text, Prestation.Text, _
                                                             Liste.Text, TFRtype.Text, TFRprix.Text, Val(G1610C8.Text), conditionnement_trimestriel.Checked, Val(en_commande.Text), _
                                                             Prestation_actCodeValue.Text, CIS.Text, communityAgrement.Checked, dispensationPlace.Text, drugInSport.Checked, Type_générique.Text, _
                                                             Vidal_id.Text, maxPrescriptionDuration.Text, prescriptionName.Text, offMarketDate.Text, onFreeAccess.Checked, onMarketDate.Text, otc.Checked, _
                                                             vidal_productId.Text, withoutPrescr.Checked, statutException.Checked, nomExploitant.Text, Réassort_auto.Checked, _
                                                            Val(Réassort_auto_seuil_min.Text), Val(Réassort_auto_seuil_max.Text), Répartiteur_principal.Text, Répartiteur_secondaire.Text, CIP.Text)
            Else
                Me.ProduitsTableAdapter.Insert(CIP.Text, EAN13.Text, CAB.Text, Designation.Text, PrixventeTTC.Text, TVA.Text, Val(Stock.Text), LPP.Text, Contenance.Text, Unitecontenance.Text, _
                                               DateDernièrevente.Text, Assimilestupefiant.Text, Liste.Text, Prestation.Text, TFRprix.Text, TFRtype.Text, Val(LPP_Quantité.Text), LPP_Type_Service.Text, _
                                               Val(G1610C8.Text), conditionnement_trimestriel.Checked, en_commande.Text, CIS.Text, Prestation_actCodeValue.Text, Type_générique.Text, Vidal_id.Text, _
                                               communityAgrement.Checked, dispensationPlace.Text, drugInSport.Checked, maxPrescriptionDuration.Text, offMarketDate.Text, onFreeAccess.Checked, onMarketDate.Text, _
                                               otc.Checked, prescriptionName.Text, vidal_productId.Text, withoutPrescr.Checked, nomExploitant.Text, statutException.Checked, Réassort_auto.Checked, _
                                               Val(Réassort_auto_seuil_max.Text), Val(Réassort_auto_seuil_min.Text), Répartiteur_principal.Text, Répartiteur_secondaire.Text, False, False, False, EAN13.Text, "", 0, False, True, False, New Date(3000, 1, 1))
            End If
            For cc = 0 To Panel1.Controls.Count - 1
                If TypeOf (Panel1.Controls.Item(cc)) Is System.Windows.Forms.TextBox Then
                    Dim txtbx As TextBox = CType(Panel1.Controls.Item(cc), TextBox)
                    txtbx.ReadOnly = True
                End If
            Next
            chkbox_can_be_changed = False
            modifier_LinkLabel.Text = "Modifier"
        End If

    End Sub

    Public Sub CEPS_Application_Décisions()
        Dim décisions = Me.CEPS_DécisionsTableAdapter.Get_Décisions_to_compute(Now)
        For r = 0 To décisions.Rows.Count - 1
            If décisions.Item(r).natureDecision = "Modification de taux de prise en charge" Then
                Select Case décisions.Item(r).New_value
                    Case "15"
                        Me.ProduitsTableAdapter.CEPS_Modification_taux_prise_charge("PH2", "médicament remboursé à 15%", décisions.Item(r).Cip_actuel)
                    Case "30"
                        Me.ProduitsTableAdapter.CEPS_Modification_taux_prise_charge("PH4", "médicament remboursé à 30%", décisions.Item(r).Cip_actuel)
                    Case "65"
                        Me.ProduitsTableAdapter.CEPS_Modification_taux_prise_charge("PH7", "médicament remboursé à 65%", décisions.Item(r).Cip_actuel)
                    Case "100"
                        Me.ProduitsTableAdapter.CEPS_Modification_taux_prise_charge("PH1", "médicament remboursé à 100%", décisions.Item(r).Cip_actuel)
                End Select
                Me.CEPS_DécisionsTableAdapter.DeleteBy_Cip_actuel_natureDecision_Date(décisions.Item(r).Cip_actuel, décisions.Item(r).natureDecision, décisions.Item(r)._Date)

            ElseIf décisions.Item(r).natureDecision = "Radiation" Then
                Me.ProduitsTableAdapter.Set_Prestation_By_CipEan13("PHN", décisions.Item(r).Cip_actuel)
                Me.CEPS_DécisionsTableAdapter.DeleteBy_Cip_actuel_natureDecision_Date(décisions.Item(r).Cip_actuel, décisions.Item(r).natureDecision, décisions.Item(r)._Date)
            End If
        Next
    End Sub




    Private Sub LPP_TextChanged(sender As Object, e As EventArgs) Handles LPP.TextChanged
        LPP_remb_Label.Text = ""
        If LPP.Text <> "" Then
            LPP_remb_Label.Text = "tarif remb:" & _
                (Val(COMPTOIR_MAIN.LPPTableAdapter.GetData_CodeLPP_Date(LPP.Text, Val(Format(Now, "yyyyMMdd"))).Item(0).PrixLPP) / 100).ToString & "€"
        Else
            LPP_remb_Label.Text = ""
        End If
    End Sub

    Public Sub MAJ_Tarifs_Reglementés(ByVal message As Boolean)
        Bandeau_info_bas_show("Mise à jpur des tarifs reglementés...")
        Dim produits = Me.ProduitsTableAdapter.GetData
        'Dim produits = Me.ProduitsTableAdapter.GetDataByCIP_and_EAN13_and_CAB("4661313", "3401046613136", "VELPEAU CERVIX 1 Collier cervical souple marine T1")
        Dim count = 0
        For Each row In produits
            count = count + 1
            Bandeau_info_bas_change_text("Mise à jour des tarifs réglementés...  (" & count.ToString & "/" & produits.Rows.Count.ToString & ")")
            Application.DoEvents()
            Try


                'maj prix médicaments
                If row.Prestation.Length = 3 Then
                    If Mid(row.Prestation, 1, 2) = "PH" And IsNumeric(Mid(row.Prestation, 3, 1)) Then
                        If Not COMPTOIR_MAIN.BdM_PrixTableAdapter1.Select_Prix_Public_TTC(row.EAN13, row.CIP, Format(Now, "yyyyMMdd")) Is Nothing Then
                            If (CDec(COMPTOIR_MAIN.BdM_PrixTableAdapter1.Select_Prix_Public_TTC(row.EAN13, row.CIP, Format(Now, "yyyyMMdd"))) / 100) <> CDec(row.PrixventeTTC) Then
                                If row.EAN13 <> "" Then
                                    Me.ProduitsTableAdapter.set_PrixventeTTC((CDec(COMPTOIR_MAIN.BdM_PrixTableAdapter1.Select_Prix_Public_TTC(row.EAN13, row.CIP, Format(Now, "yyyyMMdd"))) / 100).ToString, row.EAN13, row.CAB, row.Designation)
                                ElseIf row.CIP <> "" Then
                                    Me.ProduitsTableAdapter.set_PrixventeTTC((CDec(COMPTOIR_MAIN.BdM_PrixTableAdapter1.Select_Prix_Public_TTC(row.EAN13, row.CIP, Format(Now, "yyyyMMdd"))) / 100).ToString, row.CIP, row.CAB, row.Designation)
                                End If
                            End If
                        End If
                    End If
                End If

                'maj prix LPP
                If Not row.IsLPPNull Then
                    If row.LPP <> "" And row.LPP_Kit = False Then
                        Dim rembs = COMPTOIR_MAIN.LPPTableAdapter.GetData_CodeLPP_Date(row.LPP, Val(Format(Now, "yyyyMMdd")))
                        If rembs.Rows.Count > 0 Then
                            If Val(rembs.Item(0).Prix_unitaire_réglementé) > 0 Then
                                If ((CDec(rembs.Item(0).Prix_unitaire_réglementé) * CDec(row.LPP_Quantité)) / 100) <> CDec(row.PrixventeTTC) Then
                                    If row.EAN13 <> "" Then
                                        Me.ProduitsTableAdapter.set_PrixventeTTC(((CDec(rembs.Item(0).Prix_unitaire_réglementé) * CDec(row.LPP_Quantité)) / 100).ToString, row.EAN13, row.CAB, row.Designation)
                                    ElseIf row.CIP <> "" Then
                                        Me.ProduitsTableAdapter.set_PrixventeTTC(((CDec(rembs.Item(0).Prix_unitaire_réglementé) * CDec(row.LPP_Quantité)) / 100).ToString, row.CIP, row.CAB, row.Designation)
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If

            Catch ex As Exception
                If message = True Then
                    MyMsg_Box.Presentation("Mise à jour prix réglementés:", "Le processus n'a pas pu traiter le produit " & row.Designation & vbCrLf & row.EAN13 & vbCrLf & row.CIP & vbCrLf & row.CAB & vbCrLf & vbCrLf & "Poursuivre la mise à jour?", True, "OUI", True, "NON", False, "")
                    If MyMsg_Box.ShowDialog() = MsgBoxResult.No Then
                        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                        Exit Sub
                    End If
                End If
            End Try
        Next
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub


    Public Sub MAJ_globale_Dernier_PAHT_remisé()
        Bandeau_info_bas_show("DEBUT PROCEDURE")


        OpenFileDialog1.ShowDialog()


        

        'If MsgBox("VERIFIER PRESENCE FICHIER Application.StartupPath\lgpi data\produits_Stock.CSV" & vbCrLf & "Designation pos 1" & vbCrLf & " GTIN13 pos 2" & vbCrLf & "CIP pos 3" & vbCrLf & _
        '         "Date achat pos 8 " & vbCrLf & " PAHT pos 9", MsgBoxStyle.YesNo) = MsgBoxResult.No Then
        '    Exit Sub
        'End If

        Dim produits = ProduitsTableAdapter.GetData
        Dim compteur = 0
        Dim total_compteur = produits.Rows.Count
        For Each Prod In produits
            compteur = compteur + 1
            Bandeau_info_bas_change_text(compteur.ToString & "/" & total_compteur.ToString & " : " & Prod.Designation)
            Application.DoEvents()
            If Val(Prod.Stock) <> 0 Then
                Try
                    Dim done = False
                    If BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.EAN13, Prod.Designation).Rows.Count > 0 Then
                        For r = 0 To BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.EAN13, Prod.Designation).Rows.Count - 1
                            If BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.EAN13, Prod.Designation).Item(r).Prix_achat_remisé > 0 Then
                                Dim PAHT = BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.EAN13, Prod.Designation).Item(r).Prix_achat_remisé
                                BDD.ProduitsTableAdapter.Set_Dernier_PAHT_remisé(PAHT, Prod.CIP, Prod.EAN13, Prod.CAB, Prod.Designation)
                                done = True
                                Exit For
                            End If
                        Next

                    ElseIf BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CIP, Prod.Designation).Rows.Count > 0 Then
                        For r = 0 To BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CIP, Prod.Designation).Rows.Count - 1
                            If BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CIP, Prod.Designation).Item(r).Prix_achat_remisé > 0 Then
                                Dim PAHT = BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CIP, Prod.Designation).Item(r).Prix_achat_remisé
                                BDD.ProduitsTableAdapter.Set_Dernier_PAHT_remisé(PAHT, Prod.CIP, Prod.EAN13, Prod.CAB, Prod.Designation)
                                done = True
                                Exit For
                            End If
                        Next

                    ElseIf BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CAB, Prod.Designation).Rows.Count > 0 Then
                        For r = 0 To BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CAB, Prod.Designation).Rows.Count - 1
                            If BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CAB, Prod.Designation).Item(r).Prix_achat_remisé > 0 Then
                                Dim PAHT = BDD.Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(Prod.CAB, Prod.Designation).Item(r).Prix_achat_remisé
                                BDD.ProduitsTableAdapter.Set_Dernier_PAHT_remisé(PAHT, Prod.CIP, Prod.EAN13, Prod.CAB, Prod.Designation)
                                done = True
                                Exit For
                            End If
                        Next

                    End If

                    If done = False Then
                        Dim lines As New List(Of String)
                        Dim sr = New StreamReader(OpenFileDialog1.FileName, System.Text.Encoding.Default)
                        Dim line = sr.ReadLine
                        While Not line Is Nothing
                            Dim Dés, GTIN13, Cip As String
                            Dés = CSV_Champ(line, 1)
                            GTIN13 = CSV_Champ(line, 2)
                            Cip = CSV_Champ(line, 3)
                            'If InStr(line, "ALLERGODIL SPRAY NAS ") <> 0 Then

                            'End If
                            If (Dés <> "" And Dés = Prod.Designation) Or (GTIN13 <> "" And GTIN13 = Prod.CAB) Or (Cip <> "" And (Cip = Prod.CIP Or Cip = Prod.EAN13)) Then
                                lines.Add(line.ToString)
                            End If
                            line = sr.ReadLine
                        End While
                        sr.Close()
                        If lines.Count > 0 Then
                            Dim PAHT As Decimal = 0
                            Dim last_date As Integer = 0

                            For Each line2 In lines

                                If CInt(Mid(CSV_Champ(line2, 8), 7, 4) & Mid(CSV_Champ(line2, 8), 4, 2) & Mid(CSV_Champ(line2, 8), 1, 2)) > last_date Then
                                    last_date = CInt(Mid(CSV_Champ(line2, 4), 7, 4) & Mid(CSV_Champ(line2, 4), 4, 2) & Mid(CSV_Champ(line2, 4), 1, 2))
                                    PAHT = CDec(CSV_Champ(line2, 5))
                                End If
                            Next
                            BDD.ProduitsTableAdapter.Set_Dernier_PAHT_remisé(PAHT, Prod.CIP, Prod.EAN13, Prod.CAB, Prod.Designation)
                            done = True
                        End If
                    End If

                    If done = False Then
                        BDD.ProduitsTableAdapter.Set_Dernier_PAHT_remisé(0, Prod.CIP, Prod.EAN13, Prod.CAB, Prod.Designation)
                        My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\MAJ_globale_Dernier_PAHT_remisé.txt", "PAS D'INFO: " & vbCrLf & Prod.Designation & " " & Prod.CIP & " " & Prod.EAN13 & " " & Prod.CAB & vbCrLf & vbCrLf, True)
                    End If
                Catch ex As Exception
                    My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\MAJ_globale_Dernier_PAHT_remisé.txt", ex.Message & vbCrLf & Prod.Designation & " " & Prod.CIP & " " & Prod.EAN13 & " " & Prod.CAB & vbCrLf & vbCrLf, True)

                End Try
            End If
        Next
        Bandeau_info_bas_hide()'Bandeau_info_bas_show_thread)
    End Sub
End Class