import React, { useState, useEffect } from 'react';
import { MdCancel } from "react-icons/md";
import { AiOutlineEdit } from "react-icons/ai";
import TrainingForm from "./AddClassManual"
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Select from 'react-select'
import { getCookie } from 'react-use-cookie';
import { DataGrid, GridToolbar, frFR } from '@mui/x-data-grid';
import Footer from "./Fotter";
import tick_ko from "../mysy_img/tick_KO.png";
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';
import { AiFillCloseCircle, } from "react-icons/ai";
import parse from 'html-react-parser'
import { BsEye, BsFileText } from "react-icons/bs";
import { useHistory } from "react-router-dom";
import axios from "axios";
import { CiCoffeeBean, CiDesktop, CiFileOff } from "react-icons/ci";
import img_loading_spin from "./../mysy_img/mysy_spin_loading.gif";
import { MdAddCircleOutline, MdRemoveCircleOutline } from "react-icons/md";
import { LuScreenShare, LuScreenShareOff } from "react-icons/lu";
import MenuItem from '@mui/material/MenuItem';
import InputAdornment from '@mui/material/InputAdornment';
import Box from '@mui/material/Box';
import 'react-tooltip/dist/react-tooltip.css'
import { Tooltip } from 'react-tooltip'
import { FcCancel, FcApproval, FcAcceptDatabase, FcPrint } from "react-icons/fc";

