' 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/>.
Public Class Produits

    Private recherche_en_cours As Boolean  'pour eviter l'affichage des détails produits sur liste longue
    Private Structure lpp_item
        Dim code As String
        Dim quantité As Integer
    End Structure
    Private lpp_items As List(Of lpp_item)


    Public produit As officine.PharmaDataSet.ProduitsRow

    Private Sub Recherche_TextBox_KeyDown(sender As Object, e As KeyEventArgs) Handles Recherche_TextBox.KeyDown
        If e.KeyCode = Keys.Enter Then
            Recherche_TextBox_Validated(Nothing, Nothing)
        End If
    End Sub
    Public Sub Recherche_TextBox_Validated(sender As Object, e As EventArgs) Handles Recherche_TextBox.Validated
        If Recherche_TextBox.Text = "" Then Exit Sub
        Bandeau_info_bas_show("recherche...")
        Try
            If Mid(Recherche_TextBox.Text, 1, 1) = "$" Then
                Recherche_TextBox.Text = Mid(Recherche_TextBox.Text, 2)
            End If
        Catch ex As Exception

        End Try

        Dim my_Search_Product_Input As New Search_Product_Input
        my_Search_Product_Input.input_String = Recherche_TextBox.Text
        my_Search_Product_Input.calcul_valeurs(100)
        recherche_produit(my_Search_Product_Input)

        Bandeau_info_bas_hide()
    End Sub
    Public Sub recherche_produit(ByVal my_search_product_input As Search_Product_Input)

        If Me.Visible = True Then
            For Each c In Controls
                If c.GetType.ToString = "System.Windows.Forms.TextBox" Then
                    c.text = ""
                End If
            Next
        End If
        Recherche_DataGridView.Rows.Clear()

        If my_search_product_input.output_String = "" Then
            Exit Sub
        End If

        Dim produits_ = Me.ProduitsTableAdapter.GetDataProduits(my_search_product_input.output_String, my_search_product_input.output_String, Replace(my_search_product_input.output_String, " ", "%"), my_search_product_input.output_String)


        Dim aliastable = BDD.Produits_AliasTableAdapter.GetDataBy_all_optional_empty_string("", "", "", "", my_search_product_input.output_String)
        For r = 0 To aliastable.Rows.Count - 1
            produits_.Merge(Me.ProduitsTableAdapter.GetDataProduits(aliastable.Item(r).CIP, aliastable.Item(r).CAB, aliastable.Item(r).Désignation, aliastable.Item(r).EAN13))
        Next

        If produits_.Rows.Count > 100 Then
            MyMsg_Box.Presentation("Officine ?", "Plus de 100 références pour cette recherche." & vbCrLf & vbCrLf & "Poursuivre?", True, "OUI", True, "NON", False, "")
            If MyMsg_Box.ShowDialog = Windows.Forms.DialogResult.No Then
                Exit Sub
            End If
        End If
        If produits_.Rows.Count > 1 Then
            recherche_en_cours = True
        End If
        For r = 0 To produits_.Rows.Count - 1
            Recherche_DataGridView.Rows.Add()
        Next
        For r = 0 To produits_.Rows.Count - 1
            Recherche_DataGridView.Item(Column_Désignation.Index, r).Value = produits_.Item(r).Designation
            Recherche_DataGridView.Item(Column_CIP.Index, r).Value = produits_.Item(r).CIP
            Recherche_DataGridView.Item(Column_EAN13.Index, r).Value = produits_.Item(r).EAN13
            Recherche_DataGridView.Item(Column_CAB.Index, r).Value = produits_.Item(r).CAB
        Next
        Recherche_DataGridView.CurrentCell = Nothing
        If Recherche_DataGridView.Rows.Count > 1 Then
            recherche_en_cours = False
            Recherche_DataGridView.CurrentCell = Recherche_DataGridView.Item(0, 0)

            Recherche_DataGridView.Focus()
        End If
        If produits_.Rows.Count = 1 And my_search_product_input.Is_datamatrix Then
            If produits_.Item(0)("Peremption_Date_Min") Is DBNull.Value Then
                produits_.Item(0).Peremption_Date_Min = New Date(3000, 1, 1)
            End If
            my_search_product_input.Calcul_Peremption_Date_Min(produits_.Item(0).CIP, produits_.Item(0).EAN13, produits_.Item(0).CAB, produits_.Item(0).Designation, CInt(produits_.Item(0).Stock), my_search_product_input.Date_peremption, produits_.Item(0).Peremption_Date_Min)
            'If produits_.Item(0).Peremption_Date_Min = New Date(3000, 1, 1) Then
            '    BDD.ProduitsTableAdapter.Set_Peremption_Date_Min(my_search_product_input.Date_peremption.ToShortDateString, produits_.Item(0).CIP, produits_.Item(0).EAN13, produits_.Item(0).CAB, produits_.Item(0).Designation)

            'ElseIf produits_.Item(0).Peremption_Date_Min <> my_search_product_input.Date_peremption Then
            '    MyMsg_Box.Presentation("Date de peremption", "La date de peremption du produit scanné (" & my_search_product_input.Date_peremption.ToShortDateString & _
            '                                                   ")" & vbCrLf & "est différente de" & vbCrLf & "la date enregistrée pour le stock (" & produits_.Item(0).Peremption_Date_Min.ToShortDateString & ")" & _
            '                                                   vbCrLf & vbCrLf & "Voulez-vous modifier la date pour le stock ?", True, "Oui", True, "Non", False, "")
            '    If MyMsg_Box.ShowDialog = Windows.Forms.DialogResult.Yes Then
            '        BDD.ProduitsTableAdapter.Set_Peremption_Date_Min(my_search_product_input.Date_peremption.ToShortDateString, produits_.Item(0).CIP, produits_.Item(0).EAN13, produits_.Item(0).CAB, produits_.Item(0).Designation)
            '    End If
            'End If
        End If
    End Sub
    Private Sub Recherche_DataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles Recherche_DataGridView.SelectionChanged
        If Recherche_DataGridView.CurrentCell Is Nothing Then Exit Sub
        If Recherche_DataGridView.Rows.Count = 0 Then Exit Sub
        If recherche_en_cours = True Then Exit Sub

        lpp_items = New List(Of lpp_item)
        LPP_codes_ComboBox.Items.Clear()
        LPP_TextBox.Text = ""
        LPP_Qtité_TextBox.Text = "0"

        Dim produits_rows = Me.ProduitsTableAdapter.GetDataProduits(Recherche_DataGridView.Item(Column_CIP.Index, Recherche_DataGridView.CurrentRow.Index).Value, _
                                                              Recherche_DataGridView.Item(Column_CAB.Index, Recherche_DataGridView.CurrentRow.Index).Value, _
                                                              Recherche_DataGridView.Item(Column_Désignation.Index, Recherche_DataGridView.CurrentRow.Index).Value, _
                                                              Recherche_DataGridView.Item(Column_EAN13.Index, Recherche_DataGridView.CurrentRow.Index).Value)
        If produits_rows.Rows.Count = 0 Then
            produit = Nothing
            Exit Sub
        End If
        produit = produits_rows.Item(0)

        DesignationTextBox.Text = produit.Designation
        NomExploitantTextBox.Text = produit.nomExploitant
        EAN13TextBox.Text = produit.EAN13
        If EAN13TextBox.Text = "" Then
            EAN13TextBox.Text = produit.CIP
        End If
        CABTextBox.Text = produit.CAB
        Prixcontrol1.TVA = CDec(produit.TVA)
        If COMPTOIR_MAIN.BdM_PrixTableAdapter1.GetDataBy_CIP_date(EAN13TextBox.Text, Now).Rows.Count > 0 Then
            Prixcontrol1.PV_TTC = CDec(COMPTOIR_MAIN.BdM_PrixTableAdapter1.GetDataBy_CIP_date(EAN13TextBox.Text, Now).Item(0).Prix_Public_TTC)
        Else
            Prixcontrol1.PV_TTC = CDec(produit.PrixventeTTC)
        End If

        StockTextBox.Text = produit.Stock
        Stock_Suivi_CheckBox.Checked = produit.Stock_Suivi
        ListeTextBox.Text = produit.Liste
        PrestationTextBox.Text = produit.Prestation
        Conditionnement_trimestrielCheckBox.Checked = produit.conditionnement_trimestriel

        Prixcontrol1.PA_HT = 0
        Prixcontrol1.Remise = 0
        Dim achats As New PharmaDataSet.Produits_AchatsDataTable
        If produit.EAN13 <> "" Then
            achats.Merge(Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(produit.EAN13, DesignationTextBox.Text))
        End If
        If produit.CAB <> "" And produit.CAB <> produit.EAN13 Then
            achats.Merge(Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(produit.CAB, DesignationTextBox.Text))
        End If
        If produit.CIP <> "" Then
            achats.Merge(Produits_AchatsTableAdapter.GetDataBy_code_designation_ordby_date_desc(produit.CIP, DesignationTextBox.Text))
        End If
        If achats.Rows.Count > 0 Then
            Histo_achats_Label.Visible = True
            achats.DefaultView.Sort = "Date DESC"
            For r = 0 To achats.Rows.Count - 1
                If achats.Item(r).Prix_achat > 0 Then
                    Prixcontrol1.PA_HT = CDec(achats.Item(r).Prix_achat.ToString)
                    Prixcontrol1.Remise = CDec(achats.Item(r).Remise.ToString)
                    'financier_.PAHT_remisé = CDec(achats.Item(r).Prix_achat_remisé.ToString)
                    Prixcontrol1.UG = achats.Item(r).Unités_Gratuites
                    Prixcontrol1.Unitées_reçues = achats.Item(r).Quantité_reçue
                    Exit For
                End If
            Next
        Else
            Histo_achats_Label.Visible = False
        End If
        Commandes_FlowLayoutPanel1.Controls.Clear()
        For r = 0 To Math.Min(4, achats.Rows.Count - 1)
            Dim link As New LinkLabel
            link.Width = 160
            link.LinkColor = Color.Black
            link.Tag = "C" & achats(r).Ref_Commande.ToString & "L" & achats(r).Ligne_Commande.ToString
            link.Text = Replace(achats(r).Prix_achat.ToString, ",", "€") & "(" & achats(r)._Date.ToShortDateString & ")"
            AddHandler link.LinkClicked, AddressOf Commandes_FlowLayoutPanel1_item_click
            Commandes_FlowLayoutPanel1.Controls.Add(link)
        Next
        Prixcontrol1.calcul()


        'LPP


        If produit.LPP_Kit = True Then
            For Each kit_row In COMPTOIR_MAIN.KitsTableAdapter.GetDataBy_Désignation_Kit(produit.Designation)
                Dim item As lpp_item
                item.code = kit_row.Code_LPP
                item.quantité = kit_row.Quantité_LPP
                lpp_items.Add(item)
            Next
        ElseIf produit("LPP") Is DBNull.Value Then '-->pour éviter erreur dbnull
        ElseIf produit.LPP <> "" Then
            Dim item As lpp_item
            item.code = produit.LPP
            item.quantité = produit.LPP_Quantité
            lpp_items.Add(item)
        End If

        Dim total_lpp As Decimal = 0
        For Each item As lpp_item In lpp_items
            LPP_codes_ComboBox.Items.Add(item.code)
            If BDD.LPPTableAdapter.GetData_CodeLPP_Date(item.code, CInt(Format(Now, "yyyyMMdd"))).Rows.Count = 0 Then
                Dim message = "Code LPP " & item.code & ":" & vbCrLf & "PAS DE TARIF DE REMBOURSEMENT A CETTE DATE" & vbCrLf
                Dim histo_rembs = BDD.LPPTableAdapter.GetDataBy_CodeLPP(item.code)
                If histo_rembs.Rows.Count > 0 Then
                    message = message & vbCrLf & "historique:" & vbCrLf
                    For r = 0 To histo_rembs.Rows.Count - 1
                        message = message & (CDec(histo_rembs(r).Tarif_de_référence) / 100).ToString & _
                            "€  du " & Mid(histo_rembs(r).DateMin, 7, 2) & "/" & Mid(histo_rembs(r).DateMin, 5, 2) & "/" & Mid(histo_rembs(r).DateMin, 1, 4) & _
                            " au " & Mid(histo_rembs(r).DateMax, 7, 2) & "/" & Mid(histo_rembs(r).DateMax, 5, 2) & "/" & Mid(histo_rembs(r).DateMax, 1, 4) & vbCrLf
                    Next
                End If
                MyMsg_Box.Presentation("Officine !", message, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            Else
                total_lpp = total_lpp + (CDec(BDD.LPPTableAdapter.GetData_CodeLPP_Date(item.code, CInt(Format(Now, "yyyyMMdd"))).Item(0).Tarif_de_référence) * item.quantité)
            End If
        Next
        If total_lpp <> 0 Then
            LPP_total_TextBox.Text = (total_lpp / 100).ToString & "€"
            LPP_total_TextBox.Visible = True
        Else
            LPP_total_TextBox.Visible = False
        End If




        TrackBar1.Value = 11
        track_bar_GroupBox.Text = (TrackBar1.Value + 1).ToString + " mois"
        affiche_graphique_vente(produit.CIP, produit.EAN13, produit.Designation, TrackBar1.Value)
        Chart1.ChartAreas(0).AxisX.Interval = 1

        If produit.Code_PharmaML = produit.EAN13 Then
            PharmaML_CheckBox.Checked = True
            CIP_RadioButton.Checked = True
            CAB_RadioButton.Checked = False
        ElseIf produit.Code_PharmaML = produit.CAB Then
            PharmaML_CheckBox.Checked = True
            CIP_RadioButton.Checked = False
            CAB_RadioButton.Checked = True
        End If

        If Not produit.IsPrestationNull Then
            Code_Acte_ComboBox.SelectedItem = produit.Prestation
        End If

        Try
            Notes_RichTextBox.Text = produit.Notes
        Catch ex As Exception
            Notes_RichTextBox.Text = ""
        End Try

        Seuil_Min_TextBox.Text = produit.Réassort_auto_seuil_min.ToString
        Seuil_Max_TextBox.Text = produit.Réassort_auto_seuil_max.ToString
        If produit.Réassort_auto = True Then
            AutoRéassort_CheckBox1.Checked = True
        Else
            AutoRéassort_CheckBox1.Checked = False
        End If
        Try
            If produit.Répartiteur_principal = "" Then
                Répartiteur_principal_MyCombobox.SelectedIndex = (-1)
            Else
                Répartiteur_principal_MyCombobox.SelectedItem = produit.Répartiteur_principal
            End If
        Catch ex As Exception
            Répartiteur_principal_MyCombobox.SelectedIndex = (-1)
        End Try

        If produit.préféré = True Then
            préféré_CheckBox.Checked = True
        Else
            préféré_CheckBox.Checked = False
        End If

        If produit.robot = True Then
            robot_CheckBox.Checked = True
        Else
            robot_CheckBox.Checked = False
        End If
        Répartiteur_principal_MyCombobox.Text = produit.Répartiteur_principal

    End Sub

    Private Sub Commandes_FlowLayoutPanel1_item_click(sender As Object, e As EventArgs)
        Dim link As LinkLabel = CType(sender, LinkLabel)
        Dim num_commande = CDec(Mid(link.Tag, 2, InStr(link.Tag, "L") - 2))
        Dim ligne_commande = CDec(Mid(link.Tag, InStr(link.Tag, "L") + 1))

        Dim data = BDD.Produits_AchatsTableAdapter.GetDataBy_Ref_Commande_Ligne_Commande(num_commande, ligne_commande).Item(0)
        Prixcontrol1.PA_HT = CDec(data.Prix_achat.ToString)
        Prixcontrol1.Remise = CDec(data.Remise.ToString)
        Prixcontrol1.UG = data.Unités_Gratuites
        Prixcontrol1.Unitées_reçues = data.Quantité_reçue
        Prixcontrol1.calcul()

    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 = COMPTOIR_MAIN.ActesTableAdapter.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)"
        Chart1.ChartAreas(0).RecalculateAxesScale()
        Chart1.ChartAreas(0).AxisX.Interval = 1
    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(produit.CIP, produit.EAN13, produit.Designation, TrackBar1.Value)

    End Sub








    Private Sub OK_Button_Click(sender As Object, e As EventArgs) Handles OK_Button.Click
        If DesignationTextBox.Text = "" Then Exit Sub
        If Seuil_Min_TextBox.Text = "" Then Seuil_Min_TextBox.Text = "0"
        If Seuil_Max_TextBox.Text = "" Then Seuil_Max_TextBox.Text = "0"

        'Try
        '    CDec(Replace(TVA_TextBox.Text, ".", ",")).ToString()
        '    CDec(Replace(PVTTC_TextBox.Text, ".", ",")).ToString()
        'Catch ex As Exception
        '    MyMsg_Box.Presentation("Officine ! ", "valeur erronée", False, "", False, "", True, "OK")
        '    MyMsg_Box.ShowDialog()
        '    Exit Sub
        'End Try
        If PharmaML_CheckBox.Checked = True And CIP_RadioButton.Checked = False And CAB_RadioButton.Checked = False Then
            MyMsg_Box.Presentation("Officine !", "Pharma-ML:" & vbCrLf & "Préciser code commande.", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        Me.ProduitsTableAdapter.set_PrixventeTTC(Prixcontrol1.PV_TTC, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)

        If Not produit Is Nothing Then
            If CInt(produit.Stock) <> CInt(StockTextBox.Text) Then
                Me.ProduitsTableAdapter.Set_Stock(CInt(StockTextBox.Text), EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
                Dim Info As String
                Info = DesignationTextBox.Text
                If EAN13TextBox.Text <> "" Then
                    Info = Info & " " & EAN13TextBox.Text
                End If
                If CABTextBox.Text <> "" And CABTextBox.Text <> EAN13TextBox.Text Then
                    Info = Info & " " & CABTextBox.Text
                End If
                Info = Info & Chr(10) & "ancien: " & produit.Stock.ToString & " nouveau: " & StockTextBox.Text
                BDD.Historique_ActionsTableAdapter.Insert(current_User.ID, Now, "Modification Stock", Info)
            End If
        End If
        Me.ProduitsTableAdapter.Set_Stock_Suivi(Stock_Suivi_CheckBox.Checked, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        Me.ProduitsTableAdapter.Set_conditionnement_trimestriel(Conditionnement_trimestrielCheckBox.Checked, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        Me.ProduitsTableAdapter.Set_TVA(Prixcontrol1.TVA, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        If PharmaML_CheckBox.Checked = False Then
            Me.ProduitsTableAdapter.Set_Code_PharmaML("", EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        ElseIf CIP_RadioButton.Checked = True Then
            Me.ProduitsTableAdapter.Set_Code_PharmaML(EAN13TextBox.Text, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        ElseIf CAB_RadioButton.Checked = True Then
            Me.ProduitsTableAdapter.Set_Code_PharmaML(CABTextBox.Text, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        End If
        Me.ProduitsTableAdapter.Set_Prestation(Code_Acte_ComboBox.Text, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        Me.ProduitsTableAdapter.Set_Notes(Notes_RichTextBox.Text, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)

        'LPP
        COMPTOIR_MAIN.KitsTableAdapter.Delete_by_Désignation(produit.Designation)
        If lpp_items.Count = 1 Then
            Dim Type_prestation = BDD.LPPTableAdapter.GetData_CodeLPP_Date(lpp_items(0).code, CInt(Format(Now, "yyyyMMdd"))).Item(0).Type_prestation
            Me.ProduitsTableAdapter.Set_LPP_Datas(False, lpp_items(0).code, Type_prestation, lpp_items(0).quantité, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        ElseIf LPP_codes_ComboBox.Items.Count > 1 Then
            Me.ProduitsTableAdapter.Set_LPP_Datas(True, "", "", 1, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
            For Each item In lpp_items
                COMPTOIR_MAIN.KitsTableAdapter.Insert("", produit.Designation, item.code, item.quantité)
            Next
        ElseIf LPP_codes_ComboBox.Items.Count = 0 Then
            Me.ProduitsTableAdapter.Set_LPP_Datas(False, "", "", 0, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        End If

        Me.ProduitsTableAdapter.Set_Info_Commande(AutoRéassort_CheckBox1.Checked, CInt(Seuil_Min_TextBox.Text), CInt(Seuil_Max_TextBox.Text), Répartiteur_principal_MyCombobox.Text, "", EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        Me.ProduitsTableAdapter.Set_préféré(préféré_CheckBox.Checked, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        Me.ProduitsTableAdapter.Set_robot(robot_CheckBox.Checked, EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
        Me.Close()
    End Sub




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

        recherche_en_cours = False
        Recherche_TextBox_Validated(Nothing, Nothing)

        Fournisseurs_ComboBox.Items.Clear()
        Dim fournisseurs = Commandes_PharmaML.FournisseurTableAdapter.GetData_OrderByNom
        For r = 0 To fournisseurs.Rows.Count - 1
            If fournisseurs.Item(r).URL <> "" Then
                Fournisseurs_ComboBox.Items.Add(fournisseurs.Item(r).Nom)
                Répartiteur_principal_MyCombobox.Items.Add(fournisseurs.Item(r).Nom)
            End If
        Next
        Code_Acte_ComboBox.Items.Clear()
        Dim code_actes = COMPTOIR_MAIN.CodePrestationsTableAdapter.GetData
        Code_Acte_ComboBox.Items.Add("")
        For r = 0 To code_actes.Rows.Count - 1
            Code_Acte_ComboBox.Items.Add(code_actes(r).Code)
        Next
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Dim myimport As New Import_Produit_From_Vidal
        myimport.TextBox1.Text = Recherche_TextBox.Text
        myimport.ShowDialog()

    End Sub




    Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        Création_produits_LPPR.Visible = True
        Création_produits_LPPR.BringToFront()
    End Sub

    Private Sub LinkLabel3_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel3.LinkClicked
        Création_produits_hors_nomenclature.Visible = True
        Création_produits_hors_nomenclature.BringToFront()
    End Sub


    Private Sub CIP_CAB_RadioButton_Click(sender As Object, e As EventArgs) Handles CIP_RadioButton.Click, CAB_RadioButton.Click

        PharmaML_CheckBox.Checked = True

    End Sub



    Private Sub PharmaML_CheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles PharmaML_CheckBox.CheckedChanged
        If PharmaML_CheckBox.Checked = False Then
            CIP_RadioButton.Checked = False
            CAB_RadioButton.Checked = False
        End If
    End Sub

    Private Sub LinkLabel4_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel4.LinkClicked
        Web_browser.Visible = True
        Web_browser.BringToFront()
        Dim Code_PharmaML As String = ""
        If PharmaML_CheckBox.Checked = False Then
            Code_PharmaML = ""
        ElseIf CIP_RadioButton.Checked = True Then
            Code_PharmaML = EAN13TextBox.Text
        ElseIf CAB_RadioButton.Checked = True Then
            Code_PharmaML = CABTextBox.Text
        End If
        Dim parameters As String = "&Désignation=" & DesignationTextBox.Text & "&CIP=" & EAN13TextBox.Text & "&Code_PharmaML=" & Code_PharmaML _
                                   & "&Début=" & Format(DateAdd(DateInterval.Month, -3, Now), "yyyy-MM-dd") & "T00:00:00" & "&Fin=" & Format(Now, "yyyy-MM-dd") & "T23:59:59"
        Web_browser.WebBrowser1.Navigate("http://" & Replace(Config.LocalNetwork_ServerName, "\", "") & "/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2fProduits%2fHistorique_achat_vente&rs:Command=Render" & parameters)

    End Sub



    Private Sub LPP_codes_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LPP_codes_ComboBox.SelectedIndexChanged
        If LPP_codes_ComboBox.SelectedItem Is Nothing Then Exit Sub
        If LPP_codes_ComboBox.SelectedItem.ToString = "" Then Exit Sub
        For Each item In lpp_items
            If item.code = LPP_codes_ComboBox.SelectedItem.ToString Then
                LPP_Qtité_TextBox.Text = item.quantité.ToString
                Dim LPP_datatable = COMPTOIR_MAIN.LPPTableAdapter.GetDataBy_CodeLPP(item.code)
                If LPP_datatable.Rows.Count > 0 Then
                    LPP_TextBox.Text = LPP_datatable.Item(0).Libellé
                Else
                    LPP_TextBox.Text = "CODE LPP INCONNU, génerera des erreurs en facturation"
                End If
                Exit For
            End If
        Next
    End Sub

    Private Sub LPP_Qtité_TextBox_TextChanged(sender As Object, e As EventArgs) Handles LPP_Qtité_TextBox.TextChanged
        If LPP_Qtité_TextBox.Text = "" Or LPP_Qtité_TextBox.Text = "0" Or LPP_codes_ComboBox.Items.Count = 0 Then Exit Sub
        Try
            CInt(LPP_Qtité_TextBox.Text).ToString()
        Catch ex As Exception
            MyMsg_Box.Presentation("Officine !", "numérique seulement", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End Try
        If Not lpp_items Is Nothing Then
            For Each item In lpp_items
                If item.code = LPP_codes_ComboBox.SelectedItem.ToString Then
                    lpp_items.Remove(item)
                    Exit For
                End If
            Next
            Dim new_item As lpp_item
            new_item.code = LPP_codes_ComboBox.SelectedItem.ToString
            new_item.quantité = CInt(LPP_Qtité_TextBox.Text)
            lpp_items.Add(new_item)
        End If
    End Sub










#Region "LPP AJOUT SUPPRESSION"
    Private Sub Ajouter_code_lpp_Button_Click(sender As Object, e As EventArgs) Handles Ajouter_code_lpp_Button.Click
        If DesignationTextBox.Text = "" Then Exit Sub

        Dim newlpp As String = InputBox("Saisir code LPP", "Ajout Code LPP")
        If newlpp = "" Then Exit Sub
        If BDD.LPPTableAdapter.GetData_CodeLPP_Date(newlpp, CInt(Format(Now, "yyyyMMdd"))).Rows.Count = 0 Then
            MyMsg_Box.Presentation("Officine", "Code LPP inconnu." & vbCrLf & "Création du code LPP?", True, "OUI", True, "NON", False, "")
            If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
                officine.LPP.ShowDialog()
                If BDD.LPPTableAdapter.GetData_CodeLPP_Date(newlpp, CInt(Format(Now, "yyyyMMdd"))).Rows.Count = 0 Then
                    MyMsg_Box.Presentation("Officine", "Impossible de renseigner un code qui n'a pas de valeur dans la base LPP." & vbCrLf & "Annulation", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If
            Else
                MyMsg_Box.Presentation("Officine", "Impossible de renseigner un code qui n'a pas de valeur dans la base LPP." & vbCrLf & "Annulation", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            End If
            Exit Sub
        End If
        For r = 0 To LPP_codes_ComboBox.Items.Count - 1
            If newlpp = LPP_codes_ComboBox.Items.Item(r).ToString Then
                MyMsg_Box.Presentation("Officine", newlpp & " déja attribué à ce produit." & vbCrLf & "Annulation", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
            End If
        Next
        Dim quantité_lpp = InputBox("Saisir quantité LPP", "Ajout Code LPP", "1")
        Try
            CInt(quantité_lpp).ToString()
        Catch ex As Exception
            MyMsg_Box.Presentation("Officine", "Quantité erronée." & vbCrLf & "Annulation", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End Try

        Dim lpp As lpp_item
        lpp.code = newlpp
        lpp.quantité = CInt(quantité_lpp).ToString
        lpp_items.Add(lpp)
        LPP_codes_ComboBox.Items.Clear()
        For Each item As lpp_item In lpp_items
            LPP_codes_ComboBox.Items.Add(item.code)
        Next
    End Sub

    Private Sub Supprimer_code_lpp_Button_Click(sender As Object, e As EventArgs) Handles Supprimer_code_lpp_Button.Click
        If LPP_codes_ComboBox.SelectedItem Is Nothing Then Exit Sub
        MyMsg_Box.Presentation("Officine", "Confirmez la suppression code " & LPP_codes_ComboBox.SelectedItem.ToString, True, "OUI", True, "NON", False, "")
        If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
            For Each item As lpp_item In lpp_items
                If item.code = LPP_codes_ComboBox.SelectedItem.ToString Then
                    lpp_items.Remove(item)
                    Exit For
                End If
            Next
            LPP_codes_ComboBox.Items.Clear()
            For Each item As lpp_item In lpp_items
                LPP_codes_ComboBox.Items.Add(item.code)
            Next
        End If
    End Sub

#End Region

    Private Sub Recherche_DataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles Recherche_DataGridView.CellContentClick

    End Sub



    Private Sub LinkLabel6_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel6.LinkClicked
        Prod_Histo_Prix_TFR.Afficher_Histo_Prix_Tfr(EAN13TextBox.Text, EAN13TextBox.Text)
    End Sub

    Private Sub LinkLabel7_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel7.LinkClicked
        Dim promo As New Promotions
        promo.intitulé_produit_TextBox.Text = DesignationTextBox.Text
        promo.CIP_TextBox.Text = EAN13TextBox.Text
        promo.CAB_TextBox.Text = CABTextBox.Text
        promo.PPTTC_TextBox.Text = Prixcontrol1.PV_TTC.ToString
        promo.Visible = True

    End Sub

    Private Sub LinkLabel8_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel8.LinkClicked
        Dim etiquette As Etiquettes_produits.etiquette
        etiquette.produit = DesignationTextBox.Text
        etiquette.PPTTC = Prixcontrol1.PV_TTC.ToString
        etiquette.Info = ""
        etiquette.quantité = 1
        If etiquettes Is Nothing Then
            etiquettes = New List(Of Etiquettes_produits.etiquette)
        End If
        etiquettes.Add(etiquette)

    End Sub

    Private Sub LinkLabel9_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel9.LinkClicked
        Etiquettes_produits.Visible = True
        Etiquettes_produits.BringToFront()
    End Sub

    Private Sub LinkLabel10_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel10.LinkClicked
        MyMsg_Box.Presentation("Suppression de produit?", "Voulez-vous supprimer le produit " & DesignationTextBox.Text & " ?", True, "OUI", True, "NON", False, "")
        If MyMsg_Box.ShowDialog = Windows.Forms.DialogResult.Yes Then
            If Not produit Is Nothing Then
                Dim Info As String
                Info = DesignationTextBox.Text
                If EAN13TextBox.Text <> "" Then
                    Info = Info & " " & EAN13TextBox.Text
                End If
                If CABTextBox.Text <> "" And CABTextBox.Text <> EAN13TextBox.Text Then
                    Info = Info & " " & CABTextBox.Text
                End If
                Info = Info & Chr(10) & "Stock: " & produit.Stock.ToString
                BDD.Historique_ActionsTableAdapter.Insert(current_User.ID, Now, "Suppression produit", Info)
            End If
            Me.ProduitsTableAdapter.Delete_Produit(EAN13TextBox.Text, CABTextBox.Text, DesignationTextBox.Text)
            Recherche_TextBox_Validated(Nothing, Nothing)

        End If
    End Sub


#Region "VIDAL"


    Private Sub VIDAL_Button_Click(sender As Object, e As EventArgs) Handles VIDAL_Button.Click
        If Not produit Is Nothing Then
            If Not produit.vidal_productId = 0 Then
                Dim psi As New ProcessStartInfo("http://vidal.fr/rest/redirect-product/id:" & produit.vidal_productId.ToString)
                psi.WindowStyle = ProcessWindowStyle.Maximized
                Process.Start(psi)
            End If
        End If

    End Sub
    Private Sub LinkLabel11_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel11.LinkClicked
        If Not produit Is Nothing Then
            If Not produit.vidal_productId = 0 Then
                Dim psi As New ProcessStartInfo("https://www.vidal.fr/rest/redirect-para/id:" & produit.vidal_productId.ToString)
                psi.WindowStyle = ProcessWindowStyle.Maximized
                Process.Start(psi)
            End If
        End If
    End Sub

    Private Sub LinkLabel12_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel12.LinkClicked
        If Not produit Is Nothing Then
            If Not produit.vidal_productId = 0 Then
                Dim psi As New ProcessStartInfo("https://www.vidal.fr/rest/getstars/news/id:" & produit.vidal_productId.ToString)
                psi.WindowStyle = ProcessWindowStyle.Maximized
                Process.Start(psi)
            End If
        End If
    End Sub
#End Region

    Private Sub Alias_Button_Click(sender As Object, e As EventArgs) Handles Alias_Button.Click
        Dim alias_ As New Produits_Alias
        alias_.DesignationTextBox.Text = produit.Designation
        alias_.CIP_TextBox.Text = produit.CIP
        alias_.EAN13TextBox.Text = produit.EAN13
        alias_.CABTextBox.Text = produit.CAB

        Dim aliastable = BDD.Produits_AliasTableAdapter.GetDataBy_all_optional_empty_string(produit.Designation, produit.CIP, produit.EAN13, produit.CAB, "")
        For r = 0 To aliastable.Rows.Count - 1
            alias_.DataGridView1.Rows.Add()
        Next
        For r = 0 To aliastable.Rows.Count - 1
            alias_.DataGridView1.Item(alias_.Alias_.Index, r).Value = aliastable(r)._Alias
        Next
        alias_.Visible = True
        alias_.BringToFront()

    End Sub



    Private Sub LinkLabel13_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel13.LinkClicked
        Messagerie_Interne.Close()
        Messagerie_Interne.Visible = True
        Messagerie_Interne.RadioButton2.Checked = True
        Messagerie_Interne.Text_RichTextBox.Text = "Produit à commander"
        If COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text <> "" Then
            Messagerie_Interne.Text_RichTextBox.Text = Messagerie_Interne.Text_RichTextBox.Text & vbCrLf & COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text
        End If
        If PharmaML_CheckBox.Checked = True Then
            Messagerie_Interne.PharmaML_CheckBox.Checked = True
            If CIP_RadioButton.Checked = True Then
                Messagerie_Interne.CodeProd_TextBox.Text = EAN13TextBox.Text
            ElseIf CAB_RadioButton.Checked = True Then
                Messagerie_Interne.CodeProd_TextBox.Text = CABTextBox.Text
            End If
        Else
            Messagerie_Interne.CodeProd_TextBox.Text = CABTextBox.Text
        End If
        Messagerie_Interne.Désignation_TextBox.Text = DesignationTextBox.Text
        Messagerie_Interne.Nouveau_Panel.BringToFront()

    End Sub

    Private Sub LinkLabel5_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel5.LinkClicked
        If produit Is Nothing Then
            Exit Sub
        End If
        If Fournisseurs_ComboBox.SelectedItem Is Nothing Then
            MyMsg_Box.Presentation("Officine ?", "Fournisseur?", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        Try
            CInt(Disp_Quantité_TextBox.Text).ToString()
        Catch ex As Exception
            Disp_Quantité_TextBox.Text = "1"
        End Try
        Commandes_PharmaML.Info_Produit(produit.CIP, produit.EAN13, produit.Designation, Fournisseurs_ComboBox.SelectedItem.ToString, produit.Code_PharmaML, CInt(Disp_Quantité_TextBox.Text))
    End Sub

    Private Sub Fournisseurs_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Fournisseurs_ComboBox.SelectedIndexChanged

    End Sub

    Private Sub Seuil_Min_TextBox_QueryContinueDrag(sender As Object, e As QueryContinueDragEventArgs) Handles Seuil_Min_TextBox.QueryContinueDrag

    End Sub

    Private Sub Seuil_Min_TextBox_TextChanged(sender As Object, e As EventArgs) Handles Seuil_Min_TextBox.TextChanged
        Try
            CInt(Seuil_Min_TextBox.Text).ToString()
        Catch ex As Exception
            Seuil_Min_TextBox.Text = 0
        End Try
    End Sub

    Private Sub Seuil_Max_TextBox_TextChanged(sender As Object, e As EventArgs) Handles Seuil_Max_TextBox.TextChanged
        Try
            CInt(Seuil_Max_TextBox.Text).ToString()
        Catch ex As Exception
            Seuil_Max_TextBox.Text = 0
        End Try
    End Sub





    Private Sub Recherche_TextBox_TextChanged(sender As Object, e As EventArgs) Handles Recherche_TextBox.TextChanged

    End Sub

    Private Sub Produits_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        round2(OK_Button)
        round2(Close_Button)

    End Sub

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

    Public Sub Peremption_Date_Min_control(ByVal CIP As String, ByVal CAB As String, ByVal Designation As String, ByVal Peremption_Date_Min_old As Date, ByVal Peremption_Date_Min_new As Date)
        Dim produit = BDD.ProduitsTableAdapter.GetDataBY_Cipean13_Or_Cab_Or_Designation(CIP, CAB, Designation).Item(0)
        If Peremption_Date_Min_new >= Peremption_Date_Min_old Then Exit Sub

    End Sub

    Public Structure Search_Product_Input
        Dim output_String As String
        Dim num_série As String
        Dim num_lot As String
        Dim Date_peremption As Date
        Dim input_String As String
        Dim Is_datamatrix As Boolean

        Public Sub clear()
            output_String = ""
            num_série = ""
            num_lot = "*"
            Date_peremption = Nothing
            Is_datamatrix = False
        End Sub

        Public Sub calcul_valeurs(ByVal warning_peremption_jours As Integer)
            clear()

            Dim Date_peremption_string = ""

            If Mid(input_String, 1, 2) = "01" And Mid(input_String, 17, 2) = "17" And Mid(input_String, 25, 2) = "10" Then
                Is_datamatrix = True
                num_lot = Mid(input_String, 27)
                Date_peremption_string = (Mid(input_String, 23, 2) & "/" & Mid(input_String, 21, 2) & "/" & "20" & Mid(input_String, 19, 2))

            ElseIf Mid(input_String, 1, 2) = "01" And Mid(input_String, 17, 2) = "11" And Mid(input_String, 25, 2) = "17" And Mid(input_String, 33, 2) = "10" Then
                Is_datamatrix = True
                num_lot = Mid(input_String, 35)
                Date_peremption_string = (Mid(input_String, 31, 2) & "/" & Mid(input_String, 29, 2) & "/" & "20" & Mid(input_String, 27, 2))

            ElseIf Mid(input_String, 1, 3) = "010" And input_String.Length >= 16 Then
                output_String = Mid(input_String, 4, 13)


            ElseIf IsNumeric(input_String) And input_String.Length > 13 Then
                output_String = Mid(input_String, 1, 13)
            Else
                output_String = input_String
            End If
            If Is_datamatrix = True Then
                If Date_peremption_string <> "" Then
                    While InStr(Date_peremption_string, "00/") <> 0
                        Date_peremption_string = Replace(Date_peremption_string, "00/", "01/")
                    End While
                    Date_peremption = Convert.ToDateTime(Date_peremption_string, Nothing)
                Else
                    Date_peremption = Nothing
                End If
                output_String = Mid(input_String, 3, 14)
                While InStr(output_String, "0") = 1
                    output_String = Mid(output_String, 2)
                End While
            Else
                num_lot = Nothing
                Date_peremption = Nothing
            End If

            If Date_peremption <> Nothing Then
                If Date_peremption.Subtract(Now).Days < warning_peremption_jours Then
                    MyMsg_Box.Presentation("Officine !", "DATE DE PEREMPTION" + Chr(10) + Date_peremption.ToLongDateString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If
            End If

        End Sub


        Public Sub Calcul_Peremption_Date_Min(ByVal CIP As String, ByVal EAN13 As String, ByVal CAB As String, ByVal Désignation As String, ByVal stock As Integer, ByVal Peremption_Date_Min_datamatrix As Date, ByVal Peremption_Date_Min_BDD As Date)
            If Peremption_Date_Min_datamatrix = Nothing Then Exit Sub

            If Peremption_Date_Min_datamatrix <> Peremption_Date_Min_BDD Then
                If Peremption_Date_Min_BDD = New Date(3000, 1, 1) Or stock <= 0 Then
                    BDD.ProduitsTableAdapter.Set_Peremption_Date_Min(Peremption_Date_Min_datamatrix.ToShortDateString, CIP, EAN13, CAB, Désignation)

                Else
                    MyMsg_Box.Presentation("Date de peremption", "La date de peremption du produit scanné (" & Peremption_Date_Min_datamatrix.ToShortDateString & _
                                           ")" & vbCrLf & "est différente de" & vbCrLf & "la date enregistrée pour le stock (" & Peremption_Date_Min_BDD.ToShortDateString & ")" & _
                                           vbCrLf & vbCrLf & "Voulez-vous modifier la date pour le stock ?", True, "Oui", True, "Non", False, "")
                    If MyMsg_Box.ShowDialog = Windows.Forms.DialogResult.Yes Then
                        BDD.ProduitsTableAdapter.Set_Peremption_Date_Min(Peremption_Date_Min_datamatrix.ToShortDateString, CIP, EAN13, CAB, Désignation)
                    End If
                End If
            End If

        End Sub

    End Structure



    Private Sub PCB_LinkLabel_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles PCB_LinkLabel.LinkClicked
        Dim codeprod = ""
        If CIP_RadioButton.Checked Then
            codeprod = EAN13TextBox.Text
        ElseIf CAB_RadioButton.Checked Then
            codeprod = CABTextBox.Text
        End If
        If codeprod <> "" Then
            Dim pcb As New Produits_PCB
            pcb.Produit_CodeLabel.Text = codeprod
            pcb.Produit_DesignationLabel.Text = DesignationTextBox.Text
            pcb.ShowDialog()
        End If
    End Sub
End Class