/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers.FactureFrs;

import Controllers.Dialog.MessageControle;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.BonReceptionFrs.BonReceptionDB;
import Models.BonReceptionFrs.BonReceptionFrs;
import Models.BonReceptionFrs.BonReceptionList;
import Models.BonReceptionFrs.BonReceptionProduitList;
import Models.FactureFrs.FactureFrs;
import Models.FactureFrs.FactureFrsDB;
import Models.Fournisseur.Fournisseur;
import Models.Fournisseur.FournisseurDB;
import Models.Produit.ListeProduit;
import Models.Stock.StockDB;
import Models.User.Profile;
import Models.User.User;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;
import org.controlsfx.control.textfield.TextFields;

/**
 * FXML Controller class
 *
 * @author Maher
 */
public class FactureFrsBonReceptionAjouterController implements Initializable {

    @FXML public AnchorPane PaneFactureBRFrsAjouter ;
     
    @FXML public TableView<BonReceptionList> TableViewBonReception ;
    @FXML public TableColumn<BonReceptionList ,String> TabColReference;
    @FXML public TableColumn<BonReceptionList ,String> TabColFournisseur;
    @FXML public TableColumn<BonReceptionList ,String> TabColDate;
    @FXML public TableColumn<BonReceptionList ,String> TabColLocalReception;
    @FXML public TableColumn<BonReceptionList ,String> TabColNetPayer;
    @FXML public TableColumn<BonReceptionList ,Boolean> TabColRechAddAction;
    

    @FXML public TableView<BonReceptionList> TableViewBonReceptionSelected;
    @FXML public TableColumn<BonReceptionList ,String> TabColReferenceSelected;
    @FXML public TableColumn<BonReceptionList ,String> TabColFournisseurSelected;
    @FXML public TableColumn<BonReceptionList ,String> TabColDateSelected;
    @FXML public TableColumn<BonReceptionList ,String> TabColLocalReceptionSelected;
    @FXML public TableColumn<BonReceptionList ,String> TabColNetPayerSelected;
    @FXML public TableColumn<BonReceptionList ,Boolean> TabColSupprimer;
    
    @FXML public TextField  TextFieldNumero ;
    @FXML public TextField  TextFieldNetPayer ;
    @FXML private TextField TextFieldFournisseur ;
    @FXML public ChoiceBox ChoiceBoxLocalReception ;
    @FXML public DatePicker DatePickerDateReception;
    
    @FXML public TextField  TextFieldNumeroFac ;
    @FXML public TextField  TextFieldHeurFac ;
    @FXML public DatePicker DatePickerDateFac;
    @FXML public Text TextCltNumeroFac ;
    @FXML public Text TextCltHeurFac ;
    @FXML public Text TextCltDateFac ;
    
    @FXML public Text TextTotalFacture;
    
    
    @FXML public Button ButtonFactureBLAjouter;
    @FXML public ProgressIndicator ProgressIndicatorBonReception;
    @FXML public ProgressIndicator ProgressIndicatorSaveFactureBLAjouter;
    
    public  ArrayList<String> ListFournisseur = new  ArrayList<>();
    public  ArrayList<String> ListLocale = new  ArrayList<>();
    
    ObservableList<BonReceptionList> ObservableListBonReception = FXCollections.observableArrayList();
    
    BonReceptionDB BonRecepDB= new BonReceptionDB();
    
    contro Controle = new contro();
    
