﻿import React from 'react';
import THead from './Partials/THead';
import TBody from './Partials/TBody';
// import Modal from 'react-modal';
import AutoBind from 'react-autobind';
import ModalNotificacion from '../../Common/ModalNotificacion';

import { ServiceRequest } from '../../Request/service';
import LocalStorage from '../../LocalStorage';


class Table extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modalIsOpen: false,
            IdPadre: 0,
            NombrePadre: '',
            lstNotificacion: [],
            lstNotificacionShow: []
        };
        AutoBind(this);
        const localStorage = new LocalStorage();

    }



    async onSelectedRow(row) {
        this.setState({ NombrePadre: row.Nombre, IdPadre: row.Id });
        await this.cargarNotificaciones(row.Id);
    }

    async cargarNotificaciones(IdPadre, NotificacionTipo, ) {
        let lstNotificacion = [];
        let lstNotificacionShow = [];
      
        let response = await ServiceRequest.Notificacion_List_All(IdPadre,
            localStorage.getItem('IndOpe_Empresa'),
            localStorage.getItem('IndOpe_Cadena')
        );
        if (response.isError == false) {
            lstNotificacion = response.data == null ? [] : response.data;

            lstNotificacionShow = lstNotificacion.filter(item => item.NotificacionTipo == (NotificacionTipo != undefined ? NotificacionTipo : 'SMS'));

        } else {
            toastr.error(response.data);
        }
        this.setState({ lstNotificacion, lstNotificacionShow, IdPadre });
    }

    async EliminarNotificacion(Id, Indicador, NotificacionTipo) {
        let response = await ServiceRequest.Notificacion_Eliminar(Id, Indicador,
            localStorage.getItem('IndOpe_Empresa'),
            localStorage.getItem('IndOpe_Cadena'));
        if (response.isError == false) {
            this.cargarNotificaciones(this.state.IdPadre, NotificacionTipo);
            toastr.success('Notificación Eliminada Correctamente.');
        } else {
            toastr.error(response.data);
        }
    };


    ValidarValores(NotificacionTipo, Valor) {

        const emailRegex = /^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i;
        const telRegex = /^[0-9]+$/i;

        if (Valor == '') {
            return 'No pueden quedar espacios en blanco.'
        };

        if (NotificacionTipo == 'Email') {
            if (!emailRegex.test(Valor)) {
                return 'Debe de ingresar un email válido.'
            }
        }

        if (NotificacionTipo == 'SMS' || NotificacionTipo == 'WhatsApp') {
            if (!telRegex.test(Valor)) {
                return 'Debe de ingresar un número de teléfono válido.'
            }
        }

        return '';
    }

    async GuardarNotificacion(Indicador, NotificacionTipo, Valor) {

        let mensaje = this.ValidarValores(NotificacionTipo, Valor);

          
        if (mensaje == '') {            
            let lstExisteNotificacion = [];
            lstExisteNotificacion = this.state.lstNotificacion.filter(item => item.Indicador == Indicador && item.NotificacionTipo == NotificacionTipo && item.NotificacionValor == Valor)
            //lstExisteNotificacion = lstNotificacion.filter(item => item.NotificacionTipo == (NotificacionTipo != undefined ? NotificacionTipo : 'SMS'));
            console.log(NotificacionTipo,'NotificacionTipo');  
            if (lstExisteNotificacion.length == 0) {
                let response = await ServiceRequest.Notificacion_Guardar(Indicador, NotificacionTipo, Valor,
                    localStorage.getItem('IndOpe_Empresa'),
                    localStorage.getItem('IndOpe_Cadena'));
                if (response.isError == false) {
                    this.cargarNotificaciones(this.state.IdPadre, NotificacionTipo);
                    toastr.success('Notificación Agregada Correctamente.');
                } else {
                    toastr.error(response.data);
                }
            }
            else {  
                toastr.error('El valor registrado ya se encuentra en la base de datos');
            }
        } else {
            toastr.error(mensaje);
        }

    };



    render() {
        const { id, data, keyRow, vertical, onSelectCombo, onChangeValor, onChangeCheckBox } = this.props;
        const dataColumns = data.columns;
        const dataRows = data.rows;
        return (
            <div>
                <div className='table-responsive'>
                    <table className={'table'} id={id}>
                        <THead columns={dataColumns} vertical={vertical} />
                        <TBody
                            rows={dataRows}
                            columns={dataColumns}
                            tableId={id}
                            keyRow={keyRow}
                            vertical={vertical}
                            onSelectCombo={onSelectCombo}
                            onChangeValor={onChangeValor}
                            onChangeCheckBox={onChangeCheckBox}
                            onDoubleClick={this.handleDoubleClick}
                            onSelectedRow={this.onSelectedRow}
                        />
                    </table>
                </div>
                <ModalNotificacion IdPadre={this.state.IdPadre}
                    NombrePadre={this.state.NombrePadre}
                    lstNotificacion={this.state.lstNotificacion}
                    lstNotificacionShow={this.state.lstNotificacionShow}
                    EliminarNotificacion={this.EliminarNotificacion}
                    GuardarNotificacion={this.GuardarNotificacion} />
                  
            </div>
        )
    }
};
export default Table; 
