from AppliDef import *
from FrmInfoProdMat import CaractProd, InfoProd


def DeterminQProdACom(Q):
    ListQ = [5, 25, 50, 100, 250, 500, 1000, 2000, 2500, 5000]
    index = 0
    for i in range(len(ListQ)):
        if Q < ListQ[i]:
            break
        index = index + 1
    return ListQ[index]


def ChercheProd(Cur, ListChamp, Nom):
    ListProds = []
    try:
        Cur.execute("SELECT " + ListChamp + " FROM PRODUITS WHERE NOMS = '" + Nom + "' order by NOMS")
        ListProds = Cur.fetchall()
    except:
        Cur.execute('SELECT ' + ListChamp + ' FROM PRODUITS WHERE NOMS = \"%' + Nom + '%\" order by NOMS')
        ListProds = Cur.fetchall()
    finally:
        if len(ListProds) == 0:
            Cur.execute('SELECT ' + ListChamp + ' FROM PRODUITS WHERE NOMS LIKE \"%' + Nom + '%\" order by NOMS')
            ListProds = Cur.fetchall()
    return ListProds


def ChercheFour(Cur, ListChamp, Nom):
    ListFours = []
    try:
        Cur.execute("SELECT " + ListChamp + " FROM Fournisseurs WHERE NOM = '" + Nom + "' order by NOM")
        ListFours = Cur.fetchall()
    except:
        Cur.execute('SELECT ' + ListChamp + ' FROM Fournisseurs WHERE NOM = \"%' + Nom + '%\" order by NOM')
        ListFours = Cur.fetchall()
    finally:
        if len(ListFours) == 0:
            Cur.execute('SELECT ' + ListChamp + ' FROM Fournisseurs WHERE NOM LIKE \"%' + Nom + '%\" order by NOM')
            ListFours = Cur.fetchall()
    return ListFours


