import React, { useRef, useState, useEffect } from "react";
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css
import Button from '@mui/material/Button';
import axios from "axios";
import { useParams } from 'react-router-dom';
import { getCookie, setCookie } from 'react-use-cookie';
import { useHistory } from "react-router-dom";
import CheckOut from "./CheckOut";
import {
    DataGrid, frFR, GridToolbar,

} from '@mui/x-data-grid';
import * as XLSX from 'xlsx';
import { Fab } from "@material-ui/core";
import { IoMdAddCircle, IoIosRemoveCircleOutline } from "react-icons/io";

import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { Editor } from '@tinymce/tinymce-react';
import parse from 'html-react-parser';
import { FcViewDetails, FcDisapprove, FcInfo } from "react-icons/fc";
import 'react-tooltip/dist/react-tooltip.css'
import { Tooltip } from 'react-tooltip'
import add_plus from "../mysy_img/plus.png";
import excel_icone from "../mysy_img/excel_icone.png";
import participants from "../mysy_img/participants.png";
import fileDownload from 'js-file-download'
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';
import { FcCancel, FcApproval, FcAcceptDatabase, FcPrint } from "react-icons/fc";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { format } from 'date-fns'
import moment from "moment";
import InputAdornment from '@mui/material/InputAdornment';
import { AiFillCloseCircle } from "react-icons/ai";
import Box from '@mui/material/Box';
import { Typography, LinearProgress, sliderClasses } from '@mui/material';
import styled from 'styled-components';
import { CiTrash } from "react-icons/ci";
import { MdAddCircleOutline, MdRemoveCircleOutline } from "react-icons/md";
import Autocomplete from '@mui/material/Autocomplete';
import img_loading_spin from "./../mysy_img/mysy_spin_loading.gif";
import { IoAddCircleOutline, IoCloseCircleOutline } from "react-icons/io5";
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Link from '@mui/material/Link';
import { PiDotsThree } from "react-icons/pi";
import { gridClasses } from '@mui/x-data-grid';
import {
    GridToolbarContainer, GridToolbarExport, GridToolbarColumnsButton,
    GridToolbarFilterButton, GridToolbarDensitySelector, GridToolbarExportContainer, useGridApiContext,
    gridFilteredSortedRowIdsSelector,
    gridVisibleColumnFieldsSelector,
    GridValueGetterParams,
    GridPreferencePanelsValue,

} from '@mui/x-data-grid';
import AttachFileIcon from '@mui/icons-material/AttachFile';
//import { utils, writeFileXLSX } from "xlsx";
import { ContextMenu, ContextMenuTrigger } from "react-contextmenu";
import zIndex from "@material-ui/core/styles/zIndex";
import { FcOpenedFolder } from "react-icons/fc";
import Module_Historique_Action from "./Module_Historique_Action";
import { GridExportCsvOptions } from '@mui/x-data-grid';


