import React, { useState, useEffect, useCallback, useRef } from "react";
import axios from "axios";
import { Helmet } from "react-helmet";
import { useParams } from 'react-router-dom'
import Header from "./Header";
import { useLocation } from "react-router-dom";
import fileDownload from 'js-file-download'
import { RichTextEditor } from '@mantine/rte';
import { Editor } from '@tinymce/tinymce-react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { getCookie, setCookie } from 'react-use-cookie';
import { useHistory } from "react-router-dom";

const TestUrl_New = (props) => {

    const { courseid, tabid } = useParams();
    const [message, setMessage] = useState(null);
    const editorRef_programme = useRef(null);
    const [editorRef_programme_limite, seteditorRef_programme] = useState(1000);
    const [field_programme, setfield_programme] = useState("");
    const [editor_tochange, seteditor_tochange] = useState("");

    function editor_keyup() {
        seteditor_tochange("1");
    }

    function DataUpdated() {

    }

    function add_text() {
        console.log(" Ajouter un texte ");
        editorRef_programme.current.insertContent("<i> OKKK </i> ");
    }

    function add_nom() {
        editorRef_programme.current.insertContent(" <i>{{nom}}</i> ");
    }

    function add_prenom() {
        editorRef_programme.current.insertContent(" <i>{{prenom}}</i> ");
    }

    function add_document() {
        var programme = editorRef_programme.current.getContent();
        console.log(" doc text = ", programme);
    }

    function delete_document() {

    }

    function add_selected_fields() {

        if (!p_collection || !p_champ_table) {
            alert(" Champ invalide ");
            return;
        }
        var local_field = "{{" + String(p_collection) + "." + String(p_champ_table) + "}}";
        editorRef_programme.current.insertContent(" <b><i>" + String(local_field) + "</i></b> ");
    }



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

    const [p_champ_table, setp_champ_table] = useState();
    const [p_collection, setp_collection] = useState();


    const [p_champ_table_bis, setp_champ_table_bis] = useState();

    const [Get_Personnalisable_Collection_and_Fields_api, setGet_Personnalisable_Collection_and_Fields_api] = useState();
    const [Get_Personnalisable_Collection_and_Fields_message, setGet_Personnalisable_Collection_and_Fields_message] = useState();
    const [Get_Personnalisable_Collection_and_Fields_result, setGet_Personnalisable_Collection_and_Fields_result] = useState();
    function Get_Personnalisable_Collection_and_Fields() {

        var form = new FormData();


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


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



        axios.post(myurl, form).then(res => {

            if (String(res.data.status) === String("true")) {
                //console.log(" In Get_Personnalisable_Collection_and_Fields  res.data.status = " + res.data.status);
                //console.log(" In Get_Personnalisable_Collection_and_Fields  res.data.message r_class = " + res.data.message);

                setGet_Personnalisable_Collection_and_Fields_api("true");
                setGet_Personnalisable_Collection_and_Fields_result(res.data.message);

            }
            else {
                setGet_Personnalisable_Collection_and_Fields_api("false");
                setGet_Personnalisable_Collection_and_Fields_message(res.data.message);
                alert(res.data.message)
            }

        }).catch((error) => {
            console.warn('Not good man :( Get_Personnalisable_Collection_and_Fields = ', error);
            setGet_Personnalisable_Collection_and_Fields_api("false");
            alert(" Impossible de recuperer la liste des collection et champs personnalisables");
            //setmyApimyApiMessage("")
        })
    }

    const [Get_Personnalisable_Collections_api, setGet_Personnalisable_Collections_api] = useState();
    const [Get_Personnalisable_Collections_message, setGet_Personnalisable_Collections_message] = useState();
    const [Get_Personnalisable_Collections_result, setGet_Personnalisable_Collections_result] = useState();
    function Get_Personnalisable_Collections() {

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

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

        axios.post(myurl, form).then(res => {

            if (String(res.data.status) === String("true")) {
                //console.log(" In Get_Personnalisable_Collections  res.data.status = " + res.data.status);
                //console.log(" In Get_Personnalisable_Collections  res.data.message r_class = " + res.data.message);

                setGet_Personnalisable_Collections_api("true");
                setGet_Personnalisable_Collections_result(res.data.message);

            }
            else {
                setGet_Personnalisable_Collections_api("false");
                setGet_Personnalisable_Collections_message(res.data.message);
                alert(res.data.message)
            }

        }).catch((error) => {
            console.warn('Not good man :( Get_Personnalisable_Collections = ', error);
            setGet_Personnalisable_Collections_api("false");
            alert(" Impossible de recuperer la liste des collection et champs personnalisables");
            //setmyApimyApiMessage("")
        })
    }

    useEffect(() => {
        Get_Personnalisable_Collections();
        Get_Personnalisable_Collection_and_Fields();

    }, [])


    const [p_document_name, setp_document_name] = useState();
    const [p_document_type, setp_document_type] = useState();
    const [p_document_ref_interne, setp_document_ref_interne] = useState();
    const [p_document_sujet, setp_document_sujet] = useState();
    const [p_document_nom, setp_document_nom] = useState();

    const [Add_one_Partner_Document_api, setAdd_one_Partner_Document_api] = useState();
    const [Add_one_Partner_Document_message, setAdd_one_Partner_Document_message] = useState();
    const [Add_one_Partner_Document_result, setAdd_one_Partner_Document_result] = useState();
    function Add_one_Partner_Document() {
        var form = new FormData();
        //form.append("token","K3cw63eKokKSbV4spjQ48SUNnfy80yrXfA");


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

        if (p_document_ref_interne)
            form.append("ref_interne", p_document_ref_interne);
        else {
            alert(" Vous devez definir une reference interne");
            return;
        }


        if (p_document_type)
            form.append("type_doc", p_document_type);
        else {
            alert(" Vous devez definir un type de document");
            return;
        }


        if (p_document_sujet)
            form.append("sujet", p_document_sujet);
        else {
            alert(" Vous devez definir un sujet");
            return;
        }

        

        if (editorRef_programme){
            var programme = editorRef_programme.current.getContent();
            form.append("contenu_doc", programme);
        }
        else {
            form.append("contenu_doc", "");
        }

        console.log(" Add_one_Partner_Document affectation form == ", form);


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

        axios.post(myurl, form).then(res => {
            console.log(" In Add_one_Partner_Document  res.data.status = " + res.data.status);
            console.log(" In Add_one_Partner_Document  res.data.message r_class = " + res.data.message);

            if (String(res.data.status) === String("true")) {
                setAdd_one_Partner_Document_api("true");
                setAdd_one_Partner_Document_result(res.data.message);

                alert(res.data.message);

            }
            else {
                setAdd_one_Partner_Document_api("false");
                setAdd_one_Partner_Document_message(res.data.message);
                alert(res.data.message);
            }

        }).catch((error) => {

            console.log('UpdateStagiaireData : Not good man :( Add_one_Partner_Document = ' + error);
            setAdd_one_Partner_Document_api("false");
            alert(" Impossible d'ajouter le document");

        })
    }


    return (
        <div className="testurl_new">
            <Helmet>
                <title>testurl_new</title>
                <meta name="description" content="{this.metaDetails.description}" />
                <meta name="keywords" content="{this.metaDetails.keywords}" />
            </Helmet>

            <Header />

            <div className="div_mobile">
                <h3> Page de test * testurl_new </h3>
                parametres courseid = {courseid}, tabid = {tabid}
                <br />

                <div className="div_row_gauche texte_area_filter" >
                    <TextField
                        name="document_name"
                        label="Choisir un document"
                        select
                        sx={{ m: 1, width: '100%' }}
                        value={p_document_name}
                        onChange={(e) => {
                            setp_document_name(e.target.value);

                        }}
                    >
                        <MenuItem value="convocation" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Convocation &nbsp;</MenuItem>
                        <MenuItem value="document2" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Document 2  &nbsp;</MenuItem>
                        <MenuItem value="document3" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Document 3&nbsp;</MenuItem>
                        <MenuItem value="document4" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Document 4 &nbsp;</MenuItem>


                    </TextField>
                </div>

                {p_document_name && <div className="div_row_gauche texte_area_filter" >
                    <TextField
                        name="document_type"
                        label="Type de document"
                        select
                        sx={{ m: 1, width: '100%' }}
                        value={p_document_type}
                        onChange={(e) => {
                            setp_document_type(e.target.value);

                        }}
                    >
                        <MenuItem value="pdf" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Pdf &nbsp;</MenuItem>
                        <MenuItem value="sms" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >SMS  &nbsp;</MenuItem>
                        <MenuItem value="email" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Email&nbsp;</MenuItem>


                    </TextField>
                </div>
                }

                {p_document_name && <div className="div_row_gauche texte_area_filter" >
                    <TextField
                        name="document_ref_interne"
                        label="Code Document"
                        sx={{ m: 1, width: '100%' }}
                        value={p_document_ref_interne}
                        onChange={(e) => {
                            setp_document_ref_interne(e.target.value);

                        }}
                    />

                </div>}

                {p_document_name && <div className="div_row_gauche texte_area_filter" >
                    <TextField
                        name="document_sujet"
                        label="Sujet"
                        sx={{ m: 1, width: '100%' }}
                        value={p_document_sujet}
                        onChange={(e) => {
                            setp_document_sujet(e.target.value);

                        }}
                    />

                </div>}



                <div className="div_row">
                    <div style={{ "width": "48%", "marginLeft": "1rem", "float": "left" }}>
                        <div className="titre_training_text"> Programme (max 1000 caractères) </div>
                        <Editor
                            id="cherif"
                            onInit={(evt, editor) => editorRef_programme.current = editor}
                            initialValue={field_programme}
                            onKeyUp={editor_keyup}
                            onEditorChange={(newValue, editor) => {
                                if (String(editor_tochange) === "1") {
                                    //alert(" change");
                                    DataUpdated();
                                    seteditor_tochange("");
                                }
                            }}
                            init={{
                                resize: false,
                                height: 500,
                                menubar: true,
                                plugins: [
                                    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'print', 'preview', 'anchor', 'searchreplace',
                                    'visualblocks', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'paste', 'code', 'help', 'wordcount',
                                    'lists', 'link', 'image', 'charmap', 'preview', 'anchor', 'searchreplace', 'visualblocks',

                                ],
                                toolbar: 'undo redo | casechange blocks | bold italic backcolor | ' +
                                    'alignleft aligncenter alignright alignjustify | ' +
                                    'bullist numlist checklist outdent indent | removeformat | a11ycheck code table help',

                                content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px; }'
                            }}
                        />
                        <Button className="bton_enreg" onClick={Add_one_Partner_Document} style={{ "margin": "1rem" }}
                        >Ajouter &nbsp;

                        </Button>


                        <Button className="bton_suppr" onClick={delete_document} style={{ "margin": "1rem" }}
                        > Supprimer &nbsp;

                        </Button>
                    </div>



                    <div style={{ "width": "48%", "marginLeft": "1rem", "float": "left" }}>
                        <div className="titre1"> Action </div>


                        <div className="div_row">

                            <div className="session_caract"> Choisir un objet  <br />
                                <TextField
                                    name="collection"
                                    id="collection"
                                    select
                                    InputLabelProps={{
                                        shrink: true,
                                    }}
                                    disabled={false}
                                    className="disabled_style enable_style"
                                    value={p_collection}
                                    onChange={(e) => {
                                        setp_collection(e.target.value);


                                    }}
                                >

                                    {Get_Personnalisable_Collections_result &&
                                        Get_Personnalisable_Collections_result.map((mycollection) => (
                                            <MenuItem key={JSON.parse(mycollection).collection_technical_name}
                                                value={JSON.parse(mycollection).collection_technical_name}
                                                style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%", "fontSize": "12px" }}>
                                                {JSON.parse(mycollection).collection_fonctional_name}&nbsp;&nbsp;

                                            </MenuItem>
                                        ))}


                                </TextField>

                            </div>
                            {<div className="session_caract"> Choisir un champ  <br />
                                <TextField
                                    name="champ_table"
                                    id="champ_table"
                                    select
                                    InputLabelProps={{
                                        shrink: true,
                                    }}
                                    disabled={false}
                                    className="disabled_style enable_style"
                                    value={p_champ_table}
                                    onChange={(e) => {
                                        setp_champ_table(e.target.value);
                                    }}
                                >

                                    {Get_Personnalisable_Collection_and_Fields_result &&
                                        Get_Personnalisable_Collection_and_Fields_result.filter((local_mymanager) => JSON.parse(local_mymanager).collection_technical_name === p_collection).map((mycollection) => (
                                            <MenuItem key={JSON.parse(mycollection).field_technical_name}
                                                value={JSON.parse(mycollection).field_technical_name}
                                                style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%", "fontSize": "12px" }}>
                                                {JSON.parse(mycollection).field_fonctional_name}&nbsp;&nbsp;

                                            </MenuItem>
                                        ))}
                                </TextField>

                            </div>}




                        </div>



                        <Button className="bton_enreg" onClick={add_selected_fields} style={{ "margin": "1rem" }}
                        >Ajouter Champ Choisi &nbsp;

                        </Button>

                    </div>
                </div>
            </div>
        </div >

    )
}


export default TestUrl_New;