const DistplayPartnerTraningsPage = (props) => {


    const history = useHistory();
    const [myApiResponse, setmyApiResponse] = useState("false");
    const filters = [
        { value: 'external_code', label: 'Code Formation' },
        { value: 'title', label: 'Titre' },
        { value: 'certif', label: 'Certification' }
    ]
    const [selectedfilt1, setselectedfilt1] = useState("");
    const [selectedfilt2, setselectedfilt2] = useState("");
    const [selectedfilt3, setselectedfilt3] = useState("");
    const [reftrainingtoupdate, setreftrainingtoupdate] = useState();
    const [externalcodetraining_toupdate, setexternalcodetraining_toupdate] = useState();
    const [updatetraining, setupdatetraining] = useState(false);



    function handleClick(event, cellValues) {

        var url = process.env.REACT_APP_API_URL + "myclass/api/check_partner_token_validity_v2/";

        var formData = new FormData();
        const stored_cookie = getCookie('tokenmysypart');
        formData.append("token", stored_cookie);
        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                console.log(' isValidToken ==> Success:', result['message'], "result['status'] = ", result['status']);

                if (String(result['status']) !== String("true")) {
                    alert("La session de connexion n'est pas valide");
                    history.push("/Connexion");
                }

                if (String(result['status']) === String("true")) {
                    Edittraining(event, cellValues);
                    //console.log(cellValues);
                }


            })
            .catch((error) => {
                console.error('Error:', error);


            });


    }

    const [selectionModel, setSelectionModel] = React.useState([]);
    const [rowss, setRows] = useState([]);
    const [tableData, setTableData] = useState([])

    const [refreshgrid, setrefreshgrid] = useState("")
    function GetAllClass_WOfilter(event) {
        var form = new FormData();

        //form.append("token","K3cw63eKokKSbV4spjQ48SUNnfy80yrXfA");
        const stored_cookie = getCookie('tokenmysypart');
        form.append("token", stored_cookie);

        var myurl = process.env.REACT_APP_API_URL + "myclass/api/get_partner_class/";

        //alert(" laaa");
        fetch(myurl,
            {
                method: 'POST',
                body: form,
            })
            .then((data) => data.json())
            .then((data) => {
                console.log('GetAllClass_WOfilter : Success:', data['message'], "data['status'] = ", data['status']);
                setTableData(data['message']);
                setRows(data['message']);

                //alert(" GetAllClass_WOfilter OKK "+refreshgrid);
                setrefreshgrid("1");


            }).catch((error) => {
                console.error('GetAllClass_WOfilter Error:', error);
                setmyApiResponse("false");
            });

    }

    function GetAllClass_new(event) {

        var form = new FormData();

        // Recuperation des parametres
        var filtre1 = p_filtre1;
        var filtre2 = p_filtre2;
        var filtre3 = p_filtre3;

        var filtre1_value = "";
        var filtre2_value = "";
        var filtre3_value = "";

        // Recuperation des valeurs de filtres

        if (p_filtre1_value) {
            filtre1_value = p_filtre1_value;
            form.append(filtre1, filtre1_value);
        }

        if (p_filtre2_value) {
            filtre2_value = p_filtre2_value;
            form.append(filtre2, filtre2_value);
        }

        if (p_filtre3_value) {
            filtre3_value = p_filtre3_value;
            form.append(filtre3, filtre3_value);
        }


        const stored_cookie = getCookie('tokenmysypart');
        form.append("token", stored_cookie);

        var myurl = process.env.REACT_APP_API_URL + "myclass/api/find_partner_class_like/";

        fetch(myurl,
            {
                method: 'POST',
                body: form,
            })
            .then((data) => data.json())
            .then((data) => {
                //console.log('Success:', data['message'], "data['status'] = ", data['status']);
                setTableData(data['message']);
                setRows(data['message']);
                if (String(data['status']) === String("false")) {
                    //console.log("erreur rrrr:" + data['status'])
                    setmyApiResponse("False");

                }
                else {
                    setmyApiResponse("True");

                }

            }).catch((error) => {
                console.error('Error:', error);
                setmyApiResponse("false");
            });

    }

    function GetAllClass_new_no_filter(event) {

        var form = new FormData();


        //form.append("token","K3cw63eKokKSbV4spjQ48SUNnfy80yrXfA");
        const stored_cookie = getCookie('tokenmysypart');
        form.append("token", stored_cookie);

        var myurl = process.env.REACT_APP_API_URL + "myclass/api/find_partner_class_like/";
        fetch(myurl,
            {
                method: 'POST',
                body: form,
            })
            .then((data) => data.json())
            .then((data) => {
                //console.log('Success:', data['message'], "data['status'] = ", data['status']);
                setTableData(data['message']);
                setRows(data['message']);
                if (String(data['status']) === String("false")) {
                    //console.log("erreur rrrr:" + data['status'])
                    setmyApiResponse("False");

                }
                else {
                    setmyApiResponse("True");

                }

            }).catch((error) => {
                console.error('Error:', error);
                setmyApiResponse("false");
            });

    }

    const [ismobilephone_columns_hide, setismobilephone_columns_hide] = useState(false);

    const [datagrid_columns_size_model1, setdatagrid_columns_size_model1] = useState(200);
    const [datagrid_columns_size_model2, setdatagrid_columns_size_model2] = useState(80);

    const columns = [
        { field: 'id', headerName: 'id', hide: true },
        { field: 'lms_class_code', headerName: 'lms_class_code', hide: true },
        { field: 'zone_diffusion', headerName: 'zone_diffusion', hide: true },
        { field: 'internal_url', headerName: 'internal_url', hide: true },
        { field: 'external_code', headerName: 'Code Formation', width: datagrid_columns_size_model1, hideable: false, resizable: true },
        { field: 'title', headerName: 'Titre', width: datagrid_columns_size_model1, hideable: false, },
        { field: 'domain', headerName: 'Domaine', width: datagrid_columns_size_model1, hideable: true, },
        { field: 'metier', headerName: 'Métier', width: datagrid_columns_size_model1, hideable: true, hide: true },
        { field: 'url', headerName: 'lien', width: datagrid_columns_size_model1, hideable: true, hide: true },
        { field: 'description', headerName: 'Description', width: datagrid_columns_size_model1, hide: ismobilephone_columns_hide, resizable: true, flex: 1 },

        { field: 'price', headerName: 'Prix', width: datagrid_columns_size_model2, align: "center", resizable: true, hide: ismobilephone_columns_hide },
        {
            field: 'published', headerName: 'Publié', width: datagrid_columns_size_model2, align: "center", resizable: true,
            valueFormatter: (params) => {
                if (String(params.value) === "0")
                    return "Non";
                else if (String(params.value) === "1")
                    return "Oui";
                else
                    return "?";
            },
        },
        {
            field: "management", headerName: 'Gestion', width: datagrid_columns_size_model2,
            renderCell: (cellValues) => {
                return (

                    <Button style={{ "marginLeft": "auto", "marginRight": "auto", "cursor": "pointer" }}

                        onClick={(event) => {
                            handleClickManagement(event, cellValues);
                        }}
                    >
                        <BsFileText />

                    </Button>

                );
            }
        },
        {
            field: "visual", headerName: 'Visualiser', width: datagrid_columns_size_model2,
            renderCell: (cellValues) => {
                return (

                    <Button style={{ "marginLeft": "auto", "marginRight": "auto", "cursor": "pointer" }}

                        onClick={(event) => {
                            Visualiser(event, cellValues);
                        }}
                    >
                        <BsEye />

                    </Button>

                );
            }
        },
        {
            field: "Print", headerName: 'Editer', width: datagrid_columns_size_model2,
            renderCell: (cellValues) => {
                return (

                    <Button style={{ "marginLeft": "auto", "marginRight": "auto", "cursor": "pointer" }}

                        onClick={(event) => {
                            handleClick(event, cellValues);
                        }}
                    >
                        <AiOutlineEdit />

                    </Button>

                );
            }
        },

        {
            field: "push_to_lms", headerName: 'Push Elearning', width: datagrid_columns_size_model2,
            renderCell: (cellValues) => {
                return (
                    <nav>



                        <Popup
                            trigger={<Button style={{ "marginLeft": "auto", "marginRight": "auto", "cursor": "pointer" }}

                                onClick={(event) => {
                                    handlepush_to_lms(event, cellValues);
                                }}
                            >

                                {cellValues.row.lms_class_code && String(cellValues.row.lms_class_code).length > 2 && <CiFileOff />}
                                {cellValues.row.lms_class_code && String(cellValues.row.lms_class_code).length <= 2 && <CiDesktop />}
                                {!cellValues.row.lms_class_code && <CiDesktop />}

                            </Button>}

                            modal
                            nested
                            position="center center"
                        >
                            {close => (
                                <div>
                                    <button className="gest_close" onClick={close}>
                                        &times;
                                    </button>
                                    <div className="gest_header"> MySy Information </div>
                                    <div className="gest_content">
                                        {' '}

                                        /!\ Important : Confirmer la publication de la formation dans l'eapce E-Learning.
                                        Vous allez écraser d'eventuelles informations déjà présente dans le e-Learning, pour cette formation.
                                    </div>
                                    <div className="gest_actions">
                                        <div style={{ "width": "45%", "float": "left" }}>
                                            <button className="gest_bton_popup" onClick={(event) => {
                                                handlepush_to_lms(event, cellValues);
                                                close();
                                            }}> Valider </button>

                                        </div>
                                        <div style={{ "width": "45%", "float": "right" }}>
                                            <button
                                                className="gest_bton_popup"
                                                onClick={() => {
                                                    //console.log('modal closed ');
                                                    close();
                                                }}
                                            >
                                                Annuler
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </Popup>
                    </nav>

                );
            }
        },

    ]


    function Visualiser(event, cellValues) {


        var url = process.env.REACT_APP_API_URL + "myclass/api/check_partner_token_validity_v2/";

        var formData = new FormData();
        const stored_cookie = getCookie('tokenmysypart');
        formData.append("token", stored_cookie);
        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                console.log(' isValidToken ==> Success:', result['message'], "result['status'] = ", result['status']);

                if (String(result['status']) !== String("true")) {
                    alert("La session de connexion n'est pas valide");
                    history.push("/Connexion");
                }
                if (String(result['status']) === String("true")) {
                    // On ne visualise que les formations publiées
                    if (cellValues.row.published !== "1") {
                        alert(" Vous devez publier la formation pour la visualiser ");
                        return;
                    }
                    window.open(
                        "/Display-Detail-formation/" + cellValues.row.internal_url,
                        '_blank'
                    );
                }


            })
            .catch((error) => {
                console.error('Error:', error);


            });

    }




    function handleClickManagement(event, cellValues) {

        // Verification de la validité du token avant action.
        var url = process.env.REACT_APP_API_URL + "myclass/api/check_partner_token_validity_v2/";

        var formData = new FormData();
        const stored_cookie = getCookie('tokenmysypart');
        formData.append("token", stored_cookie);
        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                console.log(' isValidToken ==> Success:', result['message'], "result['status'] = ", result['status']);

                if (String(result['status']) !== String("true")) {
                    alert("La session de connexion n'est pas valide");
                    history.push("/Connexion");
                }
                else if (String(result['status']) === String("true")) {
                    window.open(
                        "/GestionAdministrative/" + cellValues.row.internal_url,
                        '_blank'
                    );
                }


            })
            .catch((error) => {
                console.error('Error:', error);


            });

        // Fin verification


    }


    function Edittraining(event, cellValues) {

        setreftrainingtoupdate(cellValues.row.internal_url);
        setexternalcodetraining_toupdate(cellValues.row.external_code);
        setupdatetraining(true);

    }

    function selectedFilter1(event) {
        setselectedfilt1(event.value);
    }

    function selectedFilter2(event) {
        setselectedfilt2(event.value);
    }

    function selectedFilter3(event) {
        setselectedfilt3(event.value);
    }

    function CancelFiltre2(event) {
        setselectedfilt2("");
    }

    function CancelFiltre3(event) {
        setselectedfilt3("");
    }

    function closeTrainingForm() {
        setupdatetraining(false);
    }

    const [selectedtraining, setselectedtraining] = useState([])

    function GetSelectedRowsTraining() {
        ///alert(" les lignes slected sont :  " + selectionModel + " nb item = " + selectionModel.length);
        //const selectedRowsData = selectionModel.map((id) => rowss.find((row) => row.id === id));
        //console.log(rowss[0]);
        var tab_tmp = []
        for (var i = 0; i < selectionModel.length; i++) {
            var myid = parseInt(String(selectionModel[i]));
            var line = JSON.parse(rowss[myid]);
            tab_tmp.push(line.internal_url);
            //console.log(rowss[myid]['external_code']);
        }
        setselectedtraining(tab_tmp);
        return tab_tmp;

    }


    // Fonction de verification de la validité d'un token.
    function isValidToken() {

        var url = process.env.REACT_APP_API_URL + "myclass/api/check_partner_token_validity_v2/";

        var formData = new FormData();
        const stored_cookie = getCookie('tokenmysypart');
        formData.append("token", stored_cookie);
        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                console.log(' isValidToken ==> Success:', result['message'], "result['status'] = ", result['status']);

                if (String(result['status']) !== String("true")) {
                    alert("La session de connexion n'est pas valide");
                    history.push("/Connexion");
                }


            })
            .catch((error) => {
                console.error('Error:', error);


            });

    }



    function Unpublish_class(tab_class) {

        var url = process.env.REACT_APP_API_URL + "myclass/api/unpublish_class/";


        for (var i = 0; i < tab_class.length; i++) {
            //console.log(" position = "+i+"  val = "+tab_class[i]);
            //alert(" debut desactivation de la formation " + tab_class[i]);
            var formData = new FormData();
            const stored_cookie = getCookie('tokenmysypart');
            formData.append("token", stored_cookie);
            formData.append("internal_url", tab_class[i]);
            fetch(
                url,
                {
                    method: 'POST',
                    body: formData,
                }
            )
                .then((response) => response.json())
                .then((result) => {
                    //console.log('Success:', result['message'], "result['status'] = ", result['status']);

                    if (String(result['status']) === String("true")) {
                        //alert(" OK pour la formation :" + tab_class[i]);
                    }

                })
                .catch((error) => {
                    console.error('Error:', error);
                    //alert(" KOO pour la formation :" + tab_class[i]);

                });

        }
    }

    function Publish_class(tab_class) {

        var url = process.env.REACT_APP_API_URL + "myclass/api/pusblish_class/";

        for (var i = 0; i < tab_class.length; i++) {

            //alert(" debut desactivation de la formation " + tab_class[i]);
            //console.log(" NB = "+i+"  id = "+tab_class[i]);
            var formData = new FormData();
            const stored_cookie = getCookie('tokenmysypart');
            formData.append("token", stored_cookie);
            formData.append("internal_url", tab_class[i]);
            fetch(
                url,
                {
                    method: 'POST',
                    body: formData,
                }
            )
                .then((response) => response.json())
                .then((result) => {
                    //console.log('Success:', result['message'], "result['status'] = ", result['status']);

                    if (String(result['status']) === String("true")) {
                        //alert(" OK pour la formation :" + tab_class[i]);
                    }

                })
                .catch((error) => {
                    console.error('Error:', error);
                    //alert(" KOO pour la formation :" + tab_class[i]);

                });

        }
    }

    function Delete_class(tab_class) {

        var url = process.env.REACT_APP_API_URL + "myclass/api/disable_class/";

        for (var i = 0; i < tab_class.length; i++) {

            //alert(" debut desactivation de la formation " + tab_class[i]);
            var formData = new FormData();
            const stored_cookie = getCookie('tokenmysypart');
            formData.append("token", stored_cookie);
            formData.append("internal_url", tab_class[i]);
            fetch(
                url,
                {
                    method: 'POST',
                    body: formData,
                }
            )
                .then((response) => response.json())
                .then((result) => {
                    //console.log('Success:', result['message'], "result['status'] = ", result['status']);

                    if (String(result['status']) === String("true")) {
                        //alert(" OK pour la formation :" + tab_class[i]);
                    }

                })
                .catch((error) => {
                    console.error('Error:', error);
                    //alert(" KOO pour la formation :" + tab_class[i]);

                });

        }
    }


    function ActionMass(e) {

        // On vide le datagrid pour faire un refresj
        setRows([]);
        //return;

        var actionenmasse = ""
        if (document.getElementById("actionmass")) {
            actionenmasse = document.getElementById("actionmass").value;
        }

        var liste_formation = GetSelectedRowsTraining();



        if (String(actionenmasse) === String("depublier")) {

            Unpublish_class(liste_formation);
            GetAllClass_WOfilter();
        }

        else if (String(actionenmasse) === String("publier")) {
            Publish_class(liste_formation);
            GetAllClass_WOfilter();
        }

        else if (String(actionenmasse) === String("supprimer")) {
            Delete_class(liste_formation);
            GetAllClass_WOfilter();
        }


    }

    const [ismobilephone, setismobilephone] = useState();
    useEffect(() => {
        //GetAllClass();
        GetAllClass_new();
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        });

        let windowWidth = window.innerWidth;
        if (windowWidth < 1001) {
            setismobilephone_columns_hide(true);
            setdatagrid_columns_size_model2(10);
        }
    }, []);

    function Clearselectedfilt1() {
        setselectedfilt1("");
    }


    const [isLoading, setLoading] = useState();


    const [handlepush_to_lms_api, sethandlepush_to_lms_api] = useState("");
    const [handlepush_to_lms_result, sethandlepush_to_lms_result] = useState("");
    const [handlepush_to_lms_message, sethandlepush_to_lms_message] = useState("");

    function handlepush_to_lms(event, cellValues) {

        if (cellValues.row.lms_class_code && String(cellValues.row.lms_class_code).length > 2) {
            alert(" Cette formation est déjà publiée sur la plateforme de E-Learning");
            return;
        }

        setLoading(true);

        //console.log(" ### event.target.value = ", event.target.value);
        const formData = new FormData();
        const url = process.env.REACT_APP_API_URL + "myclass/api/Push_Class_To_MySy_LMS/";

        const stored_cookie = getCookie('tokenmysypart');
        formData.append("token", stored_cookie);
        formData.append('class_internal_url', cellValues.row.internal_url);

        axios.post(url, formData).then(res => {
            //console.log(" In getCurrentUserData  res.data.status = " + res.data.status);
            //console.log(" In getCurrentUserData  res.data.message = " + res.data.message);
            if (String(res.data.status) === "true") {

                sethandlepush_to_lms_api("true");
                sethandlepush_to_lms_result(res.data.message);

                setLoading(false);
                GetAllClass_new();
                alert(res.data.message);


            }
            else if (String(res.data.status) === String("Err_Connexion")) {
                alert('Erreur: ' + res.data.message);
                history.push("/Connexion");
                return;
            }
            else {

                sethandlepush_to_lms_api("false");
                sethandlepush_to_lms_message(res.data.message);
                setLoading(false);
                alert("Erreur : " + res.data.message);
            }

        }).catch((error) => {
            console.warn('Erro handlepush_to_lms = ', error);
            sethandlepush_to_lms_api("false");
            setLoading(false);
        })
    }

    const [p_filtre1, setp_filtre1] = useState();
    const [p_filtre1_value, setp_filtre1_value] = useState();

    const [p_filtre2, setp_filtre2] = useState();
    const [p_filtre2_value, setp_filtre2_value] = useState();

    const [p_filtre3, setp_filtre3] = useState();
    const [p_filtre3_value, setp_filtre3_value] = useState();

    function clean_all_filters() {
        setp_filtre1();
        setp_filtre1_value();
        setp_filtre2();
        setp_filtre2_value();

        setp_filtre3();
        setp_filtre3_value();
        GetAllClass_new_no_filter();
    }



    const datagridSx = {
        borderRadius: 2,
        marginRight: 1,
        marginLeft: 1,
        border: 0,
        overflowX: 'scroll',
        "& .MuiDataGrid-main": { borderRadius: 0 },
        /*'& div[data-rowIndex][role="row"]:nth-of-type(5n-4)': {
          color: "blue",
          fontSize: 18,
          //risky
          minHeight: "60px !important",
          height: 60,
          "& div": {
            minHeight: "60px !important",
            height: 60,
            lineHeight: "59px !important"
          }
        },*/
        "& .MuiDataGrid-virtualScrollerRenderZone": {
            "& .MuiDataGrid-row": {
                "&:nth-child(2n)": { backgroundColor: "rgba(235, 235, 235, .7)" }
            }
        },
        "& .MuiDataGrid-columnHeaders": {
            backgroundColor: "#c8cfd5",
            color: "black",
            fontSize: 16
        }
    };


    const [actionmass_ftion_val, setactionmass_ftion_val] = useState();
    const actionmass_ftion = (event) => {
        const value = event.target.value;


        if (String(value) === "publier" || String(value) === "depublier" || String(value) === "supprmier") {
            setactionmass_ftion_val(value);
        }
        else {
            setactionmass_ftion_val();
        }
    }


    function GetSelectedRows_ftion_Ids() {


        var tab_tmp = []
        for (var i = 0; i < selectionModel.length; i++) {
            //console.log(" ### selectionModel_insc[i] = ", selectionModel_insc[i]);
            var myid = parseInt(String(selectionModel[i]));
            //var line = JSON.parse(rowss[myid]);
            tab_tmp.push(myid);
        }
        return tab_tmp;

    }

    async function actionmass_ftion_Traitemet() {


        var liste_formation = GetSelectedRowsTraining();

        console.log(" liste_formation = ", liste_formation);
        console.log(" actionmass_ftion_val = ", actionmass_ftion_val);

        if (String(actionmass_ftion_val) === String("depublier")) {

            Unpublish_class(liste_formation);
            GetAllClass_WOfilter();
            window.location.reload();
        }

        else if (String(actionmass_ftion_val) === String("publier")) {
            Publish_class(liste_formation);
            GetAllClass_WOfilter();
            window.location.reload();
        }

        else if (String(actionmass_ftion_val) === String("supprimer")) {
            Delete_class(liste_formation);
            GetAllClass_WOfilter();
            window.location.reload();
        }

    }

    const sleep = (milliseconds) => {
        return new Promise(resolve => setTimeout(resolve, milliseconds))
    }


    return (

        <div className='displaypartnertrainingpagination'>
            {isLoading && <div className="loader-container">
                <div className="mysy_spinner">  <img src={img_loading_spin} />  </div>
            </div>}

            {updatetraining && <div>

                <div className='detail_training'>
                    <TrainingForm mytrainingclass={{
                        'ref': reftrainingtoupdate, 'class_external_code': externalcodetraining_toupdate
                    }} ispending={props.ispending} currentpack={props.currentpack} closeTrainingForm={closeTrainingForm} />
                </div>


                <hr />
                <div onClick={closeTrainingForm} className="parter_div_filtrer_center">
                    <AiFillCloseCircle alt="Fermer detail formation" />FERMER
                </div>

            </div>
            }

            <div className="titre1">  Utilisez les filtres !</div>
            <div className="div_row" style={{ "marginBottom": "5px" }}>
                <div className="div_row_gauche texte_area_filter" >
                    <TextField
                        name="filtre1"
                        label="Choisir un champ"
                        select
                        sx={{ m: 1, width: '100%' }}
                        value={p_filtre1}
                        onChange={(e) => {
                            setp_filtre1(e.target.value)
                        }}
                    >
                        <MenuItem value="external_code" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }}>Code externe formation &nbsp;&nbsp;</MenuItem>
                        <MenuItem value="title" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Titre Formation &nbsp;</MenuItem>
                        <MenuItem value="certif" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Certifiée &nbsp;</MenuItem>

                    </TextField>
                </div>
                <div className="div_row_droite texte_area_filter_value" >
                    {p_filtre1 &&
                        <TextField
                            sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}
                            required
                            name="filtre1_value"
                            id="filtre1_value"

                            InputLabelProps={{
                                shrink: true,
                            }}
                            disabled={false}
                            className="disabled_style"
                            value={p_filtre1_value}
                            onChange={(e) => { setp_filtre1_value(e.target.value); }}
                            InputProps={{
                                endAdornment: (
                                    <InputAdornment position="end">
                                        <AiFillCloseCircle
                                            style={{ 'cursor': "pointer", "color": "orangered" }}
                                            onClick={(e) => {
                                                setp_filtre1_value("");
                                            }} />
                                    </InputAdornment>
                                ),
                            }}

                        />
                    }

                </div>
                {p_filtre1 && <div className='filter_bton_add'>
                    <Tooltip id="my-tooltip01" style={{ "fontSize": "12px" }} />
                    <a data-tooltip-id="my-tooltip01" data-tooltip-content="Ajouter une nouvelle ligne de filtre">
                        &nbsp; <MdAddCircleOutline onClick={(e) => {
                            setp_filtre2("1");
                        }} />
                    </a>
                </div>}
                {p_filtre1 && <div className='filter_bton_add'>
                    <Tooltip id="my-tooltip02" style={{ "fontSize": "12px" }} />
                    <a data-tooltip-id="my-tooltip02" data-tooltip-content="Supprimer cette ligne de filtre">
                        &nbsp; <MdRemoveCircleOutline onClick={(e) => {
                            setp_filtre1();
                            setp_filtre1_value();
                        }}
                        />
                    </a>
                </div>}


            </div>

            {p_filtre2 &&
                <div className="div_row" style={{ "marginBottom": "5px" }}>
                    <div className="div_row_gauche texte_area_filter">
                        <TextField
                            name="filtre2"
                            label="Choisir un champ"
                            select
                            sx={{ m: 1, width: '100%' }}
                            options={filters}
                            value={p_filtre2}
                            onChange={(e) => {
                                setp_filtre2(e.target.value)
                            }}
                        >

                            <MenuItem value="external_code" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }}>Code externe formation &nbsp;&nbsp;</MenuItem>
                            <MenuItem value="title" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Titre Formation &nbsp;</MenuItem>
                            <MenuItem value="certif" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Certifiée &nbsp;</MenuItem>

                        </TextField>
                    </div>
                    <div className="div_row_droite texte_area_filter_value" style={{ "marginTop": "0.5rem" }}>
                        {String(p_filtre2).length > 3 &&
                            <TextField
                                sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}
                                required
                                name="filtre2_value"
                                id="filtre2_value"

                                InputLabelProps={{
                                    shrink: true,
                                }}
                                disabled={false}
                                className="disabled_style"
                                value={p_filtre2_value}
                                onChange={(e) => setp_filtre2_value(e.target.value)}
                                InputProps={{
                                    endAdornment: (
                                        <InputAdornment position="end">
                                            <AiFillCloseCircle
                                                style={{ 'cursor': "pointer", "color": "orangered" }}
                                                onClick={(e) => {
                                                    setp_filtre2_value("");
                                                }} />
                                        </InputAdornment>
                                    ),
                                }}

                            />}
                    </div>

                    {String(p_filtre2).length > 3 && <div className='filter_bton_add' >
                        <Tooltip id="my-tooltip03" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip03" data-tooltip-content="Ajouter une nouvelle ligne de filtre">
                            &nbsp; <MdAddCircleOutline
                                onClick={(e) => {
                                    setp_filtre3("1");
                                }}
                            />
                        </a>
                    </div>}

                    {String(p_filtre2).length > 3 && <div className='filter_bton_add'>
                        <Tooltip id="my-tooltip04" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip04" data-tooltip-content="Supprimer cette ligne de filtre">
                            &nbsp; <MdRemoveCircleOutline
                                onClick={(e) => {
                                    setp_filtre2();
                                    setp_filtre2_value();
                                }}
                            />
                        </a>
                    </div>}

                </div>
            }


            {p_filtre3 &&
                <div className="div_row" style={{ "marginBottom": "5px" }}>
                    <div className="div_row_gauche texte_area_filter">
                        <TextField
                            name="filtre3"
                            label="Choisir un champ"
                            select
                            sx={{ m: 1, width: '100%' }}
                            options={filters}
                            value={p_filtre3}
                            onChange={(e) => {
                                setp_filtre3(e.target.value)
                            }}
                        >

                            <MenuItem value="external_code" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }}>Code externe formation &nbsp;&nbsp;</MenuItem>
                            <MenuItem value="title" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Titre Formation &nbsp;</MenuItem>
                            <MenuItem value="certif" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Certifiée &nbsp;</MenuItem>

                        </TextField>
                    </div>
                    <div className="div_row_droite texte_area_filter_value" style={{ "marginTop": "0.5rem" }}>
                        {String(p_filtre3).length > 3 &&
                            <TextField
                                sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}
                                required
                                name="filtre3_value"
                                id="filtre3_value"

                                InputLabelProps={{
                                    shrink: true,
                                }}
                                disabled={false}
                                className="disabled_style"
                                value={p_filtre3_value}
                                onChange={(e) => setp_filtre3_value(e.target.value)}
                                InputProps={{
                                    endAdornment: (
                                        <InputAdornment position="end">
                                            <AiFillCloseCircle
                                                style={{ 'cursor': "pointer", "color": "orangered" }}
                                                onClick={(e) => {
                                                    setp_filtre3_value("");
                                                }} />
                                        </InputAdornment>
                                    ),
                                }}

                            />}
                    </div>

                    {String(p_filtre3).length > 3 && <div className='filter_bton_add'>
                        <Tooltip id="my-tooltip05" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip05" data-tooltip-content="Supprimer cette ligne de filtre">
                            &nbsp; <MdRemoveCircleOutline onClick={(e) => {
                                setp_filtre3();
                                setp_filtre3_value();
                            }} />
                        </a>
                    </div>}
                </div>
            }



            {<div className="div_row" style={{ "border": "None", "color": "orange", "textAlign": "center" }}>

                <div className="div_row_gauche">
                    <Button variant="contained" className="bton_enreg" onClick={GetAllClass_new}>Rechercher
                    </Button>
                </div>

                <div className="div_row_droite">
                    <Button variant="contained" className="bton_annule" onClick={clean_all_filters}>Annuler
                    </Button>

                </div>

            </div>}



            <div className="div_row"> &nbsp; </div>

            <div style={{ height: "850 px", "width": "100%" }}>

                {String(myApiResponse) === "False" && <div className='koUpdateData'>
                    Impossible de traiter la demande
                </div>}


                {String(myApiResponse) === "True" && <div style={{ height: "800px", width: '100%', paddingRight: '1px' }}>
                    &nbsp;

                    <Box
                        sx={{
                            height: "700px",
                            width: '100%',
                            paddingRight: '2px',
                            '& .cell--published': {
                                backgroundColor: '#a2cf6e',
                                color: '#1a3e72',
                                fontWeight: 'bold',
                            },
                            '& .cell--unpublished': {
                                backgroundColor: '#ffac33',
                                color: '#1a3e72',
                                fontWeight: 'light',
                            },
                            '& .line--published': {
                                backgroundColor: '#E6F7C8',
                                color: 'black',
                            },
                            '& .line--unpublished': {
                                backgroundColor: '#FAD7A0',
                                color: 'black',
                            },

                        }}
                    >
                        <DataGrid
                            checkboxSelection
                            onSelectionModelChange={(newSelectionModel) => {
                                setSelectionModel(newSelectionModel);
                                //console.log("ch selected--" + newSelectionModel);
                            }}
                            selectionModel={selectionModel}
                            localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                            rows={rowss.map((item, index) => (

                                {
                                    id: index,
                                    internal_url: JSON.parse(item).internal_url,
                                    zone_diffusion: JSON.parse(item).zone_diffusion_str,
                                    external_code: JSON.parse(item).external_code,
                                    title: parse((JSON.parse(item).title).replace(/(<([^>]+)>)/ig, '')),
                                    domain: JSON.parse(item).domaine,
                                    metier: JSON.parse(item).metier,
                                    url: JSON.parse(item).url,
                                    price: JSON.parse(item).price,
                                    description: parse((JSON.parse(item).description).replace(/(<([^>]+)>)/ig, '')),
                                    published: JSON.parse(item).published,
                                    lms_class_code: JSON.parse(item).lms_class_code,
                                }
                            ))}



                            columns={columns}
                            pageSize={10}
                            className="datagridclass"

                            rowsPerPageOptions={[10]}
                            //disableSelectionOnClick
                            components={{
                                Toolbar: GridToolbar,
                            }}
                            sx={datagridSx}
                            getCellClassName={(params) => {
                                if (params.field === 'published' && String(params.value) === "1") {
                                    return 'cell--published';
                                }

                                if (params.field === "published" && String(params.value) !== "1") {
                                    return 'cell--unpublished'
                                }

                            }}
                            getRowClassName={(params) => {
                                if (String(params.row.published) === "1") {
                                    return 'line--published';
                                }

                                if (String(params.row.published) !== "1") {
                                    return 'line--unpublished';
                                }
                            }}

                        />
                    </Box>


                </div>}
            </div>
            <br />
            <div className="div_row">
                {selectionModel && selectionModel.length >= 1 && <div className="block_en_mass">
                    <nav >Traitement en masse </nav>
                    &nbsp;


                    <TextField

                        select
                        InputLabelProps={{
                            shrink: true,
                        }}
                        inputProps={{ min: "0", max: "1", step: "1" }}
                        disabled={false}
                        className="block_en_mass_select"

                        value={actionmass_ftion_val}
                        onChange={actionmass_ftion}
                    >
                        <MenuItem value="" style={{ "paddingLeft": "5px", "textAlign": "left" }}>Action &nbsp;&nbsp;</MenuItem>
                        <MenuItem value="publier" style={{ "paddingLeft": "5px", "textAlign": "left" }}>Publier &nbsp;</MenuItem>
                        <MenuItem value="depublier" style={{ "paddingLeft": "5px", "textAlign": "left" }}>Dépublier &nbsp;</MenuItem>
                        <MenuItem value="supprmier" style={{ "paddingLeft": "5px", "textAlign": "left" }}>Supprimer &nbsp;</MenuItem>

                    </TextField>

                    {actionmass_ftion_val && <nav className='block_en_mass_bton_action'>
                        <Popup
                            trigger={<Button className="bton_enreg" style={{ "width": "90%" }}>

                                <FcAcceptDatabase /> Traiter

                            </Button>}
                            modal
                            nested
                            position="center center"

                        >

                            {close => (
                                <div>
                                    <button className="gest_close" onClick={close}>
                                        &times;
                                    </button>
                                    <div className="gest_header"> MySy Information </div>
                                    <div className="gest_content">
                                        {' '}

                                        Confirmer l'action <b> {actionmass_ftion_val} </b> en masse.
                                    </div>
                                    <div className="gest_actions">
                                        <div style={{ "width": "45%", "float": "left" }}>
                                            <button className="gest_bton_popup" onClick={(event) => {
                                                actionmass_ftion_Traitemet();
                                                close();
                                            }}> Valider </button>

                                        </div>
                                        <div style={{ "width": "45%", "float": "right" }}>
                                            <button
                                                className="gest_bton_popup"
                                                onClick={() => {
                                                    //console.log('modal closed ');
                                                    close();
                                                }}
                                            >
                                                Annuler
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </Popup>
                    </nav>
                    }

                </div>}
            </div>

        </div>


    )

}

export default DistplayPartnerTraningsPage;