﻿import React, { memo, Fragment, Component } from 'react'
import { withRouter } from 'react-router-dom';
import { ImagenesRutas } from "../../request/RutasConfig.jsx";
import Botones from '../../components/UI/botonera/headerBotonesOld.js';
import ModalImagen from '../../components/UI/Imagen/modalImagenAniversarios.jsx';
import { Notificacion } from '../../components/Util/Notificacion/Notificacion.jsx';
import {
    Aniversarios_SubirImagen_Request,
    tablaFontSize_NumeroAniversario,
    Obtener_lstHtml,
    TablaRango_GuardarLista,
    Actualizar_TamnoFuente,
    Eliminar_TamanoFuente,
    Registrar_Datos,
    Obtener_ParamGenerales
} from "../../request/MantenimientosRequest.jsx"
import Session from '../../components/Util/session/index.jsx';
import TablaFiltro from '../../components/UI/tablaFiltroShort/tablaFiltroShort.jsx';
import Select from "../../components/UI/Select/Select";
import { validarInt, validarDecimal } from '../../components/Util/Util.jsx';
import ModalRango from './modalRango.jsx';
import Swal from 'sweetalert2';
import ComboBox from '../../components/UI/comboBox/combobox.jsx';
import TextArea from '../../components/UI/textArea/textArea.jsx';

const rowEventsDist = {
    onClick: (e, row, rowIndex) => {
    }
};


