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 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;
        if (nextProps.actTabla != actTabla) {



        }
    }

    componentDidMount = () => {
        console.log(`this.props.datos: ${JSON.stringify(this.props.datos)}`);
        console.log(`this.props.datos: ${JSON.stringify(this.props.keyField)}`);

    }
    handleronClick = (e, row, rowIndex) => {

    }

    calculasizePerPageList = (cantidad, pLineaspoPagina) => {
        let 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 } = this.props;
        //const readOnlyAttr = attributes.readOnly ? { readOnly: 'readOnly' } : {};
        const { SearchBar } = Search;
        const buscar = (busqueda == undefined) ? { display: 'none', float: "right" } : { display: 'unset', float: "right" };
        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" };// [] : botones;
        // let rowSty = {};
        // rowSty = rowStyle == undefined ? rowSty.color="#b0b0b0" : rowStyle; 
        const _size = (datos == undefined) ? 0 : datos.length;
        const _sizePerPageList = this.calculasizePerPageList(_size, LineaspoPagina);
        const _hideSizePerPage = (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 = '#10a599';
                activeStyle.color = 'white';
            } else {
                activeStyle.backgroundColor = 'white';
                activeStyle.color = '#10a599';
            }
            if (typeof page === 'string') {
                activeStyle.backgroundColor = 'white';
                activeStyle.color = '#10a599';
            }
            return (
                <li className="page-item">
                    <a href="#" onClick={handleClick} style={activeStyle}>{page}</a>
                </li>
            );
        };
        const optPaginacion = {
            custom: true,
            paginationSize: this.state.sizePerPage,
            pageStartIndex: 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: true,
            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 BotonDet = (props) => {

            const _Agregar = botones == undefined ? 'Agregar' : botones[0] == undefined ? 'Agregar' : botones[0].tooltip;
            const _Eliminar = botones == undefined ? 'Eliminar' : botones[1] == undefined ? 'Eliminar' : botones[1].tooltip;
            const _Modificar = botones == undefined ? 'Modificar' : botones[2] == undefined ? 'Modificar' : botones[2].tooltip;

            const botoneraAgr = botones == undefined ? { display: 'none' } : botones[0] == undefined ? { display: 'none' } : { display: 'unset', float: "right" };// [] : botones;
            const botoneraEli = botones == undefined ? { display: 'none' } : botones[1] == undefined ? { display: 'none' } : { display: 'unset', float: "right" };// [] : botones;
            const botoneraMod = botones == undefined ? { display: 'none' } : botones[2] == undefined ? { display: 'none' } : { display: 'unset', float: "right" };

            const onClickAgragarDet = () => {
                ingresarDetalle(props.onSearch);
                props.onSearch('0');
                props.onSearch('');
            }

            const onClickEliminarDet = () => {
                eliminarDetalle();
                props.onSearch('0');
                props.onSearch('');
            }

            const onClickModificarDet = () => {
                modificarDetalle(props.onSearch);
                props.onSearch('0');
                props.onSearch('');
            }

            return (
                <Fragment>
                    <div style={botoneraEli} key={'1r'} className="tooltip2"><span className={'tooltiptext2'}>{_Eliminar}</span>
                        <a key={'1r'} id={'btnEliminarDet'} href="#" type="button" className={'btn btn-sm pull-right flipInX animated'} onClick={onClickEliminarDet}><i className={'fa fa-trash'}></i>{''}</a>
                    </div>
                    <div style={botoneraAgr} key={'1m'} className="tooltip2"><span className={'tooltiptext2'}>{_Agregar}</span>
                        <a key={'1m'} id={'btnAgragarDet'} href="#" type="button" className={'btn btn-sm pull-right flipInX animated'} onClick={onClickAgragarDet}><i className={'fa fa-plus'}></i>{''}</a>
                    </div>
                    <div style={botoneraMod} key={'1md'} className="tooltip2"><span className={'tooltiptext2'}>{_Modificar}</span>
                        <a key={'1m'} id={'btnModificarDet'} href="#" type="button" className={'btn btn-sm pull-right flipInX animated'} onClick={onClickModificarDet}><i className={'fa fa-pencil'}></i>{''}</a>
                    </div>

                </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 = 1;
                                        }

                                        props.onSizePerPageChange(n.value, pPage)
                                    }}>{n.text}</a></li>
                                );
                            })
                        }
                    </ul>
                </div>
            );
        }

        return (

            <Fragment>
                <ToolkitProvider
                    keyField={keyField}
                    data={datos}
                    columns={columnas}
                    search
                    exportCSV={csvExport}
                >
                    {
                        props => (
                            <div>
                                <div className='row'>
                                    <div className={"col-xs-12 col-sm-12 col-md-12 col-lg-12"} style={botonera}>
                                        <BotonDet {...props.searchProps} />
                                    </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={buscar}>
                                            <SearchBar {...props.searchProps} placeholder="Buscar" tableId={`${keyField}-${datos.length}`} />
                                        </div>

                                    </div>
                                </div>
                                <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>

                                                {renderSizePerPageDropDown({ ...paginationProps })}

                                                <PaginationTotalStandalone
                                                    {...paginationProps}
                                                />
                                                <PaginationListStandalone
                                                    {...paginationProps}
                                                />
                                            </div>
                                        )
                                    }
                                </PaginationProvider>

                            </div>
                        )
                    }
                </ToolkitProvider>
                <hr></hr>
            </Fragment>



        )
    }
}
export default grid;