class FrmCommandProd(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.TabProdACom = None
        self.BtnPlus = None
        self.FrmAjoutProdACom = None
        self.ListProdACom = []
        self.ListNomsProdACom = []
        self.ListProduits = []
        self.MenuClicDroitTabProdACom = []
        self.MenuClicDroitTabProdAComAnnul = []
        self.ListProdAComAnnul = []
        self.ListTabProdACOM = []
        self.ListComDelay = []
        self.MenuClicDroitTabComDelay = []
        self.ListProdComDelay = []
        self.TabComDelay = None
        self.FrmBonCom = None
        self.LineSelect = 0
        self.AffichList = ['Produits chimiques à commander', 'Produits chimiques à commander en attente de validation',
                           'Commandes de produits chimiques en attente de livraison',
                           'Récapitulatif annuel des commandes de produits chimiques',
                           'Récapitulatif annuel des quantités de produits chimiques commandés']
        self.AnneeListe = []
        self.AnneeListe.append(str(datetime.now().date().year))
        self.StringAnnee = tk.StringVar()
        self.AnneeSelect = self.AnneeListe[0]
        self.ListAnnee = None
        self.BonComAnnuel = []
        self.TabRecapComAnnuel = None
        self.TotalTTC = 0
        self.labelValTotal = None
        self.MenuClicDroitTabRecapComAnnuel = []
        self.ListProdRecapCom = []
        self.TabRecapQComAnnuel = None
        self.EntryManuelVal = None
        self.LCell = []
        self.ListModif = []
        self.ImgBtnRetour, self.CanvasBtnRetour, self.ImgCanvasBtnRetour = None, None, None
        self.CoefSecu = float(self.MainAppli.CoeffSecuProd.replace(',', '.'))
        self.TVA = float(1 + float(self.MainAppli.TVA.replace(',', '.')) / 100)

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAjout/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        coefY = float(ConfigResolution(self.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.curSave))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAjout/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAjout/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmCommandProd)

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, 'Commandes de produits chimiques', '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

        self.SelectAffich = tk.StringVar()
        self.SelectAffich.set(self.AffichList[0])
        self.ListSelectAffich = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.033),
                                                textvariable=self.SelectAffich, values=self.AffichList)
        self.CanvasFrmFond.create_window(int(self.SX * 0.975), int(self.SY * coefY), anchor=tk.NE,
                                         window=self.ListSelectAffich)

        self.ListSelectAffich.bind('<<ComboboxSelected>>', self.AffichSelection)

        self.CanvasMenu = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.995),
                                     int(self.SY * 0.965), int(self.SX * 0.003), int(self.SY * 0.031), tk.NW)

        self.AffichTabProdACom(0)

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.CanvasFrmFond.pack()

    def AffichSelection(self, _):
        Index = self.AffichList.index(self.SelectAffich.get())
        if Index == 0:
            self.AffichTabProdACom(Index)
        elif Index == 1:
            self.AffichTabProdAComDelay(Index)
        elif Index == 2:
            self.AffichTabComDelay(Index)
        elif Index == 3:
            self.AffichTabRecapCom(Index)
        elif Index == 4:
            self.AffichTabRecapQCom(Index)

    def AffichTabProdACom(self, Index):
        self.EffaceMenu()

        LabelInCanvas(self.CanvasMenu.CanvasMenu, self.AffichList[Index], '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)
        self.ListProdACom = []
        self.ListNomsProdACom = []

        self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabProd + " from PRODUITS order by NOMS")
        self.ListProduits = self.MainAppli.cur.fetchall()

        for i in range(len(self.ListProduits)):
            if self.ListProduits[i][23] != '' and self.ListProduits[i][23] is not None:
                self.ListProdACom.append(self.ListProduits[i])
                self.ListNomsProdACom.append(self.ListProduits[i][0])
            elif self.ListProduits[i][19] != '' and self.ListProduits[i][19] is not None and \
                    self.ListProduits[i][24] != 'OUI' and (self.ListProduits[i][25] == '' or
                                                           self.ListProduits[i][25] is None):
                if float(self.ListProduits[i][18].replace(',', '.')) < float(
                        self.ListProduits[i][19].replace(',', '.')) * self.CoefSecu:
                    self.ListProdACom.append(self.ListProduits[i])
                    self.ListNomsProdACom.append(self.ListProduits[i][0])

        self.LCell = [0.05, 0.01, 0.01, 0.01, 0.008, 0.01, 0.008, 0.01]
        self.TabProdACom = Tableau(self.CanvasMenu.CanvasMenu, len(self.ListProdACom), 8,
                                   ['Désignation', 'Fournisseur', 'Référence', 'Conditionnement', 'Unité de mesure',
                                    'Prix unitaire HT (€)', 'Quantité', 'Prix total HT (€)'], self.LCell,
                                   AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                   AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)

        self.FillTabProdACOM(self.ListProdACom)

        self.ListTabProdACOM = [["", "", "", "", "", "", "", ""]]
        self.MenuClicDroitTabProdACom = []
        for r in range(len(self.ListProdACom)):
            ListMenu = []
            for i in range(8):
                ListMenu.append(tk.Menu(self.TabProdACom.TabLabels[r][i], tearoff=0))
                self.ListTabProdACOM[r][i] = self.TabProdACom.TabLabels[r][i]['text']

                def GestEvt(evt, j=r):
                    return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabProdACom, j)

                self.TabProdACom.TabLabels[r][i].bind("<Button-3>", GestEvt)
            self.MenuClicDroitTabProdACom.append(ListMenu)
            self.ListTabProdACOM.append(["", "", "", "", "", "", "", ""])

        for r in range(self.TabProdACom.NLine):
            self.MenuClicDroitTabProdACom[r][0].add_command(label="Modifier la commande du produit chimique",
                                                            command=self.ModifProdACom)
            self.MenuClicDroitTabProdACom[r][0].add_command(label="Supprimer le produit chimique de la commande",
                                                            command=self.SupProdACom)
            self.MenuClicDroitTabProdACom[r][0].add_separator()
            self.MenuClicDroitTabProdACom[r][0].add_command(label="Editer un bon de commande", command=self.EditBonCom)
            self.MenuClicDroitTabProdACom[r][0].add_command(label="Editer une demande de devis",
                                                            command=self.EditDevis)

        self.BtnPlus = BtnAction(self.CanvasFrmFond, int(self.SX * 0.985), int(self.SY * 0.044), self.RatioX * 0.52,
                                 self.RatioX * 0.52, 'Media/FrmConsomProd/BtnPlus/')
        self.BtnPlus.CanvasBtn.bind('<ButtonRelease-1>', self.AjoutProdACom)

        for l in range(self.TabProdACom.NLine):
            for k in range(self.TabProdACom.NCol):
                def GestEvt(evt, Line=l, Col=k):
                    return self.ModifVal(evt, Line, Col)

                def GestEvt2(evt):
                    return self.AnnulModifVal(evt)

                self.TabProdACom.TabLabels[l][k].bind('<Double-1>', GestEvt)
                self.TabProdACom.TabLabels[l][k].bind('<Button-1>', GestEvt2)

        if len(self.ListProdACom) > 0:
            for C in range(self.TabProdACom.NCol):
                def GestEvt3(evt):
                    return self.AnnulModifVal(evt)

                self.TabProdACom.TabLabelNCol[C].bind('<Button-1>', GestEvt3)

        self.CanvasFrmFond.bind("<Button-1>", self.AnnulModifVal)
        self.CanvasMenu.CanvasMenu.bind("<Button-1>", self.AnnulModifVal)
        self.TabProdACom.scrollable_canvas.interior.bind("<Button-1>", self.AnnulModifVal)
        self.TabProdACom.scrollable_canvas.bind("<Button-1>", self.AnnulModifVal)

    def ActionBtnAnnulPress(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[2])

    def ActionAnnul(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[1])
        self.TabProdACom.TabLabels[self.ListModif[-1][0]][self.ListModif[-1][1]]['text'] = self.ListModif[-1][2]
        if self.ListModif[-1][1] == 5 or self.ListModif[-1][1] == 6:
            try:
                Ptotal = int(self.TabProdACom.TabLabels[self.ListModif[-1][0]][6]['text']) * \
                         float(self.TabProdACom.TabLabels[self.ListModif[-1][0]][5]['text'].replace(',', '.'))
                self.TabProdACom.TabLabels[self.ListModif[-1][0]][7]['text'] = ("%.2f" % Ptotal).replace('.', ',')
            except:
                self.TabProdACom.TabLabels[self.ListModif[-1][0]][7]['text'] = '?'
            self.ListTabProdACOM[self.ListModif[-1][0]][self.ListModif[-1][1]] = \
                self.TabProdACom.TabLabels[self.ListModif[-1][0]][self.ListModif[-1][1]]['text']
            self.ListTabProdACOM[self.ListModif[-1][0]][7] = \
                self.TabProdACom.TabLabels[self.ListModif[-1][0]][7]['text']
        self.SaveModifVal(self.ListModif[-1][0], self.ListModif[-1][1])
        del self.ListModif[-1]
        if len(self.ListModif) == 0:
            self.CanvasBtnRetour.destroy()
            self.CanvasBtnRetour = None

    def AjoutProdACom(self, _):
        self.ActionAjoutProdACom(0)

    def ActionAjoutProdACom(self, N):
        self.FrmAjoutProdACom = FrmAjoutProdACom(self.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY, N, self)

    def ModifProdACom(self):
        self.ActionAjoutProdACom(1)
        self.FrmAjoutProdACom.EntryProd.Data.set(self.TabProdACom.TabLabels[self.LineSelect][0]['text'])
        self.FrmAjoutProdACom.ActionModifProd()

    def SupProdACom(self):
        Prod = self.TabProdACom.TabLabels[self.LineSelect][0]['text']
        if self.ListProdACom[self.LineSelect][23] != '' and self.ListProdACom[self.LineSelect][23] is not None:
            self.MainAppli.cur.execute("UPDATE PRODUITS SET QCOM ='' WHERE NOMS='" + Prod + "'")
        else:
            self.MainAppli.cur.execute("UPDATE PRODUITS SET QCOMANNUL ='OUI' WHERE NOMS='" + Prod + "'")
        self.MainAppli.DataBaseChimie.commit()
        self.MainAppli.SaveListModifDTB('Chimie', 'Suppression produit chimique à commander - ' + Prod)
        self.AffichTabProdACom(0)

    def EditBonCom(self):
        if self.TabProdACom.TabLabels[self.LineSelect][1]['text'] != '' \
                and self.TabProdACom.TabLabels[self.LineSelect][1]['text'] != '?':
            self.FrmBonCom = FrmBonCom(self.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY, self.ListTabProdACOM,
                                       self.TabProdACom.TabLabels[self.LineSelect][1]['text'], 1, self)
        else:
            tkMB.showwarning('Attention', "Veuillez indiquer le fournisseur du produit", parent=self)

    def EditDevis(self):
        self.FrmBonCom = FrmBonCom(self.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY, self.ListTabProdACOM,
                                   self.TabProdACom.TabLabels[self.LineSelect][1]['text'], 4, self)

    def AffichMenuClicDroit(self, event, MenuClicDroitTab, j):
        MenuClicDroitTab[j][0].post(event.x_root, event.y_root)
        self.LineSelect = j

    def AffichTabProdAComDelay(self, Index):
        self.EffaceMenu()
        LabelInCanvas(self.CanvasMenu.CanvasMenu, self.AffichList[Index], '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)

        self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabProd + " from PRODUITS order by NOMS")
        self.ListProduits = self.MainAppli.cur.fetchall()

        self.ListProdAComAnnul = []

        for i in range(len(self.ListProduits)):
            if self.ListProduits[i][24] == 'OUI':
                self.ListProdAComAnnul.append(self.ListProduits[i])

        self.TabProdACom = Tableau(self.CanvasMenu.CanvasMenu, len(self.ListProdAComAnnul), 8,
                                   ['Désignation', 'Fournisseur', 'Référence', 'Conditionnement', 'Unité de mesure',
                                    'Prix unitaire HT (€]', 'Quantité', 'Prix total HT (€)'],
                                   [0.05, 0.01, 0.01, 0.01, 0.008, 0.01, 0.008, 0.01],
                                   AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                   AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)
        self.FillTabProdACOM(self.ListProdAComAnnul)

        self.MenuClicDroitTabProdAComAnnul = []
        for r in range(len(self.ListProdAComAnnul)):
            ListMenu = []
            for i in range(8):
                ListMenu.append(tk.Menu(self.TabProdACom.TabLabels[r][i], tearoff=0))

                def GestEvt(evt, j=r):
                    return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabProdAComAnnul, j)

                self.TabProdACom.TabLabels[r][i].bind("<Button-3>", GestEvt)
            self.MenuClicDroitTabProdAComAnnul.append(ListMenu)

        for r in range(self.TabProdACom.NLine):
            self.MenuClicDroitTabProdAComAnnul[r][0].add_command(label="Valider la commande du produit chimique",
                                                                 command=self.ValidProdACom)
            self.MenuClicDroitTabProdAComAnnul[r][0].add_separator()
            self.MenuClicDroitTabProdAComAnnul[r][0].add_command(label="Supprimer le produit chimique en attente de "
                                                                       "validation", command=self.SupProdAComDelay)

    def ValidProdACom(self):
        Prod = self.TabProdACom.TabLabels[self.LineSelect][0]['text']
        self.MainAppli.cur.execute("UPDATE PRODUITS SET QCOMANNUL ='' WHERE NOMS='" + Prod + "'")
        self.MainAppli.DataBaseChimie.commit()
        self.MainAppli.SaveListModifDTB('Chimie', 'Validation produit chimique à commander - ' + Prod)
        self.AffichTabProdAComDelay(1)

    def SupProdAComDelay(self):
        Prod = self.TabProdACom.TabLabels[self.LineSelect][0]['text']
        self.MainAppli.cur.execute("UPDATE PRODUITS SET QUTIL ='' WHERE NOMS='" + Prod + "'")
        self.MainAppli.DataBaseChimie.commit()
        self.MainAppli.SaveListModifDTB('Chimie', 'Suppression produit chimique à commander en attente de validation - '
                                        + Prod)
        self.ValidProdACom()

    def FillTabProdACOM(self, List):
        ListIndex = [9, 20, 21, 1, 22]
        for i in range(len(List)):
            self.TabProdACom.TabLabels[i][0]['text'] = List[i][0]
            for j in range(5):
                if List[i][ListIndex[j]] != '' and List[i][ListIndex[j]] is not None:
                    self.TabProdACom.TabLabels[i][j + 1]['text'] = List[i][ListIndex[j]]
                    if j == 4:
                        try:
                            self.TabProdACom.TabLabels[i][j + 1]['text'] = (
                                        "%.2f" % float(List[i][ListIndex[j]].replace(
                                    ',', '.'))).replace('.', ',')
                        except:
                            self.TabProdACom.TabLabels[i][j + 1]['text'] = '?'
                else:
                    self.TabProdACom.TabLabels[i][j + 1]['text'] = '?'
            if List[i][23] != '' and List[i][23] is not None:
                if List[i][21] != '' and List[i][21] is not None and List[i][21] != '?':
                    self.TabProdACom.TabLabels[i][6]['text'] = str(int(float(List[i][23]) / float(List[i][21])))
                    try:
                        Ptotal = int(self.TabProdACom.TabLabels[i][6]['text']) * float(
                            self.TabProdACom.TabLabels[i][5]['text'].replace(',', '.'))
                        self.TabProdACom.TabLabels[i][7]['text'] = ("%.2f" % Ptotal).replace('.', ',')
                    except:
                        self.TabProdACom.TabLabels[i][7]['text'] = '?'
                else:
                    self.TabProdACom.TabLabels[i][6]['text'] = List[i][23] + " " + List[i][1]
                    self.TabProdACom.TabLabels[i][7]['text'] = '?'
            elif self.TabProdACom.TabLabels[i][1]['text'] != '?':
                if List[i][21] != '' and List[i][21] is not None:
                    self.TabProdACom.TabLabels[i][6]['text'] = str(
                        int((float(List[i][19].replace(',', '.')) * self.CoefSecu -
                             float(List[i][18].replace(',', '.'))) / float(
                            List[i][21])) + 1)
                    try:
                        Ptotal = int(self.TabProdACom.TabLabels[i][6]['text']) * float(
                            self.TabProdACom.TabLabels[i][5]['text'].replace(',', '.'))
                        self.TabProdACom.TabLabels[i][7]['text'] = ("%.2f" % Ptotal).replace('.', ',')
                    except:
                        self.TabProdACom.TabLabels[i][7]['text'] = '?'
                else:
                    QProdACom = DeterminQProdACom(int(
                        float(List[i][19].replace(',', '.')) * self.CoefSecu -
                        float(List[i][18].replace(',', '.'))))
                    self.TabProdACom.TabLabels[i][6]['text'] = str(QProdACom) + " " + List[i][1]
                    self.TabProdACom.TabLabels[i][7]['text'] = '?'
            else:
                QProdACom = DeterminQProdACom(int(
                    float(List[i][19].replace(',', '.')) * self.CoefSecu -
                    float(List[i][18].replace(',', '.'))))
                self.TabProdACom.TabLabels[i][6]['text'] = str(QProdACom) + " " + List[i][1]
                self.TabProdACom.TabLabels[i][7]['text'] = '?'

    def AffichTabComDelay(self, Index):
        self.EffaceMenu()
        LabelInCanvas(self.CanvasMenu.CanvasMenu, self.AffichList[Index], '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)

        self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabBonComProd +
                                   " from BONSCOMMANDEPRODUITS WHERE CLOTURE = 'NON' order by NBON")
        self.ListComDelay = self.MainAppli.cur.fetchall()
        ListNBonComDelay = []
        for i in range(len(self.ListComDelay)):
            if self.ListComDelay[i][0] not in ListNBonComDelay:
                ListNBonComDelay.append(self.ListComDelay[i][0])

        self.TabComDelay = Tableau(self.CanvasMenu.CanvasMenu, len(ListNBonComDelay), 5,
                                   ['Numéro de bon', 'Date', 'Fournisseur', 'Nombre de produits \n commandés',
                                    'Prix total TTC (€)'], [0.015, 0.015, 0.015, 0.015, 0.015],
                                   AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                   AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)

        for j in range(len(ListNBonComDelay)):
            for i in range(len(self.ListComDelay)):
                if self.ListComDelay[i][0] == ListNBonComDelay[j]:
                    self.TabComDelay.TabLabels[j][0]['text'] = self.ListComDelay[i][0]
                    self.TabComDelay.TabLabels[j][1]['text'] = FormatDate(self.ListComDelay[i][1])
                    self.TabComDelay.TabLabels[j][2]['text'] = self.ListComDelay[i][2]
                    self.TabComDelay.TabLabels[j][3]['text'] = self.ListComDelay[i][3]
                    Ptotal = (float(self.ListComDelay[i][4].replace(',', '.')) +
                              float(self.ListComDelay[i][5].replace(',', '.'))) * self.TVA
                    self.TabComDelay.TabLabels[j][4]['text'] = ("%.2f" % Ptotal).replace('.', ',')
                    break

        self.MenuClicDroitTabComDelay = []
        for r in range(self.TabComDelay.NLine):
            ListMenu = []
            for i in range(5):
                ListMenu.append(tk.Menu(self.TabComDelay.TabLabels[r][i], tearoff=0))

                def GestEvt(evt, k=r):
                    return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabComDelay, k)

                def GestEvt2(evt, k=r):
                    return self.ActionAffichBonComDelay(evt, k)

                self.TabComDelay.TabLabels[r][i].bind("<Button-3>", GestEvt)
                self.TabComDelay.TabLabels[r][i].bind("<Double-1>", GestEvt2)
            self.MenuClicDroitTabComDelay.append(ListMenu)

        for r in range(self.TabComDelay.NLine):
            self.MenuClicDroitTabComDelay[r][0].add_command(label="Visualiser le bon de commande",
                                                            command=self.AffichBonComDelay)
            self.MenuClicDroitTabComDelay[r][0].add_separator()
            self.MenuClicDroitTabComDelay[r][0].add_command(label="Supprimer le bon de commande",
                                                            command=self.SupBonComDelay)

    def ActionAffichBonComDelay(self, _, k):
        self.LineSelect = k
        self.AffichBonComDelay()

    def AffichBonComDelay(self):
        self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabBonComProd +
                                   " from BONSCOMMANDEPRODUITS WHERE NBON = '" +
                                   self.TabComDelay.TabLabels[self.LineSelect][0]['text'] + "' order by PRODUIT")
        self.ListProdComDelay = self.MainAppli.cur.fetchall()

        self.FrmBonCom = FrmBonCom(self.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY, self.ListProdComDelay,
                                   self.TabComDelay.TabLabels[self.LineSelect][2]['text'], 2, self)

    def SupBonComDelay(self):
        Rep = tkMB.askyesno('Attention', 'Voulez-vous supprimer le bon de commande "' +
                            self.TabComDelay.TabLabels[self.LineSelect][0]['text'] +
                            '" en attente de livraison?', parent=self)
        if Rep:
            self.MainAppli.cur.execute("SELECT PRODUIT FROM BONSCOMMANDEPRODUITS WHERE NBON='" +
                                       self.TabComDelay.TabLabels[self.LineSelect][0]['text'] + "'")
            ListProd = self.MainAppli.cur.fetchall()
            for i in range(len(ListProd)):
                self.MainAppli.cur.execute("UPDATE PRODUITS SET QenCOM ='' WHERE NOMS='" + ListProd[i][0] + "'")
            self.MainAppli.cur.execute("DELETE FROM BONSCOMMANDEPRODUITS WHERE NBON='" +
                                       self.TabComDelay.TabLabels[self.LineSelect][0]['text'] + "'")
            self.MainAppli.DataBaseChimie.commit()
            self.MainAppli.SaveListModifDTB('Chimie', 'Suppression bon de commande - '
                                            + self.TabComDelay.TabLabels[self.LineSelect][0]['text'])
            self.AffichTabComDelay(2)

    def AffichTabRecapCom(self, Index):
        self.EffaceMenu()
        LabelInCanvas(self.CanvasMenu.CanvasMenu, self.AffichList[Index], '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)

        self.MainAppli.cur.execute("SELECT NBON, DATE, FOURNISSEUR, NBRPROD, PRIXTOTCOM, FRAISPORT "
                                   "FROM BONSCOMMANDEPRODUITS WHERE CLOTURE = 'OUI' order by NBON")
        ListBonCom = self.MainAppli.cur.fetchall()

        self.AnneeListe = []
        self.AnneeListe.append(str(datetime.now().date().year))
        for i in range(len(ListBonCom)):
            if ListBonCom[i][0][0:4] not in self.AnneeListe:
                self.AnneeListe.append(ListBonCom[i][0][0:4])
        self.AnneeListe.sort()

        self.ListAnnee = ListeDeroulante(self.CanvasMenu.CanvasMenu,
                                         int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                                         textvariable=self.StringAnnee, values=self.AnneeListe)
        self.CanvasMenu.CanvasMenu.create_window(int(int(self.CanvasMenu.CanvasMenu['width']) * 0.978),
                                                 int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004),
                                                 anchor=tk.NE,
                                                 window=self.ListAnnee)
        self.ListAnnee.bind('<<ComboboxSelected>>', self.SelectAnnee)
        self.StringAnnee.set(self.AnneeSelect)

        self.BonComAnnuel = []
        for i in range(len(ListBonCom)):
            if ListBonCom[i][0][0:4] == self.StringAnnee.get() and ListBonCom[i] not in self.BonComAnnuel:
                self.BonComAnnuel.append(ListBonCom[i])

        self.TabRecapComAnnuel = Tableau(self.CanvasMenu.CanvasMenu, len(self.BonComAnnuel), 5,
                                         ['Numéro de bon', 'Date', 'Fournisseur', 'Nombre de produits \n commandés',
                                          'Prix total TTC (€)'], [0.015, 0.015, 0.015, 0.015, 0.015],
                                         AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                         AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)

        self.TotalTTC = 0
        for i in range(len(self.BonComAnnuel)):
            for j in range(4):
                if j == 1:
                    self.TabRecapComAnnuel.TabLabels[i][j]['text'] = FormatDate(self.BonComAnnuel[i][j])
                else:
                    self.TabRecapComAnnuel.TabLabels[i][j]['text'] = self.BonComAnnuel[i][j]
            if self.BonComAnnuel[i][5] != '' and self.BonComAnnuel[i][5] is not None:
                Ptotal = (float(self.BonComAnnuel[i][4].replace(',', '.')) +
                          float(self.BonComAnnuel[i][5].replace(',', '.'))) * self.TVA
            else:
                Ptotal = float(self.BonComAnnuel[i][4].replace(',', '.')) * self.TVA
            self.TotalTTC = self.TotalTTC + Ptotal
            self.TabRecapComAnnuel.TabLabels[i][4]['text'] = ("%.2f" % Ptotal).replace('.', ',')

        if len(self.BonComAnnuel) > 0:
            labelEspace = tk.Label(self.TabRecapComAnnuel.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                   width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.015), bg='white',
                                   font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            labelEspace.grid(row=self.TabRecapComAnnuel.NLine + 1, column=3)
            labelEspace2 = tk.Label(self.TabRecapComAnnuel.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                    width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.015), bg='white',
                                    font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            labelEspace2.grid(row=self.TabRecapComAnnuel.NLine + 1, column=4)

            labelTitreTotal = tk.Label(self.TabRecapComAnnuel.scrollable_canvas.interior, text='TOTAL TTC ANNUEL (€)',
                                       relief=tk.RIDGE,
                                       width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.015), bg='white',
                                       font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            labelTitreTotal.grid(row=self.TabRecapComAnnuel.NLine + 2, column=3)
            self.labelValTotal = tk.Label(self.TabRecapComAnnuel.scrollable_canvas.interior,
                                          text=("%.2f" % self.TotalTTC).replace('.', ','), relief=tk.RIDGE,
                                          width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.015), bg='white',
                                          font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0))
            self.labelValTotal.grid(row=self.TabRecapComAnnuel.NLine + 2, column=4)

        self.MenuClicDroitTabRecapComAnnuel = []
        for r in range(self.TabRecapComAnnuel.NLine):
            ListMenu = []
            for i in range(5):
                ListMenu.append(tk.Menu(self.TabRecapComAnnuel.TabLabels[r][i], tearoff=0))

                def GestEvt(evt, k=r):
                    return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabRecapComAnnuel, k)

                def GestEvt2(evt, k=r):
                    return self.ActionAffichBonComRecap(evt, k)

                self.TabRecapComAnnuel.TabLabels[r][i].bind("<Button-3>", GestEvt)
                self.TabRecapComAnnuel.TabLabels[r][i].bind("<Double-1>", GestEvt2)
            self.MenuClicDroitTabRecapComAnnuel.append(ListMenu)

        for r in range(self.TabRecapComAnnuel.NLine):
            self.MenuClicDroitTabRecapComAnnuel[r][0].add_command(label="Visualiser le bon de commande",
                                                                  command=self.AffichBonComRecap)

    def SelectAnnee(self, _):
        self.AnneeSelect = self.StringAnnee.get()
        self.AffichTabRecapCom(3)

    def ActionAffichBonComRecap(self, _, k):
        self.LineSelect = k
        self.AffichBonComRecap()

    def AffichBonComRecap(self):
        self.MainAppli.cur.execute("select " + self.MainAppli.ListChampsTabBonComProd +
                                   " from BONSCOMMANDEPRODUITS WHERE NBON = '" +
                                   self.TabRecapComAnnuel.TabLabels[self.LineSelect][0]['text'] + "' order by PRODUIT")
        self.ListProdRecapCom = self.MainAppli.cur.fetchall()

        self.FrmBonCom = FrmBonCom(self.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY, self.ListProdRecapCom,
                                   self.TabRecapComAnnuel.TabLabels[self.LineSelect][2]['text'], 3, self)

    def AffichTabRecapQCom(self, Index):
        self.EffaceMenu()
        LabelInCanvas(self.CanvasMenu.CanvasMenu, self.AffichList[Index], '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004), tk.NW)

        self.MainAppli.cur.execute(
            "SELECT NBON, PRODUIT, COND, QUANTITE FROM BONSCOMMANDEPRODUITS WHERE CLOTURE = 'OUI' order by NBON")
        ListBonCom = self.MainAppli.cur.fetchall()

        self.AnneeListe = []
        self.AnneeListe.append(str(datetime.now().date().year))
        for i in range(len(ListBonCom)):
            if ListBonCom[i][0][0:4] not in self.AnneeListe:
                self.AnneeListe.append(ListBonCom[i][0][0:4])
        self.AnneeListe.sort()

        self.ListAnnee = ListeDeroulante(self.CanvasMenu.CanvasMenu,
                                         int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01),
                                         textvariable=self.StringAnnee, values=self.AnneeListe)
        self.CanvasMenu.CanvasMenu.create_window(int(int(self.CanvasMenu.CanvasMenu['width']) * 0.978),
                                                 int(int(self.CanvasMenu.CanvasMenu['height']) * 0.004),
                                                 anchor=tk.NE,
                                                 window=self.ListAnnee)
        self.ListAnnee.bind('<<ComboboxSelected>>', self.SelectAnnee2)
        self.StringAnnee.set(self.AnneeSelect)

        self.BonComAnnuel = []
        for i in range(len(ListBonCom)):
            if ListBonCom[i][0][0:4] == self.AnneeSelect:
                self.BonComAnnuel.append(ListBonCom[i])

        self.TabRecapQComAnnuel = Tableau(self.CanvasMenu.CanvasMenu, len(self.BonComAnnuel), 3,
                                          ['Produits', 'Quantité', 'Unité de mesure'], [0.05, 0.015, 0.015],
                                          AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                          AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)

        for i in range(len(self.BonComAnnuel)):
            self.TabRecapQComAnnuel.TabLabels[i][0]['text'] = self.BonComAnnuel[i][1]
            CondUnit = self.BonComAnnuel[i][2].split(' ')
            self.TabRecapQComAnnuel.TabLabels[i][1]['text'] = str(int(CondUnit[0]) * int(self.BonComAnnuel[i][3]))
            self.TabRecapQComAnnuel.TabLabels[i][2]['text'] = CondUnit[1]

    def SelectAnnee2(self, _):
        self.AnneeSelect = self.StringAnnee.get()
        self.AffichTabRecapQCom(4)

    def EffaceMenu(self):
        self.ListModif = []
        for widget in self.CanvasMenu.CanvasMenu.winfo_children():
            widget.destroy()
        if self.BtnPlus is not None:
            self.BtnPlus.CanvasBtn.destroy()
            self.BtnPlus = None
        if self.CanvasBtnRetour is not None:
            self.CanvasBtnRetour.destroy()
            self.CanvasBtnRetour = None

    def ModifVal(self, _, i, j):
        if j != 0 and j != 7 and self.EntryManuelVal is None:
            self.EntryManuelVal = tk.Entry(self.TabProdACom.scrollable_canvas.interior, text='',
                                           width=int(int(self.CanvasMenu.CanvasMenu['width']) * self.LCell[j]),
                                           font=AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                           justify='right')
            self.EntryManuelVal.grid(row=i + 1, column=j)
            self.EntryManuelVal.insert(0, self.TabProdACom.TabLabels[i][j]['text'])
            self.EntryManuelVal.focus_set()

            def GestEvt(evt):
                return self.ValidModifVal(evt, i, j)

            self.EntryManuelVal.bind('<Return>', GestEvt)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ValidModifVal(self, _, i, j):
        OldVal = self.TabProdACom.TabLabels[i][j]['text']
        if self.EntryManuelVal.get() != '':
            self.TabProdACom.TabLabels[i][j]['text'] = self.EntryManuelVal.get()
            self.ListTabProdACOM[i][j] = self.TabProdACom.TabLabels[i][j]['text']
            if j == 5 or j == 6:
                try:
                    if j == 5:
                        self.TabProdACom.TabLabels[i][j]['text'] = ("%.2f" % float(
                            self.TabProdACom.TabLabels[i][j]['text'].replace(',', '.'))).replace('.', ',')
                    else:
                        int(self.EntryManuelVal.get())
                    try:
                        Ptotal = int(self.TabProdACom.TabLabels[i][6]['text']) * \
                                 float(self.TabProdACom.TabLabels[i][5]['text'].replace(',', '.'))
                        self.TabProdACom.TabLabels[i][7]['text'] = ("%.2f" % Ptotal).replace('.', ',')
                    except:
                        self.TabProdACom.TabLabels[i][7]['text'] = '?'
                    self.ListTabProdACOM[i][7] = self.TabProdACom.TabLabels[i][7]['text']
                    self.ListTabProdACOM[i][j] = self.TabProdACom.TabLabels[i][j]['text']
                except:
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabProdACom.TabLabels[i][j]['text'] = OldVal
                    self.ListTabProdACOM[i][j] = self.TabProdACom.TabLabels[i][j]['text']
            elif j == 3:
                try:
                    int(self.EntryManuelVal.get())
                except:
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabProdACom.TabLabels[i][j]['text'] = OldVal
                    self.ListTabProdACOM[i][j] = self.TabProdACom.TabLabels[i][j]['text']
            elif j == 4:
                if self.EntryManuelVal.get() != "g" and self.EntryManuelVal.get() != "mL" and \
                        self.EntryManuelVal.get().upper() != "UNIT":
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabProdACom.TabLabels[i][j]['text'] = OldVal
                    self.ListTabProdACOM[i][j] = self.TabProdACom.TabLabels[i][j]['text']

            if self.EntryManuelVal.get() != OldVal:
                if self.CanvasBtnRetour is None:
                    self.ImgBtnRetour, wsize, hsize, self.CanvasBtnRetour, self.ImgCanvasBtnRetour = CanInWindow(
                        'Media/FrmMain/BtnRetour/', self.RatioX, self.RatioX, self.CanvasFrmFond, tk.CENTER,
                        int(self.SX * 0.965), int(self.SY * 0.045), 1)
                    self.CanvasBtnRetour.bind('<ButtonPress-1>', self.ActionBtnAnnulPress)
                    self.CanvasBtnRetour.bind('<ButtonRelease-1>', self.ActionAnnul)
                    ChangeCursor(self.CanvasBtnRetour)
                self.ListModif.append([i, j, OldVal])
                self.SaveModifVal(i, j)

            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None

        else:
            self.EntryManuelVal.insert(0, OldVal)

    def SaveModifVal(self, i, j):
        if 0 < j < 6 and self.TabProdACom.TabLabels[i][j]['text'] != '?':
            REQUETE = ['FOURNISSEUR', 'REFERENCE', 'CONDITIONNEMENT', 'UNITMES', 'PRIXHT']
            self.MainAppli.cur.execute("UPDATE PRODUITS SET '" + REQUETE[j - 1] + "' ='" +
                                       self.TabProdACom.TabLabels[i][j]['text']
                                       + "' WHERE NOMS='" + self.TabProdACom.TabLabels[i][0]['text'] + "'")
            self.MainAppli.DataBaseChimie.commit()
            self.MainAppli.SaveListModifDTB('Chimie', 'Modification - ' + REQUETE[j - 1] + ' - ' +
                                            self.TabProdACom.TabLabels[i][0]['text'])
        elif j == 6:
            if self.TabProdACom.TabLabels[i][3]['text'] != '?':
                QCom = int(self.TabProdACom.TabLabels[i][6]['text']) * int(self.TabProdACom.TabLabels[i][3]['text'])
                self.MainAppli.cur.execute("UPDATE PRODUITS SET 'QCOM' ='" + str(QCom)
                                           + "' WHERE NOMS='" + self.TabProdACom.TabLabels[i][0]['text'] + "'")
                self.MainAppli.DataBaseChimie.commit()
                self.MainAppli.SaveListModifDTB('Chimie', 'Modification quantité en commande - '
                                                + self.TabProdACom.TabLabels[i][0]['text'])

    def AnnulModifVal(self, _):
        if self.EntryManuelVal is not None:
            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None
        self.TabProdACom.ActionUnSelect()

    def MoveOnCanvas(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.ImgCanvasBtnQuit, image=self.MainAppli.ImgBtnQuit[0])

    def CacheFrmCommandProd(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.ListBtnActionV[8].CanvasBtn.itemconfig(self.MainAppli.ListBtnActionV[8].ImgCanvasBtn,
                                                              image=self.MainAppli.ListBtnActionV[8].ImgBtn[0])
        self.destroy()
        self.MainAppli.parent.lift()
        self.MainAppli.Action1()


class FrmAjoutProdACom(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Action, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.Action = Action
        self.EntryProd = None
        self.ListBoxProd = None
        self.TitreQuant = None
        self.EntryQuant = None
        self.ListProds = []
        self.InfoProd = None
        self.CaractProd = None
        self.TitreQuantACom = None
        self.QuantACom = None
        self.BtnPlus, self.BtnMoins = None, None
        self.BtnOK, self.BtnAnnul = None, None
        self.IndexElt = 0

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAjout/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        coefY = float(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.MainAppli.curSave))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAjout/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAjout/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmAjoutProdACom)

        Titre = ''
        if self.Action == 0:
            Titre = 'Ajouter des produits chimiques à commander'
        elif self.Action == 1:
            Titre = 'Modifier un produit chimique à commander'

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, Titre, '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

        self.CanvasMenu1 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.965), int(self.SX * 0.003), int(self.SY * 0.031), tk.NW)

        self.CanvasMenu2 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.965), int(self.SX * 0.5), int(self.SY * 0.031), tk.N)

        self.CanvasMenu3 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.965), int(self.SX * 0.998), int(self.SY * 0.031), tk.NE)

        self.AffichSelectProd()

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.CanvasFrmFond.pack()

    def AffichSelectProd(self):
        LabelInCanvas(self.CanvasMenu1.CanvasMenu, "Sélection d'un produit chimique", '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.004), tk.NW)

        self.EntryProd = EntryData(self.CanvasMenu1.CanvasMenu, int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.108),
                                   int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                                   int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.07), tk.CENTER,
                                   AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0))

        self.EntryProd.EntryData.config(justify='center')
        self.EntryProd.EntryData.bind('<KeyRelease>', self.ModifProd)

        self.ListBoxProd = Scrollable_ListBox(self.CanvasMenu1.CanvasMenu,
                                              int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                                              int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.11),
                                              int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.158),
                                              int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.053))

        self.ListBoxProd.ListBox.bind('<<ListboxSelect>>', self.OnSelectListBox)

        self.AffichListprod()
        self.ListBoxProd.ListBox.selection_set(0)
        if len(self.ListProds) > 0:
            self.EntryProd.Data.set(self.ListProds[0][0])
            self.AffichInfoProd(0)
            self.AffichCaractProd(0)

    def AffichListprod(self):
        self.MainAppli.MainAppli.cur.execute("select " + self.MainAppli.MainAppli.ListChampsTabProd +
                                             " from PRODUITS order by NOMS")
        self.ListProds = self.MainAppli.MainAppli.cur.fetchall()

        self.ListBoxProd.ListBox.delete(0, tk.END)
        for i in range(len(self.ListProds)):
            self.ListBoxProd.ListBox.insert(tk.END, self.ListProds[i][0])
        self.ListBoxProd.ListBox.selection_set(0)

    def ModifProd(self, _):
        self.ActionModifProd()

    def ActionModifProd(self):
        self.MainAppli.MainAppli.cur.execute('SELECT ' + self.MainAppli.MainAppli.ListChampsTabProd +
                                             ' FROM PRODUITS WHERE NOMS LIKE \'%' +
                                             self.EntryProd.Data.get() + '%\' order by NOMS')
        self.ListProds = self.MainAppli.MainAppli.cur.fetchall()
        self.ListBoxProd.ListBox.delete(0, tk.END)
        for i in range(len(self.ListProds)):
            self.ListBoxProd.ListBox.insert(tk.END, self.ListProds[i][0])
        self.ListBoxProd.ListBox.selection_set(0)
        if len(self.ListProds) > 0:
            self.AffichInfoProd(0)
            self.AffichCaractProd(0)

    def OnSelectListBox(self, evt):
        try:
            w = evt.widget
            self.IndexElt = int(w.curselection()[0])
            self.EntryProd.Data.set(self.ListProds[self.IndexElt][0])
            self.AffichInfoProd(self.IndexElt)
            self.AffichCaractProd(self.IndexElt)
        except:
            pass

    def ModifQuant(self, _):
        try:
            int(self.EntryQuant.Data.get())
        except:
            self.EntryQuant.Data.set('')

    def AffichInfoProd(self, NProd):
        self.EffaceMenu3()
        LabelInCanvas(self.CanvasMenu3.CanvasMenu, 'Stock / Fournisseur du produit chimique sélectionné', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.002), tk.NW)
        self.InfoProd = InfoProd(self.CanvasMenu3.CanvasMenu, self.ListProds[NProd],
                                 self.MainAppli.MainAppli.cur, self.MainAppli.MainAppli.SizeFont, self.RatioX,
                                 self.RatioY, 3)
        self.TitreQuantACom = self.CanvasMenu3.CanvasMenu.create_text(
            int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.05),
            int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.952), text='Quantité à commander:',
            font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 1), anchor=tk.W)

        if self.Action == 1:
            Quant = self.MainAppli.TabProdACom.TabLabels[self.MainAppli.LineSelect][6]['text']
        else:
            Quant = '1'
        if self.ListProds[NProd][21] != '' and self.ListProds[NProd][21] is not None:
            self.QuantACom = LabelInCanvas(self.CanvasMenu3.CanvasMenu, Quant, 'white',
                                           AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0),
                                           int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.4),
                                           int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.94), tk.NW)
            self.QuantACom.Label.config(width=int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.006),
                                        height=int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.003), relief=tk.RIDGE)

            self.BtnPlus = BtnAction(self.CanvasMenu3.CanvasMenu, int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.48),
                                     int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.95), self.RatioX * 1.1,
                                     self.RatioX * 1.1, 'Media/FrmAjout/BtnPlus/')
            self.BtnPlus.CanvasBtn.bind('<ButtonRelease-1>', self.QuantAComPlus)
            self.BtnMoins = BtnAction(self.CanvasMenu3.CanvasMenu,
                                      int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.48),
                                      int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.97), self.RatioX * 1.1,
                                      self.RatioX * 1.1, 'Media/FrmAjout/BtnMoins/')
            self.BtnMoins.CanvasBtn.bind('<ButtonRelease-1>', self.QuantAComMoins)
        else:
            self.QuantACom = EntryData(self.CanvasMenu3.CanvasMenu,
                                       int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.015),
                                       int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.38),
                                       int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.95), tk.NW,
                                       AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0))
            LabelInCanvas(self.CanvasMenu3.CanvasMenu, self.ListProds[NProd][1], '#E0E0E0',
                          AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0),
                          int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.55),
                          int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.95), tk.NW)
            self.QuantACom.EntryData.config(justify='center')

        self.BtnOK = BtnAction(self.CanvasMenu3.CanvasMenu, int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.88),
                               int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.96), self.RatioX * 0.75,
                               self.RatioX * 0.75, 'Media/FrmAjout/BtnOK2/')
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.ValidAjoutProdACom)
        self.BtnAnnul = BtnAction(self.CanvasMenu3.CanvasMenu, int(int(self.CanvasMenu3.CanvasMenu['width']) * 0.95),
                                  int(int(self.CanvasMenu3.CanvasMenu['height']) * 0.96), self.RatioX * 0.75,
                                  self.RatioX * 0.75, 'Media/FrmAjout/BtnAnnul2/')
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.CacheFrmAjoutProdACom)

    def AffichCaractProd(self, NProd):
        self.EffaceMenu2()
        LabelInCanvas(self.CanvasMenu2.CanvasMenu, 'Informations sur le produit chimique sélectionné', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.002), tk.NW)
        self.CaractProd = CaractProd(self.CanvasMenu2.CanvasMenu, self.ListProds[NProd],
                                     self.MainAppli.MainAppli.SizeFont, self.RatioX, self.RatioY)

    def QuantAComPlus(self, _):
        self.BtnPlus.CanvasBtn.itemconfig(self.BtnPlus.ImgCanvasBtn, image=self.BtnPlus.ImgBtn[0])
        self.QuantACom.Label.config(text=str(int(self.QuantACom.Label['text']) + 1))

    def QuantAComMoins(self, _):
        self.BtnMoins.CanvasBtn.itemconfig(self.BtnMoins.ImgCanvasBtn, image=self.BtnMoins.ImgBtn[0])
        if int(self.QuantACom.Label['text']) > 1:
            self.QuantACom.Label.config(text=str(int(self.QuantACom.Label['text']) - 1))

    def EffaceMenu3(self):
        for widget in self.CanvasMenu3.CanvasMenu.winfo_children():
            widget.destroy()
        if self.InfoProd is not None:
            self.CanvasMenu3.CanvasMenu.delete(self.InfoProd.NomProd)
            self.CanvasMenu3.CanvasMenu.delete(self.InfoProd.TitreStock)
            self.CanvasMenu3.CanvasMenu.delete(self.InfoProd.TitreFournisseur)
            self.CanvasMenu3.CanvasMenu.delete(self.TitreQuantACom)
            self.InfoProd = None

    def EffaceMenu2(self):
        for widget in self.CanvasMenu2.CanvasMenu.winfo_children():
            widget.destroy()

    def ValidAjoutProdACom(self, _):
        self.BtnOK.CanvasBtn.itemconfig(self.BtnOK.ImgCanvasBtn, image=self.BtnOK.ImgBtn[0])
        Rep = True
        if self.ListProds[self.IndexElt][0] in self.MainAppli.ListNomsProdACom:
            Rep = tkMB.askyesno('Attention', self.ListProds[self.IndexElt][0]
                                + '" est déja présent dans la liste des produits à commander, '
                                  'souhaitez-vous mettre à jour les données?', parent=self)
        if Rep:
            QuantACOM = 0
            if self.ListProds[self.IndexElt][21] != '' and self.ListProds[self.IndexElt][21] is not None:
                QuantACOM = int(self.QuantACom.Label['text']) * int(self.ListProds[self.IndexElt][21])
            else:
                if self.QuantACom.EntryData.get() != '':
                    try:
                        QuantACOM = int(self.QuantACom.EntryData.get())
                    except:
                        self.QuantACom.Data.set('')
                        QuantACOM = 0
                else:
                    tkMB.showwarning('Attention', "Veuillez indiquer la quantité de produit à commander", parent=self)

            if QuantACOM != 0:
                self.MainAppli.MainAppli.cur.execute("UPDATE PRODUITS SET QCOM ='" + str(QuantACOM) + "' WHERE NOMS='"
                                                     + self.ListProds[self.IndexElt][0] + "'")
                self.MainAppli.MainAppli.DataBaseChimie.commit()
                self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Ajout produit chimique à commander - '
                                                          + self.ListProds[self.IndexElt][0])
                self.CacheFrmAjoutProdACom(_)

    def MoveOnCanvas(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.MainAppli.ImgCanvasBtnQuit,
                                                          image=self.MainAppli.MainAppli.ImgBtnQuit[0])

    def CacheFrmAjoutProdACom(self, _):
        self.MainAppli.AffichTabProdACom(0)
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.destroy()
        self.MainAppli.FrmAjoutProdACom = None
        self.MainAppli.MainAppli.parent.lift()
        self.MainAppli.MainAppli.FrmLift()
        self.MainAppli.lift()


