import React, { Fragment } from "react";
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import cellEditFactory from 'react-bootstrap-table2-editor';
import ToolkitProvider, { Search, CSVExport } from 'react-bootstrap-table2-toolkit';
import paginationFactory, { PaginationProvider, PaginationListStandalone, PaginationTotalStandalone, SizePerPageDropdownStandalone } from 'react-bootstrap-table2-paginator';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAngleDoubleLeft } from '@fortawesome/free-solid-svg-icons';
import { Link } from 'react-router-dom';
import Botones from '../botonera/headerBotones';

const customTotal = (from, to, size) => (
    <span className="react-bootstrap-table-pagination-total">
        &nbsp;Mostrando {from} a {to} de {size} resultados
    </span>
);

const { ExportCSVButton } = CSVExport;




class grid extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: {},
            sizePerPage: 5,
        };
    }

    getDerivedStateFromProp = (nextProps, prevState) => {
        if (nextProps.actTabla != prevState.actTabla) {
            log.console('Cambio la cantidad de elementos de la actTabla1')

        }
    }

    componentDidUpdate = (nextProps) => {
        const actTabla = this.props.actTabla;
        //console.log(`componentDidUpdate entro1`);
        if (nextProps.actTabla != actTabla) {

            // console.log(`componentDidUpdate entro`)

        }
    }

    /*componentDidUpdate = (prevProps, prevState) => {
        const actTabla = this.props.actTabla;
        console.log(`componentDidUpdate entro1`);
        if (nextProps.actTabla != actTabla) {

            console.log(`componentDidUpdate entro`)

        }
    }*/

    handleronClick = (e, row, rowIndex) => {

    }

    calculasizePerPageList = (cantidad, pLineaspoPagina, pMuestraTodo) => {
        let lista = [];
        /*if(pMuestraTodo){
            lista = [ {
                text: 'Todo', value: 10000
            },{
                text: 'Todo', value: cantidad
            }]
            return lista;
        }*/
        if (pLineaspoPagina != undefined) {
            let _pag = Number(this.props.LineaspoPagina); // Number(pLineaspoPagina);//.toString().trim(), // parseInt( pLineaspoPagina);
            _pag = _pag + 1;
            lista = [{
                text: '25', value: _pag
                //text: '7', value: 7
            }, {
                text: 'Todo', value: cantidad
            }]
            return lista;
        }
        if (cantidad <= 15) {
            lista = [{
                text: '5', value: 5
            }, {
                text: '10', value: 10
            },
            {
                text: 'Todo', value: cantidad
            }]
            return lista;
        }

        if (cantidad <= 20) {
            lista = [{
                text: '5', value: 5
            }, {
                text: '10', value: 10
            }, {
                text: '15', value: 15
            },
            {
                text: 'Todo', value: cantidad
            }]
            return lista;
        }

        if (cantidad <= 50) {
            lista = [{
                text: '5', value: 5
            }, {
                text: '10', value: 10
            }, {
                text: '15', value: 15
            }, {
                text: '25', value: 25
            }, {
                text: '35', value: 35
            },
            {
                text: 'Todo', value: cantidad
            }]
            return lista;
        }
        if (cantidad > 50) {
            lista = [{
                text: '5', value: 5
            }, {
                text: '10', value: 10
            }, {
                text: '15', value: 15
            }, {
                text: '25', value: 25
            }, {
                text: '35', value: 35
            }, {
                text: '65', value: 65
            }, {
                text: '85', value: 85
            }, {
                text: '100', value: 100
            },
            {
                text: 'Todo', value: cantidad
            }]
            return lista;
        }
    }

    render() {
        const { columnas, datos, keyField, modo, rowEvents, selectRow, conFiltro, rowStyle, botones, busqueda, ingresarDetalle, eliminarDetalle, actTabla, modificarDetalle,
            exportarCVS, LineaspoPagina, nombreCSV, botonesLista, muestraTodo, titulo } = this.props;
        //const readOnlyAttr = attributes.readOnly ? { readOnly: 'readOnly' } : {};
        const { SearchBar } = Search;
        const buscar = (busqueda == undefined) ? { display: 'none', float: "right" } : { display: 'unset', float: "right" };
        const styleTit = (titulo == undefined) ? { display: 'none' } : { display: 'unset'}; 
        const _exportarCVS = (exportarCVS == undefined) ? { display: 'unset', float: "left" } : (exportarCVS == false) ? { display: 'none', float: "left" } : { display: 'unset', float: "left" };
        const name = "btnExportar";
        const clase = "btn btn-sm pull-right flipInX animated";
        const leyenda = "";
        const iclase = "fa fa-download";
        const botonera = botones == undefined ? { display: 'none' } : { display: 'unset', float: "right", margin: "-8px 0" };// [] : botones;
        const botoneslistaT = botones == undefined ? [] : botonesLista;
        // let rowSty = {};
        // rowSty = rowStyle == undefined ? rowSty.color="#b0b0b0" : rowStyle; 
        const _size = (datos == undefined) ? 0 : datos.length;   //((muestraTodo ==undefined ) ? 0 : (muestraTodo ) ? 20000: 0): datos.length;
        const _muestraTodo = (muestraTodo == undefined) ? false : muestraTodo;
        const _sizePerPageList = (_muestraTodo == true) ? 0 : this.calculasizePerPageList(_size, LineaspoPagina, _muestraTodo);
        const _hideSizePerPage = (_muestraTodo == true) ? true : (datos == undefined) ? true : ((datos.length == 0) ? true : false);
        const pageButtonRenderer = ({
            page,
            active,
            disable,
            title,
            onPageChange
        }) => {
            const handleClick = (e) => {
                e.preventDefault();
                onPageChange(page);
            };
            const activeStyle = {};
            if (active) {
                activeStyle.backgroundColor = '#d73220';
                activeStyle.color = 'white';
            } else {
                activeStyle.backgroundColor = 'white';
                activeStyle.color = '#d73220';
            }
            if (typeof page === 'string') {
                activeStyle.backgroundColor = 'white';
                activeStyle.color = '#d73220';
            }
            return (
                <li className="page-item">
                    <a href="#" onClick={handleClick} style={activeStyle}>{page}</a>
                </li>
            );
        };
        const optPaginacion = {
            //custom: true,
            paginationSize: (_muestraTodo == true) ? 0 : this.state.sizePerPage,
            pageStartIndex: (_muestraTodo == true) ? 0 : 1,
            alwaysShowAllBtns: true, // Always show next and previous button
            withFirstAndLast: true, // Hide the going to First and Last page button
            hideSizePerPage: _hideSizePerPage, // false, // Hide the sizePerPage dropdown always
            hidePageListOnlyOnePage: true, // Hide the pagination list when only one page
            firstPageText: '<<',
            prePageText: '<',
            nextPageText: '>',
            lastPageText: '>>',
            nextPageTitle: 'Siguiente Página',
            prePageTitle: 'Página Anterior',
            firstPageTitle: 'Primera Página',
            lastPageTitle: 'Última Página',
            showTotal: !_muestraTodo,
            paginationTotalRenderer: customTotal,
            sizePerPageList: _sizePerPageList, // A numeric array is also available. the purpose of above example is custom the text      
            pageButtonRenderer
        };
        const NombreCsv = nombreCSV ?? "DatosTabla";
        const csvExport = {
            fileName: `${NombreCsv}.csv`,
            separator: ',',
            ignoreHeader: false,
            noAutoBOM: false,
            blobType: "text/plain;charset=UTF-8",
        };

        const Boton = ({ name, clase, evento, leyenda, iclase, indice, tooltip }) => {
            const _clase = (tooltip !== undefined) ? (tooltip.length !== 0) ? "tooltiptext2" : "" : "";

            return (
                <div key={indice} className="tooltip2"><span className={_clase}>{tooltip}</span>
                    <a key={indice} id={name} type="button" className={clase} onClick={evento}><FontAwesomeIcon icon={iclase} />{leyenda}</a>
                </div>
            )
        }

        //<button id="btnVerArbol" type="button" className="btn pull-right flipInX animated" onClick={this.onClickVerArbol}><FontAwesomeIcon icon={faAngleDoubleLeft} style={iClase} /></button>


        const SelectBotones = ({ botones }) => {

            return botones.map((item, index) => {
                //const _clase =   (item.tooltip !== undefined) ? (item.tooltip.length  !== 0  ) ? "tooltiptext2" : "" : "";  
                return <Boton key={index}
                    name={item.name}
                    clase={item.clase}
                    evento={item.evento}
                    leyenda={item.leyenda}
                    iclase={item.iclase}
                    indice={index}
                    tooltip={item.tooltip}
                />
            })
        }


        const BotonDet = () => {

            return (
                <Fragment>
                    <SelectBotones
                        botones={botoneslistaT}
                    />
                </Fragment>
            );
        }

        const renderSizePerPageDropDown = props => {

            return (
                <div className='btn-group'>
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        {props.sizePerPage} <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                        {
                            props.sizePerPageList.map((n, idx) => {
                                return (
                                    <li key={idx}><a class="dropdown-item" onClick={() => {
                                        let pPage = props.page;

                                        if (Math.ceil(datos.length / n.value) < props.page) {
                                            pPage = 0;
                                        }

                                        props.onSizePerPageChange(n.value, pPage)
                                    }}>{n.text}</a></li>
                                );
                            })
                        }
                    </ul>
                </div>
            );
        }

        return (

            <Fragment>
                <ToolkitProvider
                    keyField={keyField}
                    data={datos}
                    columns={columnas}
                    search={{ searchFormatted: true }}
                    exportCSV={csvExport}
                >
                    {
                        props => (
                            <div>
                                <div className='row margenBotonesTabla'>

                                    <div style={styleTit} className={"col-xs-12 col-sm-12 col-md-12 col-lg-12"}>
                                        <h3>{titulo}</h3>
                                    </div>

                                    <div className={"col-xs-12 col-sm-12 col-md-12 col-lg-12"} style={{ margin: "15px 0" }}>

                                        <div style={{ float: "left" }}>
                                            <div class="tooltip2"><span class="tooltiptext2">Exportar</span>
                                                <ExportCSVButton {...props.csvProps} className={clase} exportOptions={{ fileName: 'tableExport' }} >
                                                    <i className={iclase} ></i>
                                                </ExportCSVButton>
                                            </div>
                                        </div>
                                        <div style={botonera}>
                                            <BotonDet />
                                        </div>
                                        <div style={buscar}>
                                            <SearchBar {...props.searchProps} placeholder="Buscar" tableId={`${keyField}-${datos.length}`} />
                                        </div>
                                    </div>
                                </div>
                                {(_muestraTodo == false) ?
                                    <PaginationProvider
                                        pagination={paginationFactory(optPaginacion)}
                                    >
                                        {
                                            ({
                                                paginationProps,
                                                paginationTableProps
                                            }) => (
                                                <div>
                                                    <div className='table-responsive'>
                                                        <BootstrapTable
                                                            //remote
                                                            {...props.baseProps}
                                                            {...paginationTableProps}
                                                            filter={filterFactory()}
                                                            cellEdit={cellEditFactory(modo)}
                                                            striped={false}
                                                            hover={true}
                                                            condensed={false}
                                                            rowEvents={rowEvents}
                                                            selectRow={selectRow}
                                                            noDataIndication={'No hay datos que mostrar'}
                                                            insertRow={true}
                                                            rowStyle={rowStyle}
                                                        />
                                                    </div>

                                                </div>
                                            )
                                        }
                                    </PaginationProvider>
                                    :
                                    <div>
                                        <div className='table-responsive'>
                                            <BootstrapTable
                                                //remote
                                                {...props.baseProps}
                                                // {...paginationTableProps}
                                                filter={filterFactory()}
                                                cellEdit={cellEditFactory(modo)}
                                                striped={false}
                                                hover={true}
                                                condensed={false}
                                                rowEvents={rowEvents}
                                                selectRow={selectRow}
                                                noDataIndication={'No hay datos que mostrar'}
                                                insertRow={true}
                                                rowStyle={rowStyle}
                                            />
                                        </div>

                                    </div>
                                }
                            </div>
                        )
                    }
                </ToolkitProvider>
                <hr></hr>
            </Fragment>



        )
    }
}
export default grid;