    String StringSeleFournissuer ;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        TabColReference.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("Numero"));
        
        TabColFournisseur.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("Fournisseur"));
        TabColFournisseur.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColFournisseur.getStyleClass().add("Center");
        
        TabColDate.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("Date"));
        TabColDate.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColDate.getStyleClass().add("Center");
        
        TabColNetPayer.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("NetPayer"));
        TabColNetPayer.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColNetPayer.getStyleClass().add("Center");
        
        TabColLocalReception.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("LocalReception"));
        TabColLocalReception.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColLocalReception.getStyleClass().add("Center");
        
        TabColRechAddAction.setSortable(true);
        TabColRechAddAction.setStyle( "-fx-alignment: CENTER;");
        
        TabColRechAddAction.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<BonReceptionList, Boolean>, 
            ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<BonReceptionList, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });
 
        // create a cell value factory with an add button for each row in the table.
        TabColRechAddAction.setCellFactory(new Callback<TableColumn<BonReceptionList, Boolean>, TableCell<BonReceptionList, Boolean>>() {
          @Override 
          public TableCell<BonReceptionList, Boolean> call(TableColumn<BonReceptionList, Boolean> personBooleanTableColumn) {
            return new FactureFrsBonReceptionAjouterController.ButtonCell();
          }
        });
        
        
        TabColReferenceSelected.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("Numero"));
        
        TabColFournisseurSelected.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("Fournisseur"));
        TabColFournisseurSelected.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColFournisseurSelected.getStyleClass().add("Center");
        
        TabColDateSelected.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("Date"));
        TabColDateSelected.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColDateSelected.getStyleClass().add("Center");
        
        TabColNetPayerSelected.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("NetPayer"));
        TabColNetPayerSelected.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColNetPayerSelected.getStyleClass().add("Center");
        
        TabColLocalReceptionSelected.setCellValueFactory(new PropertyValueFactory<BonReceptionList, String>("LocalReception"));
        TabColLocalReceptionSelected.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColLocalReceptionSelected.getStyleClass().add("Center");
        
        TabColSupprimer.setSortable(true);
        TabColSupprimer.setStyle( "-fx-alignment: CENTER;");
        
        TabColSupprimer.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<BonReceptionList, Boolean>, 
            ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<BonReceptionList, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });
 
        // create a cell value factory with an add button for each row in the table.
        TabColSupprimer.setCellFactory(new Callback<TableColumn<BonReceptionList, Boolean>, TableCell<BonReceptionList, Boolean>>() {
          @Override 
          public TableCell<BonReceptionList, Boolean> call(TableColumn<BonReceptionList, Boolean> personBooleanTableColumn) {
            return new FactureFrsBonReceptionAjouterController.ButtonCellRemove();
          }
        });
        
        ListFournisseur = new FournisseurDB().getAllFournisseur("CONCAT(`id_fourisseur`,' - ',`nom`)");
        TextFields.bindAutoCompletion(TextFieldFournisseur, ListFournisseur);
        
        StockDB Stock = new StockDB();
        ListLocale = Stock.getAllListLocal();
        ChoiceBoxLocalReception.getItems().addAll(ListLocale);
        
        DatePickerDateFac.setValue(LocalDate.now());
        TextFieldHeurFac.setText(LocalDateTime.now().getHour()+":"+LocalDateTime.now().getMinute());

        RechecheBonReception();
        
        getRechecheBonReception("");
        
        AjouterFactureBL();
    }





    //Define the button cell
    private class ButtonCell extends TableCell<BonReceptionList, Boolean> {
        
        final Button cellButton = new Button();
        
        ButtonCell(){
            cellButton.getStyleClass().add("btn-icon-primary");
            Image coffeeImage = new Image(getClass().getResourceAsStream("/Public/icon/iconaffecter.png"));
            ImageView buttonGraphic = new ImageView();
            buttonGraphic.setImage(coffeeImage);
            cellButton.setGraphic(buttonGraphic);

            //Action when the button is pressed
            cellButton.setOnAction(new EventHandler<ActionEvent>(){
                @Override
                public void handle(ActionEvent t) {
                   BonReceptionList BonReceptionListSelect = (BonReceptionList)getTableRow().getItem();
                   AffectBonReception(BonReceptionListSelect);
                }
            });
        }
        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            if(!empty){
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }
    
    
    //Define the button cell
    private class ButtonCellRemove extends TableCell<BonReceptionList, Boolean> {
        
        final Button cellButton = new Button();
        
        ButtonCellRemove(){
            cellButton.getStyleClass().add("btn-danger");
            Image coffeeImage = new Image(getClass().getResourceAsStream("/Public/icon/icondelete.png"));
            ImageView buttonGraphic = new ImageView();
            buttonGraphic.setImage(coffeeImage);
            cellButton.setGraphic(buttonGraphic);

            //Action when the button is pressed
            cellButton.setOnAction(new EventHandler<ActionEvent>(){
                @Override
                public void handle(ActionEvent t) {
                    int selectdIndex = getTableRow().getIndex();
                    ObservableListBonReception.remove(selectdIndex);
                    CalculeFacture();
                    TableViewBonReceptionSelected.setItems(ObservableListBonReception);
                    TableViewBonReceptionSelected.refresh();
                }
            });
        }
        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            if(!empty){
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }
    
    
    private void getRechecheBonReception(final String KeyWordSearch )
    {
        try {
            ProgressIndicatorBonReception.setVisible(true);
            TableViewBonReception.setVisible(false);

            // Create a Runnable
            Runnable task = new Runnable(){
                public void run(){
                    Platform.runLater(new Runnable(){
                        @Override
                        public void run(){
                           
                            TableViewBonReception.setItems(BonRecepDB.getBonReceptionNotFact(KeyWordSearch));
                            ProgressIndicatorBonReception.setVisible(false);
                            TableViewBonReception.setVisible(true);
                        }
                    });	
                }
            };


            Thread backgroundThread = new Thread(task); // Run the task in a background thread
            backgroundThread.setDaemon(true);   // Terminate the running thread if the application exits
            backgroundThread.start();   // Start the thread

        }catch (Exception ex) {
             System.err.println("Exception getRechecheBonReception \n"+ex.getMessage());
        }
        
    }
    
    
    private boolean  ContrFournissuer()
    {
        final MessageControle messagecontrol = new MessageControle();
        Text text3 = new Text();
        text3.setFont(Font.font("Arial", FontWeight.BOLD, 13));
        text3.setFill(Color.web("#363a38"));
        if(ObservableListBonReception.size()>0){
            boolean result = true ;
            StringSeleFournissuer = ObservableListBonReception.get(0).getFournisseur();
            int indise = 1;
            //Verifier si la produit exsiste déja
            while(indise<=ObservableListBonReception.size() && result){
               result =  ObservableListBonReception.get(indise-1).getFournisseur().equals(StringSeleFournissuer);
               indise++; 
            }
            
            //si le fournisseur n'exsiste pas
            if(!result){
                text3.setText("Les fournisseurs sélectionnés sont différents");
                messagecontrol.DetailMSG.getChildren().add(text3);
                messagecontrol.bouttonOK.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {
                        messagecontrol.stackpane.setVisible(false);
                    }
                });
                messagecontrol.ShowNotification();
                return false;
            }
            
            
            //si la facture existe déja
            String IdFournisseur = StringSeleFournissuer.split(" - ", -1)[0];
            FactureFrsDB FactureDB = new FactureFrsDB();
            FactureFrs Facture = FactureDB.getFactureFrs(null, TextFieldNumeroFac.getText(), IdFournisseur);
            if(Facture.getIdFactureFrs() != null){
                text3.setText("Cette facture existe déja");
                messagecontrol.DetailMSG.getChildren().add(text3);
                messagecontrol.bouttonOK.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {
                        messagecontrol.stackpane.setVisible(false);
                    }
                });
                messagecontrol.ShowNotification();
                return false;
            }
            
            return true;
        }
        else{
            //si la liste est vide
            text3.setText("Vous devez ajouter au moin un Bon Réception à la liste");
            messagecontrol.DetailMSG.getChildren().add(text3);
            messagecontrol.bouttonOK.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    messagecontrol.stackpane.setVisible(false);
                }
            });
            messagecontrol.ShowNotification();
            return false;
        }
        
    }
    
    private void AjouterFactureBL(){
        ButtonFactureBLAjouter.setOnAction(new EventHandler<ActionEvent>() {     //supprimer le message du suucés et reaficher les formulaires  
            @Override
            public void handle(ActionEvent event) {
               
                if( Controle.ContrNumeriqueNotnull(TextFieldNumeroFac, TextCltNumeroFac)  && 
                    ContrFournissuer()   &&
                    Controle.ContrHour(TextFieldHeurFac, TextCltHeurFac)  &&
                    Controle.ContrNullDatePicker(DatePickerDateFac, TextCltDateFac)){
                    
                    
                    ButtonFactureBLAjouter.setText("");
                    ButtonFactureBLAjouter.setDisable(true);
                    ProgressIndicatorSaveFactureBLAjouter.setVisible(true);
                    
                    Runnable task = new Runnable(){// Create a Runnable
                        public void run(){
                            Platform.runLater(new Runnable(){
                                @Override
                                public void run(){
                                    
                                    FactureFrs Facture = setFactureBRFrs();
                                    FactureFrsDB FactureDB = new FactureFrsDB();
                                    FactureDB.setFactureBRDB(Facture);

                                    try {
                                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/FactureFrs/FactureFrsDetail.fxml"));
                                        Parent ParentFxmlFournisseur = (Parent)fxmlLoader.load();

                                        FactureFrsDetailController FactureFrsDetail = fxmlLoader.getController();
                                        FactureFrsDetail.setDataFactureDetailFrs(Facture.getIdFactureFrs());
                                        FactureFrsDetail.PaneSucessFrs.setVisible(true);
                                        PaneFactureBRFrsAjouter.getChildren().clear();
                                        PaneFactureBRFrsAjouter.getChildren().add(ParentFxmlFournisseur);

                                    }catch (IOException ex) {
                                        Logger.getLogger(FactureFrsDetailController.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                            });	
                        }
                    };
                    
                    Thread backgroundThread = new Thread(task);// Run the task in a background thread
                    backgroundThread.setDaemon(true);// Terminate the running thread if the application exits
                    backgroundThread.start();
                }
                
                ButtonFactureBLAjouter.setText("Enregister Facture BR");
                ButtonFactureBLAjouter.setDisable(false);
                ProgressIndicatorSaveFactureBLAjouter.setVisible(false);
                 
            }
        });
        
    }
    
    public FactureFrs setFactureBRFrs(){
        
        FactureFrs FactureBRFrs = new FactureFrs();
        FactureBRFrs.setNumero(TextFieldNumeroFac.getText());
        FactureBRFrs.setHeurCreation(TextFieldHeurFac.getText());
        FactureBRFrs.setDateCreation(DatePickerDateFac.getValue().toString());
        
        String IdFournisseur = StringSeleFournissuer.split(" - ", -1)[0];
        Fournisseur Frs = new Fournisseur();
        Frs.setCode(IdFournisseur);
        FactureBRFrs.setFournisseur(Frs);
        
        FactureBRFrs.setDevise(ParametreSystem.CurrencySign);
        
        Profile profile= new Profile();
        profile.setIdprofile(User.idprofile);
        FactureBRFrs.setProfile(profile);
        
        FactureBRFrs.setLocal(ParametreSystem.NomLocalPC);
        
        float total_hors_tax_net = 0;
        float total_tva = 0;
        float net_a_payer = 0;
        
        ArrayList<String> listRefeProduct = new ArrayList<>();
        ArrayList<BonReceptionProduitList> listProd = new ArrayList<>();
        ObservableList<ListeProduit> ListProduit = FXCollections.observableArrayList() ;
        
        ObservableList<BonReceptionFrs> ListeBonReception =  FXCollections.observableArrayList() ;
        for(int i=0; i<ObservableListBonReception.size(); i++){
            BonReceptionFrs BonReception = BonRecepDB.getBonReceptionFrs(ObservableListBonReception.get(i).getCode(), null, null);
            ObservableList<BonReceptionProduitList> ObservableListProduit = BonReception.getListProduit();
            for(int j=0; j<ObservableListProduit.size();j++){
                listProd.add(ObservableListProduit.get(j));
                listRefeProduct.add(ObservableListProduit.get(j).getReference());
                float tva = Adaptateur.StringToFloat(ObservableListProduit.get(j).getTva());
                float total_hors_tax = Adaptateur.StringToFloat(ObservableListProduit.get(j).getPrixUnitaireHorsTaxenNet());
                total_tva += (total_hors_tax *  tva) /100 ;
                total_hors_tax_net += Adaptateur.StringToFloat(ObservableListProduit.get(j).getPrixUnitaireHorsTaxenNet());
                net_a_payer += Adaptateur.StringToFloat(ObservableListProduit.get(j).getMontant());
            }
            ListeBonReception.add(BonReception);
        }
        
        listRefeProduct = (ArrayList) listRefeProduct.stream().distinct().collect(Collectors.toList());
        for(String Refe : listRefeProduct){
            float quantite = 0;
            float p_u_h_t = 0;
            float p_u_h_t_net = 0;
            float tva = 0;
            float montant = 0;
            String designation = "";
            for(int j=0; j<listProd.size(); j++){
                if(Refe.equals(listProd.get(j).getReference())){
                    quantite += Adaptateur.StringToFloat(listProd.get(j).getQuantite());
                    p_u_h_t += Adaptateur.StringToFloat(listProd.get(j).getPrixUnitaireHorsTaxe());
                    p_u_h_t_net += Adaptateur.StringToFloat(listProd.get(j).getPrixUnitaireHorsTaxenNet());
                    tva = Adaptateur.StringToFloat(listProd.get(j).getTva());
                    montant +=  Adaptateur.StringToFloat(listProd.get(j).getMontant());
                    designation = listProd.get(j).getDesignation();
                }
            }
            ListProduit.add(new ListeProduit(Refe, designation, Adaptateur.ArrondFloatToString(quantite), Adaptateur.ArrondFloatToString(p_u_h_t), "0", Adaptateur.ArrondFloatToString(p_u_h_t_net), Adaptateur.ArrondFloatToString(tva), Adaptateur.ArrondFloatToString(montant)));
        }
        FactureBRFrs.setListProduit(ListProduit);
        
        FactureBRFrs.setTotalHorsTaxNet(Adaptateur.ArrondFloatToString(total_hors_tax_net));
        FactureBRFrs.setTotalTVA(Adaptateur.ArrondFloatToString(total_tva));
        FactureBRFrs.setRemise("0");
        FactureBRFrs.setTimbre(ParametreSystem.Timbre);
        FactureBRFrs.setListeBonReception(ListeBonReception);
        
        net_a_payer += Adaptateur.StringToFloat(ParametreSystem.Timbre);
        FactureBRFrs.setNetAPayer(Adaptateur.ArrondFloatToString(net_a_payer));
        
        return FactureBRFrs;
    }
    
    private void AffectBonReception(BonReceptionList BRList){
        //lorce qu'il y a plus que ligne
        if(ObservableListBonReception.size()>0){
           boolean result = false ;
           int indise = 1;
           //Verifier si la produit exsiste déja
           while(indise<=ObservableListBonReception.size() && !result){
               result =  ObservableListBonReception.get(indise-1).getCode().equals(BRList.getCode());
               indise++; 
           }
           //si le produit n'exsiste pas on la joute à la table view
           if(!result){
                ObservableListBonReception.add(BRList); 
            }
        }
        else{
             ObservableListBonReception.add(BRList);
        }
        CalculeFacture();
        TableViewBonReceptionSelected.setItems(ObservableListBonReception);
        TableViewBonReceptionSelected.refresh();
    }
    
    
    private void CalculeFacture(){
        float somme = 0;
        
        for(int i=0; i<ObservableListBonReception.size(); i++){
            somme += Adaptateur.ArrondStringToFloat(ObservableListBonReception.get(i).getNetPayer());
        }
        
        if(somme > 0){
            somme += Adaptateur.ArrondStringToFloat(ParametreSystem.Timbre);
            TextTotalFacture.setText(Adaptateur.ArrondFloatToString(somme)+" "+ParametreSystem.CurrencySign);
        }else{
            TextTotalFacture.setText("");
        }
        
        
    }
    
    
    private void RechecheBonReception(){
        TextFieldNumero.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                String numero = Adaptateur.addSlashes(TextFieldNumero.getText());
                if(numero.isEmpty()){
                    TableViewBonReception.setItems(null);
                }
                else{
                   getRechecheBonReception(" AND (BR.numero LIKE '"+numero+"%') ");
                }
                
            }
        });
        
        TextFieldNetPayer.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                String netpayer = TextFieldNetPayer.getText();
                if(netpayer.isEmpty()){
                    TableViewBonReception.setItems(null);
                }
                else{
                   getRechecheBonReception(" AND (BR.net_a_payer LIKE '"+netpayer+"%') ");
                }
            }
        });
        
        
        DatePickerDateReception.setOnAction(new EventHandler<ActionEvent>() {
            @Override 
            public void handle(ActionEvent actionEvent) {
                try{
                    getRechecheBonReception(" AND (DATE(BR.date_reception) = "+"'"+DatePickerDateReception.getValue().toString()+"')");
                }catch(Exception ex){}
            }
        });
        DatePickerDateReception.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                try{
                    String DateReception = DatePickerDateReception.getConverter().fromString(DatePickerDateReception.getEditor().getText()).toString();
                    getRechecheBonReception(" AND (DATE(BR.date_reception) = "+"'"+DateReception+"')");
                }catch(Exception ex){}
            }
        });
        
        
        TextFieldFournisseur.textProperty().addListener(new ChangeListener<String>() { 
            @Override 
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { 
                if(newValue.contains(" - ")){
                    String[] array = newValue.split(" - ", -1);
                    getRechecheBonReception(" AND (BR.id_fournisseur = '"+array[0]+"') ");
                }
            } 
        });
        
        
        ChoiceBoxLocalReception.valueProperty().addListener(new ChangeListener<String>() {
            @Override 
            public void changed(ObservableValue ov, String t, String ValLocal) {
                getRechecheBonReception(" AND (BR.local_reception LIKE '"+ValLocal+"%') ");
            }    
        });
    }
    
}