class TabAniversario extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showModalImagen: false,
            fotoSrc: ImagenesRutas.AniversariosIcon,
            archivoFoto: null,
            AltoYAnchoImg: [{ width: 0, height: 0, x: 0, y: 0 }],
            imgAniversario: '',
            listaRangoCes: [],
            listaRangoPre: [],
            columnasRangoPre: [
                { dataField: 'Rango_Desde', text: 'Desde', hidden: false, sort: false, editable: false },
                { dataField: 'Rango_Hasta', text: 'Hasta', hidden: false, sort: false, editable: false },
                { dataField: 'Rango_Valor', text: 'Tamaño Fuente', csvText: 'Dias Aplicar', hidden: false, sort: false, editable: true, attributes: { max: 100, min: 1 } },
                //{ dataField: 'Eliminar', text: 'Eliminar', csvText: 'Dias Aplicar', hidden: false, sort: false, editable: true },

            ],
            cellEdit: {},
            tap: 0, botonDetPre: [], botonDetCes: [], eventTabla: () => { },
            botonPre: [],
            Datos: {
                Desde: { value: '', attributes: { readOnly: true, focus: false } },
                Hasta: { value: '', attributes: { readOnly: false, focus: false } },
                DiasAplicar: { value: '', attributes: { readOnly: false, focus: false, max: 100, min: 1 } },
                //Eliminar: { value: '', attributes: { readOnly: false, focus: false } },
            },
            menuId: 0, menuOpciones: [], textoAdicional: "",
            opcionValidar: 0,
            lstHTML: [],
            textoCorreoAniversario: "",
            DatosHtmlAniversario: {
                Html_Id: {
                    value: "",
                    attributes: {
                        readOnly: false,
                        focus: false,
                        hidden: "unset",
                        //label: "Tipo:"
                    }
                }
            },
            //ModalRango
            selectModal: undefined,
        }
    }

    //Imagen Aniversario
    handleDataImagenAniversario = async (event) => {
        let formData = new FormData();
        formData.append("FormFile", event)
        this.setState({ archivoImagen: event })



    };
    handleClickSelFoto = (e) => {
        this.setState({ showModalImagen: true });

    }
    handleSubirFoto = async () => {
        const usuario = JSON.parse(sessionStorage.getItem('usuario'));
        if (!this.state.archivoFoto) {
            Notificacion.error('Dede seleccionar una imagen');
            return;
        }
        const pParametros = {
            TipoImagen: "Imagen_Aniversario",
            File: this.state.archivoImagen,
            Usuario: usuario
        };
        let widthImg = this.state.AltoYAnchoImg.width;
        let height = this.state.AltoYAnchoImg.height;
        if (!this.ValidarTamnoImg(widthImg, height)) {
            Notificacion.error('Las dimensiones de la imagen no son permitidas');
        }
        else {
            //validarTamanoImg()
            const token = JSON.parse(sessionStorage.getItem('token'));

            let response = await Aniversarios_SubirImagen_Request(token, pParametros);
            if (response.Exitoso == false) {
                Notificacion.error('No se ha podido guardar la imagen seleccionada.');
            }
            else {
                Notificacion.success('Se ha guardado la imagen de Aniversario, con éxito.');
            }
        }

    }
    nuevaImagen = async (canvas, croppedArea) => {
        this.setState({ fotoSrc: canvas, archivoFoto: canvas, showModalImagen: false, AltoYAnchoImg: croppedArea });

    }
    handleCerrarModalImg = () => this.setState({ showModalImagen: false });
    //Validaciones
    ValidarTamnoImg = (widthImg, height) => {
        if (widthImg > 720 && height > 480) {
            return false;
        }
        else {
            return true;
        }
    }
    validarArreglo = (arreglo, columnaTexto, columnaValor, descripcion) => {

        let arregloRetorno = [];

        if (columnaTexto !== undefined && columnaTexto !== '') {
            if (Array.isArray(arreglo) && arreglo.length > 0) {
                if ((arreglo[0].MsgError === null || arreglo[0].MsgError === undefined ? '' : arreglo[0].MsgError) === '') {

                    arreglo.map(function (item) {
                        arregloRetorno.push({ value: item[columnaValor], label: item[columnaTexto] });
                    });

                } else {
                    if (arreglo[0].MsgError !== null) {
                        Notificacion.error("No se encontraron datos para: " + descripcion);
                        //Error({ text: `No se encontraron datos para: ${descripcion}` });
                        this.volverAtras();
                    }
                }
            } else {
                Notificacion.error("No se encontraron datos " + descripcion == undefined ? '' : ': ' + descripcion);
                //Error({ text: `No se encontraron datos${descripcion == undefined ? '' : ': ' + descripcion}` });
            }
        } else {
            if (Array.isArray(arreglo) && arreglo.length > 0) {
                if ((arreglo[0].MsgError === null || arreglo[0].MsgError === undefined ? '' : arreglo[0].MsgError) !== '') {
                    Notificacion.error("Error: " + arreglo[0].MsgError);
                    //Error({ text: `${arreglo[0].MsgError}` });
                } else {
                    arregloRetorno = arreglo;
                }
            } else {
                Notificacion.error("No se encontraron datos " + descripcion == undefined ? '' : ': ' + descripcion);
                //Error({ text: `No se encontraron datos${descripcion == undefined ? '' : ': ' + descripcion}` });
            }
        }

        return arregloRetorno;

    }
    validaTablaMontos(pid, pTab, pnewValue) {

        let lista = [];
        let indice = -1;
        let valor = parseInt(pnewValue);
        if (pTab == 1) {
            lista = this.state.listaRangoPre;
        }
        lista.filter((item, i) => {
            if (item.id == pid) {
                indice = i;
            }
        });

        if (indice => 0) {
            if (indice < lista.length - 1) {
                indice = indice + 1;
                for (let j = indice, len = lista.length; j < len; j++) {
                    if (valor > 0) {//(parseInt(lista[j].Desde) <= valor){
                        valor = valor + 1;
                        lista[j].Desde = valor;
                        if (parseInt(lista[j].Hasta) <= valor) {
                            valor = valor + 1;
                            lista[j].Hasta = valor;
                        } else {
                            valor = 0;
                        }
                    }
                }
            }
            if (pTab == 1) {
                this.setState({ listaRangoPre: lista });
            }
        }
    }
    validaMonto = (newValue) => {
        if (newValue.toString().trim().length == 0) {
            return {
                valid: false,
                message: 'Debe ingresar un dato válido'
            };
        }
        if (isNaN(newValue)) {
            return {
                valid: false,
                message: 'Debe ingresar un dato válido'
            };
        }
        if (newValue < 1) {
            return {
                valid: false,
                message: 'Valor permitido de 1 a 100'
            };
        }
        if (newValue > 100) {
            return {
                valid: false,
                message: 'Valor permitido de 1 a 100'
            };
        }
        let isValid = true;
        isValid = validarDecimal(newValue);
        if (isValid == false) {
            return {
                valid: false,
                message: 'Debe ingresar un dato válido'
            };
        }
        return { valid: true, mensaje: '', new: newValue };

    }
    validarDatos = (pDatos) => {

        let mensaje = '';
        if (pDatos.Desde.value.toString().trim().length == 0) { mensaje = ' Desde' }
        if (pDatos.Hasta.value.toString().trim().length == 0) {
            if (mensaje.trim().length == 0) {
                mensaje = ' Hasta'
            } else {
                mensaje = mensaje + ', Hasta'
            }
        }
        if (pDatos.DiasAplicar.value.toString().trim().length == 0) {
            if (mensaje.trim().length == 0) {
                mensaje = 'Tamaño Fuente'
            } else {
                mensaje = mensaje + ', Tamaño Fuente'
            }
        }

        if (pDatos.DiasAplicar.value < 1 || pDatos.DiasAplicar.value > 100) {
            //Notificacion.error(
            mensaje = "Debe ingresar un dato válido Tamaño Fuente, entre 1 y 100"
            //);
            return mensaje;
        }

        if (mensaje.trim().length > 0) {

            mensaje = 'Debe ingresar datos válidos en los siguientes campos:' + mensaje + '.'
            return mensaje;
        }

        if (pDatos.Desde.value >= pDatos.Hasta.value) {
            mensaje = 'El valor Hasta debe ser mayor al valor Desde.'
            return mensaje;
        }
        if (pDatos.Hasta.value > 100) {
            mensaje = 'El valor máximo permitido de Hasta es 100.'
            return mensaje;
        }

        return mensaje;

    }

    //Modal Rango
    agregarRangosPre = (event) => {
        this.handleModal(1, event);

    }
    eliminarRangosPre = (event) => {
        this.handleModalEliminar(1, event);

    }
    cerrarModal = () => {
        const modal = undefined;
        const Datos = this.state.Datos;
        Datos.Desde.value = 0;
        Datos.Hasta.value = 0;
        Datos.DiasAplicar.value = 0;


        this.setState(() => ({
            selectModal: modal, Datos
        }));
    }
    seleccionModal = () => {

        let Datos = { ...this.state.Datos };
        const mensaje = this.validarDatos(Datos);
        let eventTabla = this.state.eventTabla;
        if (mensaje.trim().length == 0) {
            const selectModal = undefined;
            const lista = this.insertaFilaDato(Datos);


            Datos.Desde.value = 0;
            Datos.Hasta.value = 0;
            Datos.DiasAplicar.value = 0;
            const _tap = this.state.tap;
            if (_tap == 1) {
                this.setState({ selectModal, Datos, listaRangoPre: lista });
                eventTabla('0');
                eventTabla('');
            }

        }
        else {
            Notificacion.error("Error: " + mensaje)
            //Error({ text: 'Error: ' + mensaje, title: '' });
        }

    }
    handleModal = (pTab, event) => {
        const modal = true;
        const tap = pTab;
        let Datos = this.state.Datos;
        let indice = 0;
        const session = new Session();
        //const _GenPaisModulo = session.get('GenPaisModuloPL');
        const eventTabla = event;

        if (pTab == 1) {

            const listaRangoPre = this.state.listaRangoPre;
            if (listaRangoPre.length > 0) {

                indice = listaRangoPre.length - 1;
                Datos.Desde.value = parseInt(listaRangoPre[indice].Rango_Hasta) + 1;
            } else {
                Datos.Desde.value = 0;
            }

        }

        this.setState(() => ({
            selectModal: modal, tap, Datos, eventTabla
        }));

    }
    handleModalEliminar = (pTab, event) => {
        const modal = true;
        const eventTabla = event;
        const tap = pTab;

        Swal.fire({
            title: 'Eliminar tamaño de fuente',
            html: '<h4>¿Está seguro que desea eliminar el <strong>último</strong> rango registrado?</h4>',
            type: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10a599',
            cancelButtonColor: '#d33',
            confirmButtonText: '<h5><i class="fa fa-check fa-fw"></i> Sí</h5>',
            cancelButtonText: '<h5><i class="fa fa-remove fa-fw"></i> No</h5>',
            reverseButtons: true,
            allowOutsideClick: false,
        }).then((result) => {
            if (result.value) {
                let lista = this.state.listaRangoPre;
                if (lista.length <= 0) {
                    Notificacion.warning("No existen datos para eliminar")
                }
                else {
                    this.borrarDatos();
                }
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                resultado = false;
            }
        })


    }
    //Mantenimiento
    insertaFilaDato = (pDatos) => {

        const _tap = this.state.tap;

        let lista = [];
        let tipo = -1;
        let tipostr = '';

        if (_tap == 1) {
            lista = [...this.state.listaRangoPre];
            tipo = 0;
            tipostr = 'P';
        }
        const fecha = new Date();
        let item = { Rango_Id: 0, Rango_Desde: pDatos.Desde.value, Rango_Hasta: pDatos.Hasta.value, Rango_Valor: pDatos.DiasAplicar.value, Rango_Fecha_Actualizacion: fecha };
        this.guardaRangos(item);
        lista.push(item);

        return lista;


    }
    guardaRangos = async (item) => {
        //let resultado = '';
        const listaDatos = item;
        const token = JSON.parse(sessionStorage.getItem('token'));
        const usuario = JSON.parse(sessionStorage.getItem('usuario'));
        const resultado = await TablaRango_GuardarLista(token, usuario, JSON.stringify(listaDatos));
        if (resultado.Exitoso) {
            Notificacion.success('Se almacenó la información con éxito');
        }
        else {
            Notificacion.error('Error: ' + resultado.Mensaje);
        }
    }
    borrarDatos = async () => {
        const token = JSON.parse(sessionStorage.getItem('token'));
        const response = await Eliminar_TamanoFuente(token);
        if (response.Exitoso) {
            Notificacion.success('Tamaño fuente eliminado, con éxito');
            const response_fontsize = await tablaFontSize_NumeroAniversario(token);
            let listaRangoPre = response_fontsize.Datos;

            if (response_fontsize.Exitoso) {
                listaRangoPre = this.validarArreglo(listaRangoPre);
                this.setState({ listaRangoPre });
            }
            else {
                listaRangoPre = [];
                this.setState({ listaRangoPre });
            }
        }
        else {
            Notificacion.error('Error al eliminar tamaño fuente');
        }

    }
    Actualizar_TamanoFuente = async (pRangoDesde, pRangoHasta, pNewValue) => {
        const token = JSON.parse(sessionStorage.getItem('token'));
        const response = await Actualizar_TamnoFuente(token, pRangoDesde, pRangoHasta, pNewValue);
        if (response.Exitoso) {
            Notificacion.success('Tamaño fuente actualizado, con éxito');
            const response_fontsize = await tablaFontSize_NumeroAniversario(token);
            let listaRangoPre = response_fontsize.Datos;
            //listaRangoPre = this.validarArreglo(listaRangoPre);
            this.setState({ listaRangoPre })
        }
        else {
            Notificacion.error('Error al actualizar tamaño fuente');
        }
    }
    //Eventos
    onChangeInputInt = (e) => {
        const name = e.target.name;
        const value = e.target.value;
        let valido = false;

        valido = validarInt(value);
        if (valido) {
            let newAttributes = this.state.Datos[name].attributes;
            // newAttributes.focus = true; //Se asigna foco al componente 
            const Datos = Object.assign({}, this.state.Datos, { [name]: { value: value, attributes: newAttributes } })
            this.setState({ Datos });
        }
    }
    componentDidMount = async () => {

        const botonDetPre = [
            {
                name: "btnAgragarDetPre",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.agregarRangosPre,
                leyenda: "",
                iclase: "fa fa-plus",
                tooltip: "Agregar Rango"
            },
            {
                name: "btnEliminarDetPre",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.eliminarRangosPre,
                leyenda: "",
                iclase: "fa fa-trash",
                tooltip: "Eliminar Rango"
            }
        ]
        //Carga de Datos Prm General Aniversario
        const token = JSON.parse(sessionStorage.getItem('token'));
        const obtenerParametrosGenerales = await Obtener_ParamGenerales(token);

        this.setState({ fotoSrc: obtenerParametrosGenerales.Imagen_Aniversario })
        //Carga de tabla Rangos
        const response_fontsize = await tablaFontSize_NumeroAniversario(token);
        let listaRangoPre = response_fontsize.Datos;
        if (response_fontsize.Exitoso) {
            listaRangoPre = this.validarArreglo(listaRangoPre);
        }
        else {
            listaRangoPre = listaRangoPre;
        }

        let menuId = 0
        let menuOpciones = null;
        const Datos = {
            Desde: { value: 0, attributes: { readOnly: true, focus: false, hidden: 'unset' } },
            Hasta: { value: 0, attributes: { readOnly: false, focus: false, hidden: 'unset' } },
            DiasAplicar: { value: 0, attributes: { readOnly: false, focus: false, hidden: 'unset' } },
            //Eliminar: { value: 0, attributes: { readOnly: false, focus: false, hidden: 'unset' } }

        };
        const _botones = [
            {
                name: "btnHome",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.volverAtras,
                leyenda: "",
                iclase: "fa fa-reply",
                tooltip: "Volver"
            },
            {
                name: "btnGuardar",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.ingresarDatos,
                leyenda: "",
                iclase: "fa fa-save",
                tooltip: "Guardar"
            }

        ]
        const botonPre = [
            {
                name: "btnPreaviso",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.agregarRangosPre,
                leyenda: "",
                iclase: "fa fa-plus",
                tooltip: "Ingresar"
            },
            {
                name: "btnEliminar",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.eliminarRangosPre,
                leyenda: "",
                iclase: "fa fa-trash",
                tooltip: "Eliminar Rango"
            }
        ];
        const columnasRangoPre = [
            { dataField: 'Rango_Desde', text: 'Desde', hidden: false, sort: false, editable: false },
            {
                dataField: 'Rango_Hasta', text: 'Hasta', hidden: false, sort: false, editable: false, validator: (newValue, row, column) => {
                    const valido = this.validaCantidadPre(newValue, row, true);
                    return valido;
                }
            },
            {
                dataField: 'Rango_Valor', text: 'Tamaño Fuente', csvText: 'Tamaño Fuente', hidden: false, sort: false, editable: true, validator: (newValue, row, column) => {
                    const valido = this.validaMonto(newValue, row);
                    let rangoDesde = row.Rango_Desde;
                    let rangoHasta = row.Rango_Hasta;
                    let rangoValorOriginal = row.Rango_Valor;
                    if (valido.valid == true && newValue != rangoValorOriginal) {
                        this.Actualizar_TamanoFuente(rangoDesde, rangoHasta, newValue);
                    }
                    return valido;
                }
            },
            //{ dataField: 'Eliminar', text: 'Eliminar', hidden: false, sort: false, editable: false },
        ];
        const cellEdit = { mode: 'click', autoSelectText: true, blurToSave: true };


        this.setState({ botonPre, Datos, columnasRangoPre, cellEdit, listaRangoPre, botonDetPre, menuId, menuOpciones })

    }

    render() {
        let { id, activeKey } = this.props;
        const { showModalImagen, fotoSrc, Datos, selectModal, menuId, opcionValidar, textoCorreoAniversario, listaRangoPre } = this.state;

        const botonesFoto = [
            {
                name: " btnSelecFoto",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.handleClickSelFoto,
                leyenda: "",
                iclase: "fa fa-image",
                tooltip: "Seleccionar foto"
            }
            , {
                name: "btnSubirFoto",
                clase: "btn btn-sm pull-right flipInX animated",
                evento: this.handleSubirFoto,
                leyenda: "",
                iclase: "fa fa-upload",
                tooltip: "Subir foto"
            },

        ]
        return (
            <Fragment>
                <div className="content">
                    <div className="content-box">
                        <div className="content-box box-secondary">
                            <div className="row">
                                <div className="col-md-12">
                                    <h3>Texto adicional correo</h3>
                                    <div className="row">
                                        <TextArea
                                            id='HtmlAniversario'
                                            col="12"
                                            value={this.props.Datos.HtmlAniversario.value}
                                            attributes={this.props.Datos.HtmlAniversario.attributes}
                                            onChangeInput={this.props.handleChangeTextArea}
                                            rows='3' />
                                    </div>
                                    <h3>Diseño HTML</h3>
                                    <div className="row">
                                        <ComboBox id="selectedHtmlAniversario"
                                            col="4"
                                            attributes={this.props.Datos.HtmlAniversario.attributes}
                                            value={this.props.selectedHtmlAniversario}
                                            label={this.props.Datos.HtmlAniversario.label}
                                            datos={this.props.listaHtmlAniversario}
                                            onChange={this.props.handleselectHtmlAniversario} />
                                    </div>
                                    <h3>Imagen de Aniversario</h3>
                                    <div className="row">
                                        <div className="col-sm-8 ">
                                            <div className="">
                                                {fotoSrc == null ?
                                                    <img className="profile-picAniversarios" src={ImagenesRutas.AniversariosIcon}></img>
                                                    : null
                                                }
                                                {fotoSrc != null ?
                                                    <img className="profile-picAniversarios" src={fotoSrc}></img>
                                                    : null
                                                }
                                            </div>
                                            <div class="col-8"><strong><h6>Se recomienda que las dimensiones de la imagen sean de 720x480 o que no las supere.</h6></strong></div>
                                            <div className="" >
                                                <Botones
                                                    botones={botonesFoto}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row">
                                        <div className="col-sm-12 col-md-12">
                                            <h3>Rangos de tamaño de fuente para Aniversarios</h3>
                                            <TablaFiltro
                                                columnas={this.state.columnasRangoPre}
                                                datos={listaRangoPre}
                                                keyField={'llave'}
                                                modo={this.state.cellEdit}
                                                rowEvents={this.state.rowEventsDist}
                                                botones={this.state.botonDetPre}
                                                ingresarDetalle={this.agregarRangosPre}
                                                eliminarDetalle={this.eliminarRangosPre}
                                                nombreCSV={"Preaviso"}
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <br />
                        </div>
                    </div>
                </div>
                <ModalImagen
                    modalTitle={'Imagen Aniversario'}
                    show={showModalImagen}
                    onHide={this.handleCerrarModalImg}
                    nuevaImagen={this.nuevaImagen}
                    handleDataImagenAniversario={this.handleDataImagenAniversario}
                />
                <ModalRango
                    selectedModal={selectModal}
                    contentLabel={'selectedBusquedas'}
                    label={'Rangos'}
                    onChangeInputInt={this.onChangeInputInt}
                    onChangeInputDecimal={this.onChangeInputDecimal}
                    cerrarModal={this.cerrarModal}
                    seleccionModal={this.seleccionModal}
                    Datos={Datos}

                />
            </Fragment >
        );
    }
};
export default withRouter(memo(TabAniversario));