class FrmBonCom(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, ListProdACom, Fournisseur, NAction, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.Fournisseur = Fournisseur
        self.ListProdACom = ListProdACom
        self.NAction = NAction
        self.ListProdBonCom = []
        self.TabBonCom = None
        self.FraisPort = 0.0
        self.TotalHT = 0
        self.TotalTTC = 0
        self.labelValTotal = None
        self.labelFrais = None
        self.labelTotalTTC = None
        self.ImgFournisseur = None
        self.MenuClicDroitTabBonCom = []
        self.LineSelect = 0
        self.EntryManuelVal = None
        self.TVA = self.MainAppli.TVA
        self.LCell = []
        self.MenuClicDroitTabBonComSup = []
        self.ListModif = []
        self.Four = []

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAjout/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        coefY = float(ConfigResolution(self.MainAppli.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.MainAppli.curSave))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAjout/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAjout/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmBonCom)

        Titre = ''
        if self.NAction == 1:
            Titre = 'Bons de commandes de produits chimiques'
        elif self.NAction == 2:
            Titre = 'Bons de commandes de produits chimiques en attente de livraison'
        elif self.NAction == 3:
            Titre = "Bons de commandes de produits chimiques livrés"
        elif self.NAction == 4:
            Titre = "Commande de produits chimiques - Demande de devis"

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, Titre, '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)
        if self.NAction < 4:
            self.CanvasMenu = CanvasMenu(self.CanvasFrmFond, 'Media/FrmCom/BonCom/', int(self.SX * 0.994),
                                         int(self.SY * 0.78), int(self.SX * 0.5), int(self.SY * 0.56), tk.CENTER)
        else:
            self.CanvasMenu = CanvasMenu(self.CanvasFrmFond, 'Media/FrmCom/BonCom/', int(self.SX * 0.994),
                                         int(self.SY * 0.9), int(self.SX * 0.5), int(self.SY * 0.5), tk.CENTER)
        if self.NAction != 3:
            self.BtnOK = BtnAction(self.CanvasFrmFond, int(int(self.CanvasFrmFond['width']) * 0.945),
                                   int(int(self.CanvasFrmFond['height']) * 0.975), self.RatioX * 0.75,
                                   self.RatioX * 0.75, 'Media/FrmAjout/BtnOK2/')
            self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.ValidBonCom)
            self.BtnAnnul = BtnAction(self.CanvasFrmFond, int(int(self.CanvasFrmFond['width']) * 0.97),
                                      int(int(self.CanvasFrmFond['height']) * 0.975), self.RatioX * 0.75,
                                      self.RatioX * 0.75, 'Media/FrmAjout/BtnAnnul2/')
            self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.CacheFrmBonCom)

        self.ImgBtnRetour, wsize, hsize, self.CanvasBtnRetour, self.ImgCanvasBtnRetour = CanInWindow(
            'Media/FrmMain/BtnRetour/', self.RatioX, self.RatioX, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.965), int(self.SY * 0.014), 0)
        self.CanvasBtnRetour.bind('<ButtonPress-1>', self.ActionBtnAnnulPress)
        self.CanvasBtnRetour.bind('<ButtonRelease-1>', self.ActionAnnul)

        self.AffichBondeCom()

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.CanvasFrmFond.pack()

    def AffichBondeCom(self):
        if self.NAction < 4:
            self.MainAppli.MainAppli.cur.execute('SELECT Logo FROM Fournisseurs WHERE NOM LIKE \'%' +
                                                 self.Fournisseur + '%\' order by NOM')
            Logo = self.MainAppli.MainAppli.cur.fetchall()
            if len(Logo) > 0 and Logo[0][0] != '' and Logo[0][0] is not None:
                PathLogo = 'Datas/Fournisseurs/Logos/' + Logo[0][0]
            else:
                PathLogo = 'Datas/Fournisseurs/Logos/Vide'

            self.ImgFournisseur = ImgInCanvas(self.CanvasFrmFond, PathLogo, 0.1, tk.CENTER,
                                              int(int(self.CanvasFrmFond['width']) * 0.07),
                                              int(int(self.CanvasFrmFond['height']) * 0.11))

            if len(Logo) == 0 or Logo[0][0] == '' or Logo[0][0] is None:
                if len(self.Fournisseur) < 15:
                    TextFournisseur = self.Fournisseur
                else:
                    TextFournisseur = self.Fournisseur.split(' ')[0] + '\n' + self.Fournisseur.split(' ')[1]
                self.ImgFournisseur.CanvasImg.create_text(
                    int(int(self.ImgFournisseur.CanvasImg['width']) * 0.5),
                    int(int(self.ImgFournisseur.CanvasImg['height']) * 0.5), text=TextFournisseur,
                    font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 4, 'bold', 0), anchor=tk.CENTER,
                    justify=tk.CENTER)

            self.Four = ChercheFour(self.MainAppli.MainAppli.cur,
                                    self.MainAppli.MainAppli.ListChampsTabFournisseurs, self.Fournisseur)
            if len(self.Four) > 0:
                c = 0
                for i in [0, 12, 1, 2, 3, 4, 10, 11]:
                    Text = ''
                    if i != 4 and i != 10 and i != 11:
                        if self.Four[0][i] is not None:
                            Text = self.Four[0][i]
                    elif i == 4:
                        if self.Four[0][i] is not None:
                            Text = 'Tel: ' + self.Four[0][i]
                    elif i == 10:
                        if self.Four[0][i] is not None:
                            Text = 'Fax: ' + self.Four[0][i]
                    elif i == 11:
                        if self.Four[0][i] is not None:
                            Text = 'Email: ' + self.Four[0][i]

                    if Text != '':
                        LabelInCanvas(self.CanvasFrmFond, Text, 'white',
                                      AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0),
                                      int(int(self.CanvasFrmFond['width']) * 0.13),
                                      int(int(self.CanvasFrmFond['height']) * 0.06 + c * int(
                                          self.CanvasFrmFond['height']) * 0.017), tk.W)
                        c += 1

        if self.NAction == 1:
            if not self.ListProdBonCom:
                for i in range(len(self.ListProdACom)):
                    if self.ListProdACom[i][1] == self.Fournisseur:
                        self.ListProdBonCom.append(self.ListProdACom[i])

            self.LCell = [0.05, 0.02, 0.013, 0.013, 0.01, 0.013]
            self.TabBonCom = Tableau(self.CanvasMenu.CanvasMenu, len(self.ListProdBonCom), 6,
                                     ['Désignation', 'Référence', 'Conditionnement',
                                      'Prix unitaire HT (€]', 'Quantité', 'Prix total HT (€)'], self.LCell,
                                     AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                     AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0), self)

            self.TotalHT = 0
            self.FraisPort = 0.0
            for i in range(len(self.ListProdBonCom)):
                self.TabBonCom.TabLabels[i][0]['text'] = self.ListProdBonCom[i][0]
                self.TabBonCom.TabLabels[i][1]['text'] = self.ListProdBonCom[i][2]
                self.TabBonCom.TabLabels[i][2]['text'] = self.ListProdBonCom[i][3] + ' ' + self.ListProdBonCom[i][4]
                self.TabBonCom.TabLabels[i][3]['text'] = self.ListProdBonCom[i][5]
                self.TabBonCom.TabLabels[i][4]['text'] = self.ListProdBonCom[i][6]
                self.TabBonCom.TabLabels[i][5]['text'] = self.ListProdBonCom[i][7]
                if self.ListProdBonCom[i][7] != '' and self.ListProdBonCom[i][7] != '?':
                    self.TotalHT = self.TotalHT + float(self.ListProdBonCom[i][7].replace(',', '.'))
            self.TotalTTC = self.TotalHT * self.TVA

            self.MenuClicDroitTabBonComSup = []
            for r in range(self.TabBonCom.NLine):
                ListMenu = []
                for k in range(6):
                    ListMenu.append(tk.Menu(self.TabBonCom.TabLabels[r][k], tearoff=0))

                    def GestEvt(evt, L=r):
                        return self.AffichMenuClicDroitSup(evt, self.MenuClicDroitTabBonComSup, L)

                    self.TabBonCom.TabLabels[r][k].bind("<Button-3>", GestEvt)
                self.MenuClicDroitTabBonComSup.append(ListMenu)

            for r in range(self.TabBonCom.NLine):
                for k in range(6):
                    self.MenuClicDroitTabBonComSup[r][k].add_command(
                        label='Supprimer le produit chimique du bon de commande', command=self.SupProd)

        elif self.NAction == 2 or self.NAction == 3:
            self.CanvasFrmFond.create_text(
                int(int(self.CanvasFrmFond['width']) * 0.8), int(int(self.CanvasFrmFond['height']) * 0.05),
                text='N° de Bon: ' + self.ListProdACom[0][0],
                font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0), anchor=tk.W)

            self.CanvasFrmFond.create_text(
                int(int(self.CanvasFrmFond['width']) * 0.8), int(int(self.CanvasFrmFond['height']) * 0.08),
                text='Date: ' + FormatDate(self.ListProdACom[0][1]),
                font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont + 2, 'bold', 0), anchor=tk.W)

            self.LCell = [0.048, 0.018, 0.011, 0.011, 0.01, 0.013, 0.008]
            self.TabBonCom = Tableau(self.CanvasMenu.CanvasMenu, len(self.ListProdACom), 7,
                                     ['Désignation', 'Référence', 'Conditionnement', 'Prix unitaire HT (€]',
                                      'Quantité', 'Prix total HT (€)', 'Produit livré'], self.LCell,
                                     AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                     AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0), self)

            self.TotalHT = float(self.ListProdACom[0][4].replace(',', '.'))
            if self.ListProdACom[0][5] != '' and self.ListProdACom[0][5] is not None:
                self.FraisPort = float(self.ListProdACom[0][5].replace(',', '.'))
            else:
                self.FraisPort = 0
            self.TotalTTC = (self.TotalHT + self.FraisPort) * self.TVA

            for i in range(len(self.ListProdACom)):
                self.TabBonCom.TabLabels[i][0]['text'] = self.ListProdACom[i][6]
                self.TabBonCom.TabLabels[i][1]['text'] = self.ListProdACom[i][7]
                self.TabBonCom.TabLabels[i][2]['text'] = self.ListProdACom[i][8]
                self.TabBonCom.TabLabels[i][3]['text'] = self.ListProdACom[i][9]
                self.TabBonCom.TabLabels[i][4]['text'] = self.ListProdACom[i][10]
                self.TabBonCom.TabLabels[i][5]['text'] = self.ListProdACom[i][11]
                self.TabBonCom.TabLabels[i][6]['text'] = self.ListProdACom[i][12]

            if self.NAction == 2:
                self.MenuClicDroitTabBonCom = []
                self.MenuClicDroitTabBonComSup = []
                for r in range(self.TabBonCom.NLine):
                    ListMenu = []
                    self.MenuClicDroitTabBonCom.append(tk.Menu(self.TabBonCom.TabLabels[r][6], tearoff=0))

                    def GestEvt(evt, L=r):
                        return self.AffichMenuClicDroit(evt, self.MenuClicDroitTabBonCom, L)

                    self.TabBonCom.TabLabels[r][6].bind("<Button-3>", GestEvt)

                    for k in range(6):
                        ListMenu.append(tk.Menu(self.TabBonCom.TabLabels[r][k], tearoff=0))

                        def GestEvt2(evt, L=r):
                            return self.AffichMenuClicDroitSup(evt, self.MenuClicDroitTabBonComSup, L)

                        self.TabBonCom.TabLabels[r][k].bind("<Button-3>", GestEvt2)
                    self.MenuClicDroitTabBonComSup.append(ListMenu)

                for r in range(self.TabBonCom.NLine):
                    self.MenuClicDroitTabBonCom[r].add_command(label='Livré', command=self.ProdLivraison)
                    self.MenuClicDroitTabBonCom[r].add_command(label='Non livré', command=self.ProdNonLivraison)
                    for k in range(6):
                        self.MenuClicDroitTabBonComSup[r][k].add_command(
                            label='Supprimer le produit chimique du bon de commande', command=self.SupProdComDelay)

        elif self.NAction == 4:
            self.LCell = [0.05, 0.02, 0.02, 0.015, 0.012]
            self.TabBonCom = Tableau(self.CanvasMenu.CanvasMenu, len(self.ListProdACom) - 1, 5,
                                     ['Désignation', 'Fournisseur', 'Référence', 'Conditionnement', 'Quantité'],
                                     self.LCell,
                                     AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                     AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'normal', 0), self)
            for i in range(self.TabBonCom.NLine):
                for j in range(3):
                    self.TabBonCom.TabLabels[i][j]['text'] = self.ListProdACom[i][j]
                self.TabBonCom.TabLabels[i][3]['text'] = self.ListProdACom[i][3] + ' ' + self.ListProdACom[i][4]
                self.TabBonCom.TabLabels[i][4]['text'] = self.ListProdACom[i][6]

            self.MenuClicDroitTabBonComSup = []
            for r in range(self.TabBonCom.NLine):
                ListMenu = []
                for k in range(5):
                    ListMenu.append(tk.Menu(self.TabBonCom.TabLabels[r][k], tearoff=0))

                    def GestEvt(evt, L=r):
                        return self.AffichMenuClicDroitSup(evt, self.MenuClicDroitTabBonComSup, L)

                    self.TabBonCom.TabLabels[r][k].bind("<Button-3>", GestEvt)
                self.MenuClicDroitTabBonComSup.append(ListMenu)

            for r in range(self.TabBonCom.NLine):
                for k in range(5):
                    self.MenuClicDroitTabBonComSup[r][k].add_command(
                        label='Supprimer le produit chimique de la demande de devis', command=self.SupProd)

        for l in range(self.TabBonCom.NLine):
            for k in range(self.TabBonCom.NCol):
                def GestEvt(evt, Line=l, Col=k):
                    return self.ModifVal(evt, Line, Col)

                def GestEvt2(evt):
                    return self.AnnulModifVal(evt)

                self.TabBonCom.TabLabels[l][k].bind('<Double-1>', GestEvt)
                self.TabBonCom.TabLabels[l][k].bind('<Button-1>', GestEvt2)

        for C in range(self.TabBonCom.NCol):
            def GestEvt3(evt):
                return self.AnnulModifVal(evt)

            self.TabBonCom.TabLabelNCol[C].bind('<Button-1>', GestEvt3)

        if self.NAction < 4:
            labelEspace = tk.Label(self.TabBonCom.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                   width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01), bg='white',
                                   font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            labelEspace.grid(row=self.TabBonCom.NLine + 1, column=4)
            labelEspace2 = tk.Label(self.TabBonCom.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                    width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.013), bg='white',
                                    font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            labelEspace2.grid(row=self.TabBonCom.NLine + 1, column=5)

            labelTitreTotal = tk.Label(self.TabBonCom.scrollable_canvas.interior, text='TOTAL HT (€)', relief=tk.RIDGE,
                                       width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01), bg='white',
                                       font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            labelTitreTotal.grid(row=self.TabBonCom.NLine + 2, column=4)
            self.labelValTotal = tk.Label(self.TabBonCom.scrollable_canvas.interior,
                                          text=("%.2f" % self.TotalHT).replace('.', ','), relief=tk.RIDGE,
                                          width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.013), bg='white',
                                          font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            self.labelValTotal.grid(row=self.TabBonCom.NLine + 2, column=5)
            labelTitreFrais = tk.Label(self.TabBonCom.scrollable_canvas.interior, text='Frais de port HT (€)',
                                       relief=tk.RIDGE,
                                       width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01), bg='white',
                                       font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            labelTitreFrais.grid(row=self.TabBonCom.NLine + 3, column=4)
            self.labelFrais = tk.Label(self.TabBonCom.scrollable_canvas.interior,
                                       text=("%.2f" % self.FraisPort).replace('.', ','), relief=tk.RIDGE,
                                       width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.013), bg='white',
                                       font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            self.labelFrais.grid(row=self.TabBonCom.NLine + 3, column=5)
            self.labelFrais.bind('<Double-1>', self.ModifFraisPort)

            labelTitreTotalTTC = tk.Label(self.TabBonCom.scrollable_canvas.interior, text='TOTAL TTC (€)',
                                          relief=tk.RIDGE,
                                          width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.01), bg='white',
                                          font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            labelTitreTotalTTC.grid(row=self.TabBonCom.NLine + 4, column=4)
            self.labelTotalTTC = tk.Label(self.TabBonCom.scrollable_canvas.interior,
                                          text=("%.2f" % self.TotalTTC).replace('.', ','), relief=tk.RIDGE,
                                          width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.013), bg='white',
                                          font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0))
            self.labelTotalTTC.grid(row=self.TabBonCom.NLine + 4, column=5)

        self.CanvasFrmFond.bind("<Button-1>", self.AnnulModifVal)
        self.TabBonCom.scrollable_canvas.interior.bind("<Button-1>", self.AnnulModifVal)
        self.TabBonCom.scrollable_canvas.bind("<Button-1>", self.AnnulModifVal)

    def SupProd(self):
        if self.NAction != 4:
            if len(self.ListProdBonCom) > 1:
                ProdSup = self.ListProdBonCom[self.LineSelect][0]
                Rep = tkMB.askyesno('Attention', 'Voulez-vous supprimer "' + ProdSup
                                    + '" du bon de commande ?', parent=self)
                if Rep:
                    del self.ListProdBonCom[self.LineSelect]
                    self.AffichBondeCom()
            else:
                Rep = tkMB.askyesno('Attention', "Voulez-vous annuler l'édition du bon de commande ?", parent=self)
                if Rep:
                    self.RetourTabProdACom()
        else:
            if len(self.ListProdACom) - 1 > 1:
                ProdSup = self.ListProdACom[self.LineSelect][0]
                Rep = tkMB.askyesno('Attention', 'Voulez-vous supprimer "' + ProdSup
                                    + '" de la demande de devis ?', parent=self)
                if Rep:
                    del self.ListProdACom[self.LineSelect]
                    self.AffichBondeCom()
            else:
                Rep = tkMB.askyesno('Attention', "Voulez-vous annuler la demande de devis ?", parent=self)
                if Rep:
                    self.RetourTabProdACom()

    def RetourTabProdACom(self):
        self.MainAppli.AffichTabProdACom(0)
        self.destroy()
        self.MainAppli.MainAppli.parent.lift()
        self.MainAppli.MainAppli.FrmLift()
        self.MainAppli.lift()

    def SupProdComDelay(self):
        if len(self.ListProdACom) > 1:
            ProdSup = self.ListProdACom[self.LineSelect][6]
            Rep = tkMB.askyesno('Attention', 'Voulez-vous supprimer "' + self.ListProdACom[self.LineSelect][6]
                                + '" du bon de commande "' + self.ListProdACom[0][0] + '" en attente de livraison?',
                                parent=self)
            if Rep:
                del self.ListProdACom[self.LineSelect]
                self.AffichBondeCom()
                self.CalculTotalHT()
                self.CalculTotalTTC()
                self.MainAppli.MainAppli.cur.execute("DELETE FROM BONSCOMMANDEPRODUITS WHERE NBON='" +
                                                     self.ListProdACom[0][0] + "' and PRODUIT='" + ProdSup + "'")
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET PRIXTOTCOM ='" + str(self.TotalHT) +
                    "' WHERE NBON='" + self.ListProdACom[0][0] + "'")
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET NBRPROD ='" + str(self.TabBonCom.NLine) +
                    "' WHERE NBON='" + self.ListProdACom[0][0] + "'")
                self.MainAppli.MainAppli.cur.execute("UPDATE PRODUITS SET QenCOM ='' WHERE NOMS='" + ProdSup + "'")
                self.MainAppli.MainAppli.DataBaseChimie.commit()
                self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Suppression produit chimique en commande - '
                                                          + ProdSup)
        else:
            self.MainAppli.SupBonComDelay()

    def ModifVal(self, _, i, j):
        if j != 0 and j != 5 and self.EntryManuelVal is None and self.NAction != 3:
            self.EntryManuelVal = tk.Entry(self.TabBonCom.scrollable_canvas.interior, text='',
                                           width=int(int(self.CanvasMenu.CanvasMenu['width']) * self.LCell[j]),
                                           font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                           justify='right')
            self.EntryManuelVal.grid(row=i + 1, column=j)
            self.EntryManuelVal.insert(0, self.TabBonCom.TabLabels[i][j]['text'])
            self.EntryManuelVal.focus_set()

            def GestEvt(evt):
                return self.ValidModifVal(evt, i, j)

            self.EntryManuelVal.bind('<Return>', GestEvt)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ModifFraisPort(self, _):
        if self.EntryManuelVal is None and self.NAction != 3:
            self.EntryManuelVal = tk.Entry(self.TabBonCom.scrollable_canvas.interior, text='',
                                           width=int(int(self.CanvasMenu.CanvasMenu['width']) * 0.013),
                                           font=AppliFont('Helvetica', self.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                           justify='right')
            self.EntryManuelVal.grid(row=self.TabBonCom.NLine + 3, column=5)
            self.EntryManuelVal.insert(0, self.labelFrais['text'])
            self.EntryManuelVal.focus_set()
            self.EntryManuelVal.bind('<Return>', self.ValidModifFrais)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ValidModifVal(self, _, i, j):
        OldVal = self.TabBonCom.TabLabels[i][j]['text']
        if self.EntryManuelVal.get() != '':
            self.TabBonCom.TabLabels[i][j]['text'] = self.EntryManuelVal.get()
            if (j == 4 or j == 3) and self.NAction != 4:
                if j == 4:
                    try:
                        int(self.TabBonCom.TabLabels[i][4]['text'])
                    except:
                        self.EntryManuelVal.delete(0, tk.END)
                        self.EntryManuelVal.insert(0, OldVal)
                        self.TabBonCom.TabLabels[i][j]['text'] = OldVal
                elif j == 3:
                    try:
                        float(self.TabBonCom.TabLabels[i][3]['text'].replace(',', '.'))
                    except:
                        self.EntryManuelVal.delete(0, tk.END)
                        self.EntryManuelVal.insert(0, OldVal)
                        self.TabBonCom.TabLabels[i][j]['text'] = OldVal
                try:
                    Ptotal = int(self.TabBonCom.TabLabels[i][4]['text']) * \
                             float(self.TabBonCom.TabLabels[i][3]['text'].replace(',', '.'))
                    self.TabBonCom.TabLabels[i][5]['text'] = ("%.2f" % Ptotal).replace('.', ',')
                    self.CalculTotalHT()
                    self.CalculTotalTTC()
                    if j == 3:
                        self.TabBonCom.TabLabels[i][j]['text'] = ("%.2f" % float(
                            self.EntryManuelVal.get().replace(',', '.'))).replace('.', ',')
                except:
                    pass
            elif j == 2:
                try:
                    int(self.EntryManuelVal.get().split(' ')[0])
                    if self.EntryManuelVal.get().split(' ')[1] != 'g' and self.EntryManuelVal.get().split(' ')[
                        1] != 'mL' \
                            and self.EntryManuelVal.get().split(' ')[1].upper() != "UNIT":
                        self.EntryManuelVal.delete(0, tk.END)
                        self.EntryManuelVal.insert(0, OldVal)
                        self.TabBonCom.TabLabels[i][j]['text'] = OldVal
                except:
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabBonCom.TabLabels[i][j]['text'] = OldVal
            elif j == 6 and self.NAction == 2:
                if self.EntryManuelVal.get().upper() != 'OUI' and self.EntryManuelVal.get().upper() != 'NON':
                    self.EntryManuelVal.delete(0, tk.END)
                    self.EntryManuelVal.insert(0, OldVal)
                    self.TabBonCom.TabLabels[i][j]['text'] = OldVal
                else:
                    self.TabBonCom.TabLabels[i][j]['text'] = self.EntryManuelVal.get().upper()

            if self.EntryManuelVal.get() != OldVal:
                self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[1])
                ChangeCursor(self.CanvasBtnRetour)
                self.ListModif.append([i, j, OldVal])
                self.SaveModifVal(i, j)

            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None
        else:
            self.EntryManuelVal.insert(0, OldVal)

    def SaveModifVal(self, i, j):
        if j == 1 or j == 2 or j == 3:
            REQUETE = ['REFERENCE', 'CONDITIONNEMENT', 'PRIXHT']
            if j != 2:
                Val = self.TabBonCom.TabLabels[i][j]['text']
            else:
                Val = self.TabBonCom.TabLabels[i][j]['text'].split(' ')[0]
                UnitMes = self.TabBonCom.TabLabels[i][j]['text'].split(' ')[1]
                self.MainAppli.MainAppli.cur.execute("UPDATE PRODUITS SET UNITMES ='" + UnitMes
                                                     + "' WHERE NOMS='" + self.TabBonCom.TabLabels[i][0]['text'] + "'")
            self.MainAppli.MainAppli.cur.execute("UPDATE PRODUITS SET '" + REQUETE[j - 1] + "' ='" + Val
                                                 + "' WHERE NOMS='" + self.TabBonCom.TabLabels[i][0][
                                                     'text'] + "'")
            self.MainAppli.MainAppli.DataBaseChimie.commit()
            self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Modification bon de commande - ' +
                                                      REQUETE[j - 1] + ' - ' + self.TabBonCom.TabLabels[i][0]['text'])
            if self.NAction != 1 and self.NAction != 4:
                REQUETE = ['REFERENCE', 'COND', 'PRIXUNIT', 'PRIXTOTAL', 'PRIXTOTCOM']
                if j == 2:
                    Val = self.TabBonCom.TabLabels[i][j]['text']
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET '" + REQUETE[j - 1] + "'='" + Val + "' WHERE NBON='" +
                    self.ListProdACom[0][0] + "' and PRODUIT='" + self.TabBonCom.TabLabels[i][0]['text'] + "'")
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET '" + REQUETE[3] + "'='" + self.TabBonCom.TabLabels[i][5][
                        'text'] + "' WHERE NBON='" +
                    self.ListProdACom[0][0] + "'and PRODUIT='" + self.TabBonCom.TabLabels[i][0]['text'] + "'")
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET '" + REQUETE[4] + "'='" + self.labelValTotal[
                        'text'] + "' WHERE NBON='" + self.ListProdACom[0][0] + "'")
                self.MainAppli.MainAppli.DataBaseChimie.commit()
                self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Modification bon de commande - '
                                                          + self.ListProdACom[0][0])
        elif j == 4 and self.NAction != 1 and self.NAction != 4:
            REQUETE = ['QUANTITE', 'PRIXTOTAL', 'PRIXTOTCOM']
            for c in range(2):
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET '" + REQUETE[0 + c] + "'='" +
                    self.TabBonCom.TabLabels[i][4 + c]['text'] + "' WHERE NBON='" +
                    self.ListProdACom[0][0] + "'and PRODUIT='" + self.TabBonCom.TabLabels[i][0]['text'] + "'")
                self.MainAppli.MainAppli.cur.execute(
                    "UPDATE BONSCOMMANDEPRODUITS SET '" + REQUETE[2] + "'='" + self.labelValTotal[
                        'text'] + "' WHERE NBON='" + self.ListProdACom[0][0] + "'")
                self.MainAppli.MainAppli.DataBaseChimie.commit()
                self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Modification bon de commande - '
                                                          + self.ListProdACom[0][0])

    def ValidModifFrais(self, _):
        OldVal = self.labelFrais['text']
        if self.EntryManuelVal.get() != '':
            try:
                self.labelFrais['text'] = ("%.2f" % float(self.EntryManuelVal.get().replace(',', '.'))).replace('.',
                                                                                                                ',')
                self.FraisPort = float(self.labelFrais['text'].replace(',', '.'))
                self.CalculTotalTTC()
                if self.NAction != 1:
                    self.MainAppli.MainAppli.cur.execute(
                        "UPDATE BONSCOMMANDEPRODUITS SET FRAISPORT = '" + self.labelFrais['text'] + "' WHERE NBON='" +
                        self.ListProdACom[0][0] + "'")
                    self.MainAppli.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.MainAppli.SaveListModifDTB('Chimie',
                                                              'Modification bon de commande - Frais de port - '
                                                              + self.ListProdACom[0][0])

            except:
                self.labelFrais['text'] = OldVal
            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None
        else:
            self.EntryManuelVal.insert(0, OldVal)

    def AnnulModifVal(self, _):
        if self.EntryManuelVal is not None:
            self.EntryManuelVal.grid_forget()
            self.EntryManuelVal = None
        self.TabBonCom.ActionUnSelect()

    def CalculTotalHT(self):
        PtotalHT = 0
        for r in range(self.TabBonCom.NLine):
            PtotalHT = PtotalHT + float(self.TabBonCom.TabLabels[r][5]['text'].replace(',', '.'))
        self.labelValTotal['text'] = ("%.2f" % PtotalHT).replace('.', ',')
        self.TotalHT = PtotalHT

    def CalculTotalTTC(self):
        PtotalTTC = (float(self.labelValTotal['text'].replace(',', '.')) + float(
            self.labelFrais['text'].replace(',', '.'))) * self.TVA
        self.labelTotalTTC['text'] = ("%.2f" % PtotalTTC).replace('.', ',')

    def ValidBonCom(self, _):
        self.BtnOK.CanvasBtn.itemconfig(self.BtnOK.ImgCanvasBtn, image=self.BtnOK.ImgBtn[0])
        if self.NAction == 1:
            Date = datetime.now()
            An = str(Date.date().year)
            Mois = str(Date.date().month)
            Jour = str(Date.date().day)
            ValidCommande = True

            NumBon = self.DeterminNBon()
            NBon = An + ' - ' + str("%03d" % NumBon)
            for i in range(len(self.ListProdBonCom)):
                for j in range(2, 6):
                    if self.TabBonCom.TabLabels[i][j]['text'] == '?':
                        tkMB.showwarning('Attention', "Veuillez indiquer le conditionnement, le prix unitaire et la "
                                                      "quantité des produits chimiques commandés !", parent=self)
                        ValidCommande = False
                        break
                if not ValidCommande:
                    break
            if ValidCommande:
                for i in range(len(self.ListProdBonCom)):
                    data = [(NBon, An + '-' + Mois + '-' + Jour, self.Fournisseur, len(self.ListProdBonCom),
                             ("%.2f" % self.TotalHT).replace('.', ','), ("%.2f" % self.FraisPort).replace('.', ','),
                             self.TabBonCom.TabLabels[i][0]['text'], self.TabBonCom.TabLabels[i][1]['text'],
                             self.TabBonCom.TabLabels[i][2]['text'], self.TabBonCom.TabLabels[i][3]['text'],
                             self.TabBonCom.TabLabels[i][4]['text'], self.TabBonCom.TabLabels[i][5]['text'], 'NON',
                             'NON')]
                    self.MainAppli.MainAppli.cur.execute(
                        "INSERT INTO BONSCOMMANDEPRODUITS(" + self.MainAppli.MainAppli.ListChampsTabBonComProd +
                        ") VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", data[0])
                    self.MainAppli.MainAppli.cur.execute("UPDATE PRODUITS SET QCOM ='' WHERE NOMS='" +
                                                         self.ListProdBonCom[i][0] + "'")
                    QenCom = str(int(self.TabBonCom.TabLabels[i][2]['text'].split(' ')[0]) *
                                 int(self.TabBonCom.TabLabels[i][4]['text']))
                    self.MainAppli.MainAppli.cur.execute("UPDATE PRODUITS SET QenCOM ='" + QenCom + "' WHERE NOMS='" +
                                                         self.ListProdBonCom[i][0] + "'")
                self.MainAppli.MainAppli.DataBaseChimie.commit()
                self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Validation bon de commande - ' + NBon)
                self.CacheFrmBonCom(_)

        elif self.NAction == 2:
            Livraison = True
            for i in range(self.TabBonCom.NLine):
                if self.TabBonCom.TabLabels[i][6]['text'] == 'NON':
                    Livraison = False
            if not Livraison:
                tkMB.showwarning('Attention', "La commande n'a pas été livrée en totalité !", parent=self)
            else:
                FrmMAJStock(self.MainAppli.MainAppli.CanvasFrmMain, self.RatioX, self.RatioY,
                            self.MainAppli.ListProdComDelay, self)

        elif self.NAction == 4:
            Devis = SaveToPDF(self.CanvasMenu.CanvasMenu, 'Datas/Devis/', 'tmp.bmp')
            AffichPDF('Produits chimiques - Demande de devis', Devis, self)
            self.CacheFrmBonCom(_)

    def DeterminNBon(self):
        NBon = 1
        self.MainAppli.MainAppli.cur.execute('SELECT NBON FROM BONSCOMMANDEPRODUITS order by NBON')
        ListNBon = self.MainAppli.MainAppli.cur.fetchall()
        ListNBonAn = []
        for i in range(len(ListNBon)):
            if ListNBon[i][0][0:4] == str(datetime.now().date().year):
                if ListNBon[i][0][-3:] not in ListNBonAn:
                    ListNBonAn.append(ListNBon[i][0][-3:])
        ListNBonAn.sort()
        if len(ListNBonAn) > 0:
            NBon = int(ListNBonAn[-1]) + 1
        return NBon

    def AffichMenuClicDroit(self, event, MenuClicDroitTab, j):
        MenuClicDroitTab[j].post(event.x_root, event.y_root)
        self.LineSelect = j

    def AffichMenuClicDroitSup(self, event, MenuClicDroitTab, j):
        MenuClicDroitTab[j][0].post(event.x_root, event.y_root)
        self.LineSelect = j

    def ProdLivraison(self):
        self.TabBonCom.TabLabels[self.LineSelect][6]['text'] = 'OUI'
        self.MainAppli.MainAppli.cur.execute("UPDATE BONSCOMMANDEPRODUITS SET LIVRAISON ='OUI' WHERE NBON='" +
                                             self.ListProdACom[0][0] + "' AND PRODUIT='" +
                                             self.TabBonCom.TabLabels[self.LineSelect][0]['text'] + "'")
        self.MainAppli.MainAppli.DataBaseChimie.commit()
        self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour livraison produit chimique en commande - ' +
                                                  self.TabBonCom.TabLabels[self.LineSelect][0]['text'])

    def ProdNonLivraison(self):
        self.TabBonCom.TabLabels[self.LineSelect][6]['text'] = 'NON'
        self.MainAppli.MainAppli.cur.execute("UPDATE BONSCOMMANDEPRODUITS SET LIVRAISON ='NON' WHERE NBON='" +
                                             self.ListProdACom[0][0] + "' AND PRODUIT='" +
                                             self.TabBonCom.TabLabels[self.LineSelect][0]['text'] + "'")
        self.MainAppli.MainAppli.DataBaseChimie.commit()
        self.MainAppli.MainAppli.SaveListModifDTB('Chimie', 'Mise à jour livraison produit chimique en commande - ' +
                                                  self.TabBonCom.TabLabels[self.LineSelect][0]['text'])

    def ActionBtnAnnulPress(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[2])

    def ActionAnnul(self, _):
        self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[1])
        self.TabBonCom.TabLabels[self.ListModif[-1][0]][self.ListModif[-1][1]]['text'] = self.ListModif[-1][2]
        if (self.ListModif[-1][1] == 4 or self.ListModif[-1][1] == 3) and self.NAction != 4:
            try:
                Ptotal = int(self.TabBonCom.TabLabels[self.ListModif[-1][0]][4]['text']) * \
                         float(self.TabBonCom.TabLabels[self.ListModif[-1][0]][3]['text'].replace(',', '.'))
                self.TabBonCom.TabLabels[self.ListModif[-1][0]][5]['text'] = ("%.2f" % Ptotal).replace('.', ',')
                self.CalculTotalHT()
                self.CalculTotalTTC()
            except:
                self.TabBonCom.TabLabels[self.ListModif[-1][0]][5]['text'] = '?'
        self.SaveModifVal(self.ListModif[-1][0], self.ListModif[-1][1])
        del self.ListModif[-1]
        if len(self.ListModif) == 0:
            self.CanvasBtnRetour.itemconfig(self.ImgCanvasBtnRetour, image=self.ImgBtnRetour[0])

    def ClosePDF(self):
        self.MainAppli.MainAppli.parent.focus_force()
        self.MainAppli.MainAppli.FrmLift()
        self.MainAppli.focus_force()

    def MoveOnCanvas(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.MainAppli.ImgCanvasBtnQuit,
                                                          image=self.MainAppli.MainAppli.ImgBtnQuit[0])

    def CacheFrmBonCom(self, _):
        if self.NAction == 1 or self.NAction == 4:
            self.MainAppli.AffichTabProdACom(0)
        elif self.NAction == 2:
            self.MainAppli.AffichTabComDelay(2)
        elif self.NAction == 3:
            self.MainAppli.AffichTabRecapCom(3)
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.destroy()
        self.MainAppli.MainAppli.parent.lift()
        self.MainAppli.MainAppli.FrmLift()
        self.MainAppli.lift()