const Intranet_Tous_Documents = (props) => {

    const { action, orderid } = useParams();


    const history = useHistory();
    const [submenu, setsubmenu] = useState("");
    const [rowss, setRows] = useState([]);
    const [rowss_total_data, setRows_total_data] = useState([]);
    const [selectionModel, setSelectionModel] = React.useState([]);

    const [rows_invoice_lines, setrows_invoice_lines] = useState([]);
    const [selectionModel_invoice_lines, setselectionModel_invoice_lines] = React.useState([]);
    const [gridline_id, setgridline_id] = useState("");
    var date_today_90j = new Date();
    date_today_90j.setDate(date_today_90j.getDate() + 90);

    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();

    const [p_filtre4, setp_filtre4] = useState("");
    const [p_filtre4_value, setp_filtre4_value] = useState();

    function ExpandableCell_50({ value }) {
        const [expanded, setExpanded] = React.useState(false);

        return (
            <nav>
                {value && <div style={{ paddingLeft: "5px", paddingRight: "15px", "display": "block", wordBreak: "break-all" }}>

                    {expanded ? value : String(value).slice(0, 50)}&nbsp;
                    {value.length > 50 && (
                        // eslint-disable-next-line jsx-a11y/anchor-is-valid
                        <Link
                            type="button"
                            component="button"
                            sx={{ fontSize: 'inherit' }}
                            onClick={() => setExpanded(!expanded)}
                        >
                            {expanded ? <nav>  <PiDotsThree />Réduire</nav> : <nav> <PiDotsThree />Voir</nav>}
                        </Link>
                    )}
                </div>}

                {!value && <div style={{ paddingLeft: "5px", paddingRight: "15px", "display": "block", wordBreak: "break-all" }}>
                    &nbsp;
                </div>
                }
            </nav>
        );
    }



    const columns = [
        { field: '_id', headerName: '_id', hide: true, disableExport: true, },
        { field: 'id', headerName: 'id', hide: true, disableExport: true },
        { field: 'invoice_header_ref_interne', headerName: 'Num Facture', minWidth: 200, flex: 1, hide: false, editable: false, },
        { field: 'order_header_ref_interne', headerName: 'Reference Cmd', minWidth: 200, flex: 1, hide: false, editable: false },
        { field: 'invoice_header_type', headerName: 'Type', width: 100, hide: false, editable: false },
        { field: 'invoice_date', headerName: 'Date Facture', width: 150, hide: false, editable: false },

        { field: 'order_header_client_id', headerName: 'Client_Id', width: 150, hide: true, editable: false, disableExport: true },
        { field: 'order_header_client_nom', headerName: 'Nom Client', minWidth: 150, flex: 1 },
        { field: 'order_header_vendeur_id', headerName: 'Vendeur Id', width: 0, hide: true, editable: false, disableExport: true },
        { field: 'order_header_vendeur_nom_prenom', headerName: 'Vendeur', width: 150, flex: 1, editable: false },
        { field: 'order_header_date_cmd', headerName: 'Date Cmd', width: 150, hide: true, editable: false },
        { field: 'total_header_hors_taxe_after_header_reduction', headerName: 'Montant HT', width: 150, hide: false, editable: false },
        { field: 'order_header_tax_amount', headerName: 'Taxe', width: 150, hide: false, editable: false },
        { field: 'total_header_toutes_taxes', headerName: 'Montant TTC', width: 150, hide: false, editable: false },
        { field: 'reste_to_paye', headerName: 'A payer', width: 150, hide: false, editable: false },
        { field: 'credit_note_ref', headerName: 'Ref. Avoir', width: 150, hide: true, editable: false, },




        /* {
             field: "Detail", headerName: 'Voir detail',
             renderCell: (cellValues) => {
                 return (
 
                     <Button
 
                         onClick={(event) => {
                             Display_Detail_Employe(event, cellValues);
                         }}
                     >
                         <FcViewDetails />
 
                     </Button>
 
                 );
             }
         },*/
        {/*
            field: "delete", headerName: 'Supprimer',
            renderCell: (cellValues) => {
                return (

                    <Popup
                        trigger={<Button

                            onClick={(event) => {
                                // handleClick_delete(event, cellValues);
                            }}
                        >
                            <CiTrash />

                        </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">
                                    {' '}

                                    En confirmant cette opération, le document sera <i><font color="red"> définitivement supprimé</font></i>. <br />

                                </div>
                                <div className="gest_actions">
                                    <div style={{ "width": "45%", "float": "left" }}>
                                        <button className="gest_bton_popup" onClick={(event) => {
                                            //handleClick_delete(event, cellValues);
                                            //console.log('modal closed ');
                                            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>


                );
            }
            */
        }

    ]



    const [selected_invoice_line_id, setselected_invoice_line_id] = useState();
    const [p_add_line_item, setp_add_line_item] = useState();

    const [p_add_line_item_type_article, setp_add_line_item_type_article] = useState("");

    const [p_add_line_item_internal_url, setp_add_line_item_internal_url] = useState();
    const [p_add_line_item_title, setp_add_line_item_title] = useState();
    const [p_add_line_item_qty, setp_add_line_item_qty] = useState();
    const [p_add_line_item_price, setp_add_line_item_price] = useState();
    const [p_add_line_item_comment, setp_add_line_item_comment] = useState();
    const [p_add_line_item_status, setp_add_line_item_status] = useState();
    const [p_add_line_item_type, setp_add_line_item_type] = useState();

    const [p_add_line_item_type_reduction, setp_add_line_item_type_reduction] = useState("fixe");
    const [p_add_line_item_reduction_value, setp_add_line_item_reduction_value] = useState();
    const [p_add_line_item_reduction_total_amount, setp_add_line_item_reduction_total_amount] = useState();
    const [p_add_line_item_total_amount_ht, setp_add_line_item_total_amount_ht] = useState();
    const [p_add_line_item_taxe, setp_add_line_item_taxe] = useState();
    const [p_add_line_item_taxe_amount, setp_add_line_item_taxe_amount] = useState();
    const [p_add_line_item_total_amount_ttc, setp_add_line_item_total_amount_ttc] = useState();
    const [p_add_line_item_duration_concat, setp_add_line_item_duration_concat] = useState();

    const [p_add_line_item_type_apprenant, setp_add_line_item_type_apprenant] = useState("");




    const [isLoading, setLoading] = useState();

    const [p_detail_header_client_nom, setp_detail_header_client_nom] = useState();
    const [p_detail_header_email_client, setp_detail_header_email_client] = useState();
    const [p_detail_header_client_nom_id, setp_detail_header_client_nom_id] = useState();

    const [p_detail_header_description, setp_detail_header_description] = useState();
    const [p_detail_header_comment, setp_detail_header_comment] = useState();
    const [p_detail_header_date_cmd, setp_detail_header_date_cmd] = useState(new Date().toLocaleDateString('fr-FR'));
    const [p_detail_header_date_expiration, setp_detail_header_date_expiration] = useState(date_today_90j.toLocaleDateString('fr-FR'));
    const [p_detail_header_condition_paiement_id, setp_detail_header_condition_paiement_id] = useState("");
    const [p_detail_header_condition_paiement_code, setp_detail_header_condition_paiement_code] = useState("");

    const [p_detail_header_ref_client, setp_detail_header_ref_client] = useState();
    const [p_detail_header_ref_interne, setp_detail_header_ref_interne] = useState();

    const [p_detail_header_vendeur_nom, setp_detail_header_vendeur_nom] = useState();
    const [p_detail_header_vendeur_nom_id, setp_detail_header_vendeur_nom_id] = useState();


    const [p_detail_header_invoice_header_annotation, setp_detail_header_invoice_header_annotation] = useState("");

    const [p_detail_header_invoice_header_ref_interne, setp_detail_header_invoice_header_ref_interne] = useState();
    const [p_detail_header_invoice_header_type, setp_detail_header_invoice_header_type] = useState();
    const [p_detail_header_invoice_date, setp_detail_header_invoice_date] = useState();


    const [p_detail_header_type, setp_detail_header_type] = useState();
    const [p_detail_header_statut, setp_detail_header_statut] = useState();
    const [p_detail_header_vendeur_id, setp_detail_header_vendeur_id] = useState();
    const [p_detail_header_client_id, setp_detail_header_client_id] = useState();
    const [p_detail_header_statut_label, setp_detail_header_statut_label] = useState();

    const [p_detail_header_date_cmd_val, setp_detail_header_date_cmd_val] = useState(new Date().toLocaleDateString('fr-FR'));
    const [p_detail_header_date_expiration_val, setp_detail_header_date_expiration_val] = useState(date_today_90j.toLocaleDateString('fr-FR'));

    const [p_detail_header_condition_paiement, setp_detail_header_condition_paiement] = useState();
    const [p_detail_header_condition_paiement_desc, setp_detail_header_condition_paiement_desc] = useState();
    const [p_detail_header_date_echeance, setp_detail_header_date_echeance] = useState();

    const [p_detail_header_fact_adr, setp_detail_header_fact_adr] = useState();
    const [p_detail_header_fact_code_postal, setp_detail_header_fact_code_postal] = useState();
    const [p_detail_header_fact_ville, setp_detail_header_fact_ville] = useState();
    const [p_detail_header_fact_pays, setp_detail_header_fact_pays] = useState();


    const [p_detail_header_liv_adr, setp_detail_header_liv_adr] = useState();
    const [p_detail_header_liv_code_postal, setp_detail_header_liv_code_postal] = useState();
    const [p_detail_header_liv_ville, sep_detail_header_liv_ville] = useState();
    const [p_detail_header_liv_pays, setp_detail_header_liv_pays] = useState();
    const [p_detail_header_total_ht, setp_detail_header_total_ht] = useState();
    const [p_detail_header_total_tax, setp_detail_header_total_tax] = useState();
    const [p_detail_header_total_ttc, setp_detail_header_total_ttc] = useState();
    const [p_detail_header_type_reduction, setp_detail_header_type_reduction] = useState();
    const [p_detail_header_total_reduction_amount, setp_detail_header_total_reduction_amount] = useState();


    const [p_detail_header_credit_note_ref, setp_detail_header_credit_note_ref] = useState();

    const [p_detail_header_type_reduction_valeur, setp_detail_header_type_reduction_valeur] = useState();
    const [p_detail_header_montant_reduction, setp_detail_header_montant_reduction] = useState();
    const [p_detail_total_header_hors_taxe_before_header_reduction, setp_detail_total_header_hors_taxe_before_header_reduction] = useState();
    const [p_detail_total_header_hors_taxe_after_header_reduction, setp_detail_total_header_hors_taxe_after_header_reduction] = useState();
    const [p_detail_order_header_tax_amount, setp_detail_order_header_tax_amount] = useState();
    const [p_detail_total_header_toutes_taxes, setp_detail_total_header_toutes_taxes] = useState();



    const [p_detail_total_lines_hors_taxe_before_lines_reduction, setp_detail_total_lines_hors_taxe_before_lines_reduction] = useState();
    const [p_detail_total_lines_hors_taxe_after_lines_reduction, setp_detail_total_lines_hors_taxe_after_lines_reduction] = useState();



    const myRef = useRef(null);

    const [history_securite_read, sethistory_securite_read] = useState("");

    useEffect(() => {

        Get_List_Of_All_PJ();


    }, [])

    const [display_detail_invoice, setdisplay_detail_invoice] = React.useState();

    const myRef_head = useRef(null);
    const [selected_id, setselected_id] = useState("");
    const [selected_order_line_id, setselected_order_line_id] = useState("");
    const [selected_order_header_type, setselected_order_header_type] = useState();

    const [order_internal_ref, setorder_internal_ref] = useState("");
    const [invoice_internal_ref, setinvoice_internal_ref] = useState("");

  
    function submenu_color_management(current_menu) {
        const list_sous_menu = ["order_header_facturation", "order_header_detail", "order_header_main", "order_header_detail", "paiement"]

        for (let i = 0; i < list_sous_menu.length; i++) {

            var sous_menu = list_sous_menu[i];
            if (String(sous_menu) !== current_menu) {
                if (document.getElementById(sous_menu)) {
                    document.getElementById(sous_menu).style.backgroundColor = "#d8edfc";
                    document.getElementById(sous_menu).style.color = "black";
                    document.getElementById(sous_menu).style.fontWeight = "normal";
                }
            }

        }

        if (document.getElementById(current_menu)) {
            document.getElementById(current_menu).style.backgroundColor = "#107758";
            document.getElementById(current_menu).style.color = "white";
            document.getElementById(current_menu).style.fontWeight = "bold";
        }

    }

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


    function print_invoice_pdf() {
        const stored_cookie = getCookie('tokenmysych');

        var nom_fichier_cmd = "Facture_" + invoice_internal_ref + ".pdf";
        // console.log(" nom_fichier_cmd = ", nom_fichier_cmd, " --- selected_id = ", selected_id);

        var url = process.env.REACT_APP_API_URL + "myclass/api/GerneratePDF_Partner_Invoice/" + stored_cookie + "/" + selected_id;

        //console.log(" nom_fichier_cmd = ", nom_fichier_cmd, " --- selected_id = ", selected_id, " --- url =", url);

        axios.get(url, { responseType: 'blob', },)
            .then((res) => {
                fileDownload(res.data, nom_fichier_cmd)
            }).catch((error) => {
                console.error('Error:', error);

            });
    }




    function clean_all_filters() {
        setp_filtre1("");
        setp_filtre1_value();

        setp_filtre2("");
        setp_filtre2_value();

        setp_filtre3("");
        setp_filtre3_value();

        setp_filtre4("");
        setp_filtre4_value();

        clean_order_detail_fields();
        setsubmenu();

        setSelectionModel([]);
        setselectionModel_invoice_lines([]);

     //   Getall_Parter_Invoice_No_Filter();
        setdisplay_detail_invoice();

        setgridline_id("");
    }

    function clean_order_detail_fields() {

    }

    const [Dialog_Detail_Article_open, setDialog_Detail_Article_open] = React.useState(false);

    const Close_Dialog_Detail_Article_open = () => {

        setDialog_Detail_Article_open(false);
    };

    const Dialog_1_handleClose = () => {
        //alert(" Utiliser le bouton 'fermer' ");
        //setOpen(false);
    };

    const Dialog_1_handleClose_buton = () => {
        setDialog_1_open(false);
    };

    const [Dialog_1_open, setDialog_1_open] = React.useState(false);



    const [Dialog_Paiement_1_message, setDialog_Paiement_1_message] = React.useState(false);
    const [Dialog_Paiement_1_open, setDialog_Paiement_1_open] = React.useState(false);

  

    const [p_detail_paiement_id, setp_detail_paiement_id] = useState("");
    const [p_detail_paiement_amount, setp_detail_paiement_amount] = useState("");

    const [p_detail_paiement_date, setp_detail_paiement_date] = useState(new Date().toLocaleDateString('fr-FR'));

    const [p_detail_paiement_ref, setp_detail_paiement_ref] = useState("");
    const [p_detail_paiement_comment, setp_detail_paiement_comment] = useState("");
    const [p_detail_paiement_mode, setp_detail_paiement_mode] = useState("");
    const [p_detail_paiement_invoice_id, setp_detail_paiement_invoice_id] = useState("");



    const [Dialog_annotation_1_message, setDialog_annotation_1_message] = React.useState(false);
    const [Dialog_annotation_1_open, setDialog_annotation_1_open] = React.useState(false);

    function Dialog_1_handle_change_annotation(message) {
        setDialog_annotation_1_message(message);
        setDialog_annotation_1_open(true);
    }

    const Dialog_annotation_1_handleClose = () => {
        //alert(" Utiliser le bouton 'fermer' ");
        //setOpen(false);
    };

    const Dialog_annotation_1_handleClose_buton = () => {

        setDialog_annotation_1_open(false);

        /* if (document.getElementById('myRef')) {
             var divh = document.getElementById('myRef').offsetTop;
             window.scrollTo({
                 top: divh,
                 behavior: "smooth",
             });
         }*/

    };

   

    const New_Option_Filter = [
        { "id": "ref_interne_invoice", "label": "Num Facture", "value": "ref_interne_invoice" },
        { "id": "ref_interne_cmd", "label": "Ref. Interne Cmd", "value": "ref_interne_cmd" },
        { "id": "ref_externe", "label": "Ref. Externe Cmd (chez le client)", "value": "ref_externe" },
        { "id": "client_nom", "label": "Nom Client", "value": "client_nom" },
        { "id": "formation", "label": "Lié a la Formation (code externe)", "value": "formation" },
        { "id": "", "label": "", "value": "" },
        { "id": "1", "label": "", "value": "1" }, // Cette ligne pour couvrir l'ajout d'une ligne de filter. C'est fait expres.
    ]


    function handleClick_menu_droite_facture(e) {
        console.log(" III ");
    }

    const New_type_apprenant = [
        { "id": "0", "label": "Autre", "value": "0" },
        { "id": "1", "label": "Salariés", "value": "1" },
        { "id": "2", "label": "Apprentis", "value": "2" },
        { "id": "3", "label": "Particuliers", "value": "3" },
        { "id": "4", "label": "Rech. Emploi", "value": "4" },
        { "id": "", "label": "", "value": "" },
    ]


    // DEBUT  EXPORT EXCEL DATAGRID 

    function CustomToolbar(props) {


        return (
            <GridToolbarContainer {...props}>

                <GridToolbarColumnsButton />
                <GridToolbarFilterButton />
                <GridToolbarDensitySelector
                    slotProps={{ tooltip: { title: 'Change density' } }}
                />
                <Box sx={{ flexGrow: 1 }} />
                <ExportButton data_colums={props.data_colums} />


            </GridToolbarContainer>
        );
    }

    function getExcelData(apiRef) {
        // Select rows and columns
        const filteredSortedRowIds = gridFilteredSortedRowIdsSelector(apiRef);
        const visibleColumnsField = gridVisibleColumnFieldsSelector(apiRef);

        // Format the data. Here we only keep the value
        const data = filteredSortedRowIds.map((id) => {
            const row = {};
            visibleColumnsField.forEach((field) => {
                row[field] = apiRef.current.getCellParams(id, field).value;
            });
            return row;
        });

        return data;
    }


    function ExportButton(props) {
        return (
            <GridToolbarExportContainer {...props}>
                <ExportMenuItem data_colums={props.data_colums} />
            </GridToolbarExportContainer>
        );
    }

    function handleExport(apiRef, data_colums) {
        const data = getExcelData(apiRef);
        const visibleColumnsField = gridVisibleColumnFieldsSelector(apiRef);


        const local_config = {
            keys: visibleColumnsField,

            columnNames: data_colums.filter((mydata) => (mydata).disableExport !== true).map(function (mydata) {
                if (mydata.headerName && visibleColumnsField.includes(mydata.field)) {
                    if (mydata.headerName) {
                        return mydata.headerName;
                    }
                }

            }),

            fileName: 'data_' + String(new Date().toJSON().slice(0, 10)).replaceAll("-", "_") + '.xlsx',
            sheetName: 'Export_' + String(new Date().toJSON().slice(0, 10)).replaceAll("-", "_"),
        };

        local_config.columnNames = local_config.columnNames.filter(function (element) {
            return element !== undefined;
        });


        const rows = data.map((row) => {
            const mRow = {};
            for (const key of local_config.keys) {
                mRow[key] = row[key];
            }
            return mRow;
        });

        const worksheet = XLSX.utils.json_to_sheet(rows);
        XLSX.utils.sheet_add_aoa(worksheet, [[...local_config.columnNames]], {
            origin: 'A1',
        });

        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, local_config.sheetName);
        XLSX.writeFile(workbook, local_config.fileName, { compression: true });
    }

    function ExportMenuItem(props) {
        const apiRef = useGridApiContext();
        const { hideMenu } = props;

        return (
            <MenuItem
                onClick={() => {
                    handleExport(apiRef, props.data_colums);
                    // Hide the export menu after the export
                    hideMenu?.();
                }}
            >
                Export Excel
            </MenuItem>
        );
    }

    // FIN EXPORT EXCEL DATAGRID 

    const [Dialog_send_invoice_with_PJ_message, setDialog_send_invoice_with_PJ_message] = React.useState(false);
    const [Dialog_send_invoice_with_PJ_open, setDialog_send_invoice_with_PJ_open] = React.useState(false);
    function Dialog_send_invoice_with_PJ_handle_change_participant_session(message) {
        setDialog_send_invoice_with_PJ_message(message);
        setDialog_send_invoice_with_PJ_open(true);
    }

    const Dialog_send_invoice_with_PJ_handleClose = () => {
        //alert(" Utiliser le bouton 'fermer' ");
        //setOpen(false);
    };

    const Dialog_send_invoice_with_PJ_handleClose_buton = () => {
        setDialog_send_invoice_with_PJ_open(false);
        settab_invoice_mail_pieces_jointes_result([]);
    };


    function Delete_invoice_email_Attached_Doc(event) {

        var doc_to_del_name = event.target.id;
        const myArray = tab_invoice_mail_pieces_jointes_result;

        let new_myArray = myArray.filter(file => file.name !== String(doc_to_del_name));

        var new_tab = []
        for (let i = 0; i < new_myArray.length; i++) {
            new_tab.push(new_myArray[i]);
        }

        settab_invoice_mail_pieces_jointes_result(new_tab);


    }

    const [sessions_file_change_1_convention_api, setsessions_file_change_1_convention_api] = useState();
    const [sessions_file_change_1_convention_result, setsessions_file_change_1_convention_result] = useState();
    const [sessions_file_change_1_convention_message, setsessions_file_change_1_convention_message] = useState();
    const sessions_file_change_1_convention = event => {

        const fileUploaded = event.target.files[0];
        let file_size = event.target.files[0].size;
        let file_type = event.target.files[0].type;


        if (file_type !== "application/pdf") {
            alert("Le fichier n'est pas de type PDF");
            return;
        }



        if (file_size > 10000000) {
            alert("Le fichier ne doit pas depasser un 1 Méga octets");
            console.log("Le fichier ne doit pas depasser un 1 Méga octets");
            return;
        }

        //var new_node = {'name':event.target.files[0].name, 'type':event.target.files[0].type}


        var new_tmp = [];

        if (tab_invoice_mail_pieces_jointes_result && tab_invoice_mail_pieces_jointes_result.length > 0) {

            tab_invoice_mail_pieces_jointes_result.map((x) => {
                new_tmp.push(x);

            });

        }

        new_tmp.push(event.target.files[0])

        settab_invoice_mail_pieces_jointes_result(new_tmp);

        //console.log(" tab_invoice_mail_pieces_jointes_result = ", tab_invoice_mail_pieces_jointes_result)


        return;


    };

    const [tab_invoice_mail_pieces_jointes_result, settab_invoice_mail_pieces_jointes_result] = useState([]);

    const [Dialog_invoice_history_message, setDialog_invoice_history_message] = React.useState(false);
    const [Dialog_invoice_history_open, setDialog_invoice_history_open] = React.useState(false);
    function Dialog_invoice_history_handle_change_participant_session(message) {
        setDialog_invoice_history_message(message);
        setDialog_invoice_history_open(true);
    }

    const Dialog_invoice_history_handleClose = () => {
        //alert(" Utiliser le bouton 'fermer' ");
        //setOpen(false);
    };

    const Dialog_invoice_history_handleClose_buton = () => {
        setDialog_invoice_history_open(false);
        settab_invoice_mail_pieces_jointes_result([]);

        if (document.getElementsByName("invoice_history_bton") && document.getElementsByName("invoice_history_bton")[0]) {
            document.getElementsByName("invoice_history_bton")[0].style.backgroundColor = "#d8edfc";
            document.getElementsByName("invoice_history_bton")[0].style.color = "#3b3e40";
        }
    };

    const [Get_List_Of_All_PJ_api, setGet_List_Of_All_PJ_api] = useState();
    const [Get_List_Of_All_PJ_result, setGet_List_Of_All_PJ_result] = useState();
    const [Get_List_Of_All_PJ_message, setGet_List_Of_All_PJ_message] = useState();

    function Get_List_Of_All_PJ() {

        const formData = new FormData();

        //formData.append('token', 'K3cw63eKokKSbV4spjQ48SUNnfy80yrXfA');
        const stored_cookie = getCookie('tokenmysych');

        formData.append("token", stored_cookie);
        formData.append("object_owner_collection", "partner_client");
        formData.append("object_owner_id", props.partner_client_id);


        //formData.append("class_internal_url", internal_url);
        //console.log("token = " + stored_cookie);
        setLoading(true);

        fetch(
            process.env.REACT_APP_API_URL + "myclass/api/Get_List_object_owner_collection_Stored_Files/",
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                setLoading(false);

                //console.log(" ## result['status'] = ", result['status'])
                if (String(result['status']) === String("true")) {
                    //console.log('Message :', result['message']);
                    setGet_List_Of_All_PJ_result(result['message']);
                    setGet_List_Of_All_PJ_api("true");

                }
                else {
                    setGet_List_Of_All_PJ_message(result['message']);
                    setGet_List_Of_All_PJ_api("false");
                }

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

    }

 // -- Gestion pièces jointes 

 const [Download_one_attached_document_api, setDownload_one_attached_document_api] = useState();
 const [Download_one_attached_document_result, setDownload_one_attached_document_result] = useState();
 const [Download_one_attached_document_message, setDownload_one_attached_document_message] = useState();
 const Download_one_attached_document = (event) => {

    const stored_cookie = getCookie('tokenmysych');

     var nom_fiche_detaillee = "Fiche_Detaillee.pdf";
     var token = stored_cookie;
     var file_name = event.target.id;


     var url = process.env.REACT_APP_API_URL + "myclass/api/Get_Stored_Downloaded_File/" + token + "/" + file_name;
     setLoading(true);

     axios.get(url, { responseType: 'blob', },)
         .then((res) => {
             setLoading(false);
             fileDownload(res.data, nom_fiche_detaillee);
             setDownload_one_attached_document_api("true");
         }).catch((error) => {
             setLoading(false);
             console.error('Error:', error);
             setDownload_one_attached_document_api("false");

         });
 }

    /***
     * IMPORTANT 
     * Ce module permet d'afficher et telecharger tous les documents qui sont dans la collection 'download_files', c'est à dire :
     * 1 - Les documents importés manuellement sur l'espace du client
     * 2 - Les devis signés electroniquement (en effet ils sont automatiquement importés dans l'espace du client)
     * 3 - Les Convention signés electroniquement (en effet ils sont automatiquement importés dans l'espace du client)
     * 4 - A ajouter : les convocations adressées à ses apprenants
     * 5 - A ajouter : les attestations adressées à ses apprenants
     * 
     * /!\ /!\ /!\ /!\ /!\ /!\ /!\  Les factures sont bien dans la collection, mais pour recuperer il faut passer par la collection 'partner_invoice_header'
     * /!\  /!\ /!\ /!\ /!\ /!\ /!\  raison pour laquel, on va mettre les documents d'un coté et les facture de l'autre.
     */
    
    return (

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


            <h3 style={{  fontFamily:'DM Sans' }}> Tous vos documents </h3>
            <div className="div_row">
                <div className="titre1">  Utilisez les filtres !</div>
                <div className="div_row" style={{ "marginBottom": "5px" }}>
                    <div className="div_row_gauche texte_area_filter" >


                        {New_Option_Filter && New_Option_Filter.length > 0 && <Autocomplete
                            disablePortal
                            name="filtre1"
                            id="filtre1"
                            className="disabled_style"
                            value={New_Option_Filter.filter((data) => (data).value === String(p_filtre1))[0].label}
                            options={New_Option_Filter}
                            onChange={(event, value) => {
                                if (value && value.value) {
                                    setp_filtre1(value.value);
                                } else {
                                    setp_filtre1("");
                                }

                            }}

                            renderInput={(params) => <TextField {...params} label="" placeholder="Choisir une option"
                                inputProps={{ ...params.inputProps, style: { fontSize: 12, height: "1.4rem" } }}

                            />
                            }
                        />}


                    </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 className="tooltip_css" id="my-tooltip01" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip01" data-tooltip-html="Ajouter une nouvelle ligne de filtre">
                            &nbsp; <MdAddCircleOutline onClick={(e) => {
                                setp_filtre2("1");
                                setp_filtre2_value("");
                            }} />
                        </a>
                    </div>}
                    {p_filtre1 && <div className='filter_bton_add'>
                        <Tooltip className="tooltip_css" id="my-tooltip02" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip02" data-tooltip-html="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">
                            {New_Option_Filter && New_Option_Filter.length > 0 && <Autocomplete
                                disablePortal
                                name="filtre2"
                                id="filtre2"
                                className="disabled_style"
                                value={New_Option_Filter.filter((data) => (data).value === String(p_filtre2))[0].label}
                                options={New_Option_Filter}
                                onChange={(event, value) => {
                                    if (value && value.value) {
                                        setp_filtre2(value.value);

                                    }

                                }}

                                renderInput={(params) => <TextField {...params} label="" placeholder="Choisir une option"
                                    inputProps={{ ...params.inputProps, style: { fontSize: 12, height: "1.4rem" } }}

                                />
                                }
                            />}
                        </div>
                        <div className="div_row_droite texte_area_filter_value" style={{ "marginTop": "0.5rem" }}>
                            {String(p_filtre2).length > 2 &&
                                <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 > 2 && <div className='filter_bton_add' >
                            <Tooltip className="tooltip_css" id="my-tooltip03" style={{ "fontSize": "12px" }} />
                            <a data-tooltip-id="my-tooltip03" data-tooltip-html="Ajouter une nouvelle ligne de filtre">
                                &nbsp; <MdAddCircleOutline
                                    onClick={(e) => {
                                        setp_filtre3("1");
                                        setp_filtre3_value("");
                                    }}
                                />
                            </a>
                        </div>}

                        {String(p_filtre2).length > 2 && <div className='filter_bton_add'>
                            <Tooltip className="tooltip_css" id="my-tooltip04" style={{ "fontSize": "12px" }} />
                            <a data-tooltip-id="my-tooltip04" data-tooltip-html="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">
                            {New_Option_Filter && New_Option_Filter.length > 0 && <Autocomplete
                                disablePortal
                                name="filtre3"
                                id="filtre3"
                                className="disabled_style"
                                value={New_Option_Filter.filter((data) => (data).value === String(p_filtre3))[0].label}
                                options={New_Option_Filter}
                                onChange={(event, value) => {
                                    if (value && value.value) {
                                        setp_filtre3(value.value);

                                    }

                                }}

                                renderInput={(params) => <TextField {...params} label="" placeholder="Choisir une option"
                                    inputProps={{ ...params.inputProps, style: { fontSize: 12, height: "1.4rem" } }}

                                />
                                }
                            />}
                        </div>
                        <div className="div_row_droite texte_area_filter_value" style={{ "marginTop": "0.5rem" }}>
                            {String(p_filtre3).length > 2 &&
                                <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_filtre2).length > 2 && <div className='filter_bton_add' >
                            <Tooltip className="tooltip_css" id="my-tooltip03" style={{ "fontSize": "12px" }} />
                            <a data-tooltip-id="my-tooltip03" data-tooltip-html="Ajouter une nouvelle ligne de filtre">
                                &nbsp; <MdAddCircleOutline
                                    onClick={(e) => {
                                        setp_filtre4("1");
                                        setp_filtre4_value("");
                                    }}
                                />
                            </a>
                        </div>}

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


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

                    <div className="div_row_gauche" style={{ "textAlign": 'left', 'marginLeft': '15px' }}>
                        <Button variant="contained" className="bton_enreg" onClick={"Getall_Parter_Invoice_With_Filter"}>Rechercher
                        </Button>
                    </div>

                    <div className="div_row_droite" style={{ "textAlign": 'right', 'marginRight': '15px' }}>
                        <Button variant="contained" className="bton_annule" onClick={clean_all_filters}>Annuler
                        </Button>

                    </div>

                </div>

                <br />
            </div>

            <div className="div_row" style={{ "border": "None", paddingRight: '10px' }}>

                {Get_List_Of_All_PJ_result && <div className="div_row" style={{ "padding": "5px" }}>
                    <div className="div_row">
                        <b> Liste des pièces jointes </b> <br />
                        <div className="div_row">
                            {Get_List_Of_All_PJ_result && Get_List_Of_All_PJ_result.map((val) => (
                                <div className="div_row_list_pj"  >
                                    <nav name={(JSON.parse(val).file_name)}
                                        id={(JSON.parse(val).file_name)}> <i> <AttachFileIcon />{(JSON.parse(val).file_business_object)} </i> <br /><font style={{ "color": "green", "cursor": "pointer" }}
                                            name={(JSON.parse(val).file_name)}
                                            id={(JSON.parse(val).file_name)} onClick={Download_one_attached_document}>  Télécharger &nbsp;</font></nav>

                                    <Popup
                                        trigger={
                                            <nav style={{ "color": "red", "cursor": "pointer" }}  > Supprimer</nav>


                                        }
                                        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">
                                                    {' '}

                                                    En confirmant cette opération, la pièce jointe sera <i><font color="red"> définitivement supprimée</font></i>. <br />


                                                </div>
                                                <div className="gest_actions">
                                                    <div style={{ "width": "45%", "float": "left" }}>
                                                        <button className="gest_bton_popup" onClick={(event) => {

                                                           // Delete_one_attached_document(event);
                                                            close();
                                                        }}
                                                            name={(JSON.parse(val).file_name)} id={(JSON.parse(val).file_name)}
                                                        > 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>

                                </div>
                            ))}
                        </div>
                    </div>
                </div>}
            </div>

            <div className="div_row" ref={myRef} id="myRef" > &nbsp;</div>
           


        </div >
    )
}


export default Intranet_Tous_Documents;