class FrmMAJStock(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, ListProd, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.ListProd = ListProd
        self.TabMAJStock = None

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAjout/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        coefY = float(ConfigResolution(self.MainAppli.MainAppli.MainAppli.Nconfig, 'YTitreFrm',
                                       self.MainAppli.MainAppli.MainAppli.curSave))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAjout/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAjout/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmMAJStock)

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond,
                                      'Mise à jour du stock de produits chimiques après réception de la commande',
                                      '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.MainAppli.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)

        self.CanvasMenu = CanvasMenu(self.CanvasFrmFond, 'Media/FrmCom/BonCom/', int(self.SX * 0.994),
                                     int(self.SY * 0.85), int(self.SX * 0.5), int(self.SY * 0.5), tk.CENTER)

        self.BtnOK = BtnAction(self.CanvasFrmFond, int(int(self.CanvasFrmFond['width']) * 0.945),
                               int(int(self.CanvasFrmFond['height']) * 0.975), self.RatioX * 0.75,
                               self.RatioX * 0.75, 'Media/FrmAjout/BtnOK2/')
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.ValidMAJStock)
        self.BtnAnnul = BtnAction(self.CanvasFrmFond, int(int(self.CanvasFrmFond['width']) * 0.97),
                                  int(int(self.CanvasFrmFond['height']) * 0.975), self.RatioX * 0.75,
                                  self.RatioX * 0.75, 'Media/FrmAjout/BtnAnnul2/')
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.CacheFrmMAJStock)

        self.AffichMAJStock()

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.CanvasFrmFond.pack()

    def AffichMAJStock(self):
        self.TabMAJStock = Tableau(self.CanvasMenu.CanvasMenu, len(self.ListProd), 5,
                                   ['Désignation', 'Unité de mesure', 'Quantité en stock \n avant commande',
                                    'Quantité commandée', 'Quantité en stock \n après commande',
                                    'Prix total TTC (€)'], [0.05, 0.015, 0.015, 0.015, 0.015],
                                   AppliFont('Helvetica', self.MainAppli.MainAppli.MainAppli.SizeFont, 'bold', 0),
                                   AppliFont('Helvetica', self.MainAppli.MainAppli.MainAppli.SizeFont, 'normal', 0),
                                   self)

        for i in range(len(self.ListProd)):
            ListProd = ChercheProd(self.MainAppli.MainAppli.MainAppli.cur,
                                   self.MainAppli.MainAppli.MainAppli.ListChampsTabProd, self.ListProd[i][6])
            self.TabMAJStock.TabLabels[i][0]['text'] = self.ListProd[i][6]
            self.TabMAJStock.TabLabels[i][1]['text'] = ListProd[0][1]
            self.TabMAJStock.TabLabels[i][2]['text'] = (
                    "%.1f" % float(ListProd[0][18].replace(',', '.'))).replace('.', ',')
            self.TabMAJStock.TabLabels[i][3]['text'] = str(
                int(self.ListProd[i][10]) * int(ListProd[0][21]))
            QStock = float(ListProd[0][18].replace(',', '.')) + float(
                self.TabMAJStock.TabLabels[i][3]['text'].replace(',', '.'))
            self.TabMAJStock.TabLabels[i][4]['text'] = ("%.1f" % QStock).replace('.', ',')

    def ValidMAJStock(self, _):
        for i in range(len(self.ListProd)):
            self.MainAppli.MainAppli.MainAppli.cur.execute(
                "UPDATE PRODUITS SET QSTOCK ='" + self.TabMAJStock.TabLabels[i][4]['text'] +
                "' WHERE NOMS='" + self.TabMAJStock.TabLabels[i][0]['text'] + "'")
            self.MainAppli.MainAppli.MainAppli.cur.execute(
                "UPDATE PRODUITS SET QenCOM ='' WHERE NOMS='" + self.TabMAJStock.TabLabels[i][0]['text'] + "'")
            self.MainAppli.MainAppli.MainAppli.cur.execute(
                "UPDATE BONSCOMMANDEPRODUITS SET CLOTURE ='OUI' WHERE NBON='" +
                self.ListProd[i][0] + "' AND PRODUIT='" +
                self.TabMAJStock.TabLabels[i][0]['text'] + "'")
        self.MainAppli.MainAppli.MainAppli.DataBaseChimie.commit()
        self.MainAppli.MainAppli.MainAppli.SaveListModifDTB('Chimie',
                                                            'Mise à jour stock produit chimique - Commande livrée - ' +
                                                            self.ListProd[0][0])
        self.destroy()
        self.MainAppli.CacheFrmBonCom(_)

    def CacheFrmMAJStock(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.destroy()
        self.MainAppli.MainAppli.MainAppli.parent.lift()
        self.MainAppli.MainAppli.MainAppli.FrmLift()
        self.MainAppli.lift()

    def MoveOnCanvas(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.MainAppli.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.MainAppli.MainAppli.ImgCanvasBtnQuit,
                                                                    image=self.MainAppli.MainAppli.MainAppli.ImgBtnQuit[
                                                                        0])
