﻿import React, { Fragment, memo, useEffect, useState } from 'react';
import { useHistory, withRouter } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faReply, faSave } from '@fortawesome/free-solid-svg-icons';
import MantNivel1Int from './MantNivel1Int.jsx';
import { SiteRutas } from '../../../request/RutasConfig.jsx';
import { muestraArbolEmpleados, validarInt, validarDecimal, farmatearMontos } from '../../../components/Util/Util.jsx';
//Invocaciones datos
import { Nivel1_Listar_Request, Nivel1_Consulta_Request, Nivel1_Guardar_Request, Nivel1_Modificar_Request, ParametrosGenerales_Consulta_Request } from "../../../request/MantenimientosRequest.jsx"
import { useSessionStorage } from '../../../components/Util/Hooks/useSessionStorage.jsx';
import { useLocalStorage } from '../../../components/Util/Hooks/useLocalStorage.jsx';
//utilitarios
import { Notificacion } from '../../../components/Util/Notificacion/Notificacion.jsx';
import { manageError } from '../../../components/Util/ManageError.js';
import ModalSpinner from '../../../components/UI/modalSpinner/modalSpinner.jsx';
import Swal from 'sweetalert2';

//Seguridad
import Session from '../../../components/Util/session/index.jsx';
import Config from '../../../components/Util/constantes.js';
import { Obtener_MenuOpciones_Lista_Request, Obtener_MenuNombre_Request } from "../../../request/MenuRequest.jsx"
import ModalSeguridad from "../../Seguridad/ModalSeguridad.jsx";
import optSeg from '../../../components/Util/seg-menu-opciones.js';

export function MantNivel1(props) {

    let historyMenu = useHistory();
    const [token, setToken] = useSessionStorage('token', '');
    const [usuario, setUsuario] = useSessionStorage('usuario');
    const [codigo, setCodigo] = useState('');
    const [id, setId] = useState('');
    const [empresa, setEmpresa] = useSessionStorage('empresa');
    const [ubicacion, setUbicacion] = useLocalStorage('Ubicacion', null);
    const [spinnerModal, setSpinnerModal] = useState(undefined);
    const [spinnerLabel, setSpinnerLabel] = useState('');
    const [spinnerTipo, setSpinnerTipo] = useState(1);
    const [datosPG, setDatosPG] = useState([]);

    const botones = [

        {
            name: "btnHomeC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => volverAtras(),
            leyenda: "",
            iclase: faReply,
            tooltip: "Volver"
        },
        {
            name: "btnGuardar",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => ingresarDatos(),
            leyenda: "",
            iclase: faSave,
            tooltip: "Guardar"
        }
    ]

    const listaCampos = {
        Codigo: { value: 0, attributes: { readOnly: true, focus: false, label: 'Número', hidden: 'none', Editando: false, maxLength: "4" } },
        Nombre: { value: '', attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: 'unset', maxLength: "50" } },
        MsgError: { value: ' ', attributes: { readOnly: false, focus: false } }
    }

    const listaMod = {
        "Nivel1_id": "",
        "Nivel1_Nombre": "",
        "Nivel1_Fec_Actualizacion": "",
    }
    const [datos, setDatos] = useState(listaCampos);
    const [listaModel, setListaModel] = useState(listaMod);

    //Seguridad
    const [usuarioS, setUsuarioS] = useSessionStorage('UsuarioS');
    const [menuId, setMenuId] = useState(0);
    const [menuOpciones, setMenuOpciones] = useState([]);
    const [showModalSeguridad, setShowModalSeguridad] = useState(false);
    const [opcionValidar, setOpcionValidar] = useState(0);
    const [opcionValidarNombre, setOpcionValidarNombre] = useState('');

    const spinnerModalMostrar = (pSpinnerModal, pSpinnerLabel, pSpinnerTipo) => {
        setSpinnerModal(pSpinnerModal);
        setSpinnerLabel(pSpinnerLabel);
        setSpinnerTipo(pSpinnerTipo);
    }

    const llenarListaDatos = () => {
        let _Campos = datos;
        let _Datos = listaModel;
        _Datos.Nivel1_id = _Campos.Codigo.value;
        _Datos.Nivel1_Nombre = _Campos.Nombre.value;
        return _Datos;
    }

    const asociarDatos = (pDatos) => {
        let _Campos = listaCampos;
        _Campos.Codigo.value = pDatos.Nivel1_id;
        _Campos.Nombre.value = pDatos.Nivel1_Nombre;
        return _Campos;
    }

    const volverAtras = () => {
        historyMenu.push(SiteRutas.ListaNivel1);
    }

    const cargarDatos = async () => {
        let spinnerLabel = 'Cargando datos...';
        spinnerModalMostrar(true, spinnerLabel, 3)
        let _id = (props.match.params.id == '0') ? '' : props.match.params.id;

        if (_id.length > 0) {
            const response = await Nivel1_Consulta_Request(token, _id);
            if (response.Exitoso) {
                const _datos = asociarDatos(response.Datos);
                setDatos(_datos);
                setCodigo(_id); 
            }
            else {
                const _login = manageError(response, props, '');
                spinnerModalMostrar(false, '', 3);
                if (!_login) { volverAtras(); }
                return false;
            }
        } else {
            setDatos(listaCampos);
            setCodigo(_id);
        }
        setId(_id);

        const responsePG = await ParametrosGenerales_Consulta_Request(token, empresa);
        if (responsePG.Exitoso) {
            const _datos = datos;
            _datos.Nombre.attributes.label = "Nombre " + responsePG.Datos.Nivel1_Nombre;
            setDatosPG(responsePG.Datos);
        }
        else {
            const _login = manageError(response, props, '');
            spinnerModalMostrar(false, '', 3);
            if (!_login) { volverAtras(); }
            return false;
        }

        const _MenuNomb = await cargarMenuNombre(Config.Modulo, optSeg.TMenuSistema.Nivel1.value); 
        let _menuId = 0;

        if (_MenuNomb.ID != undefined) {
            _menuId = _MenuNomb.ID;
        }
        const _UsuarioS = usuarioS;
        let _menuOpciones = null;
        if (_menuId > 0) {
            _menuOpciones = await cargarMenuOpciones(Config.Modulo, _UsuarioS, _menuId);
        }
        setMenuId(_menuId), setMenuOpciones(_menuOpciones)

        spinnerModalMostrar(false, '', 3)
    }

    useEffect(() => {
        muestraArbolEmpleados(false);
        const carga = async () => { await cargarDatos() }
        carga()
    }, [])

    const ingresarDatos = async () => {
        if (validarDatos()) {
            const _id = id;
            const optSegopt = optSeg.TOpciones_Menu;
            const _value = (_id > 0) ? optSegopt.Editar.value : optSegopt.Nuevo.value;
            let validar = validarMenuOpcion(_value);
            if (!validar) {
                await ingresarDatosSel();
            }
        }

    }

    const ingresarDatosSel = async () => {
        if (validarDatos()) {

            const _data = llenarListaDatos();
            let resultado = '';
            let spinnerLabel = id.length > 0 ? 'Actualizando datos' : 'Ingresando datos';
            spinnerModalMostrar(true, spinnerLabel, 3)
            if (codigo.length > 0) {
                resultado = await Nivel1_Modificar_Request(token, JSON.stringify(_data));
            }
            else {
                const arreglo = await Nivel1_Listar_Request(token);
                let _id = obtenerIdFaltanteOSiguiente(arreglo.Datos);
                _data.Nivel1_id = _id;
                resultado = await Nivel1_Guardar_Request(token, JSON.stringify(_data));
            };
            spinnerModalMostrar(false, '', 3)
            if (resultado.Exitoso == true) {
                Notificacion.success('Se actualizó la información con éxito');
            }
            else {
                if (isNaN(resultado.Mensaje.trim())) {
                    const _login = manageError(resultado, props, 'Error: ');
                    spinnerModalMostrar(false, '', 3);
                    if (_login) { return false; };
                }
                else {
                    Notificacion.success('Se almacenó la información con éxito');
                }
            }
            volverAtras();
        }
    }

    const validarDatos = () => {
        const _datos = datos;
        const _datosPG = datosPG;

        if ((_datos.Nombre.value == "") || (_datos.Nombre.value == '') || (_datos.Nombre.value.trim() == '') || (_datos.Nombre.value == null)) {
            Notificacion.error('Error: Debe ingresar el dato Nombre ' + _datosPG.Nivel1_Nombre);
            return false;
        }

        return true;
    }

    const obtenerIdFaltanteOSiguiente = (arreglo) => {

        let idFaltanteOSiguiente = 0;
        let consecutivoEsCorrecto = true;

        arreglo.sort((a, b) => a.Nivel1_id - b.Nivel1_id);

        for (let i = 0; i < arreglo.length; i++) {
            const idActual = arreglo[i].Nivel1_id;

            if (idActual !== i + 1) {
                idFaltanteOSiguiente = i + 1;
                consecutivoEsCorrecto = false;
                break;
            }
        }

        if (consecutivoEsCorrecto) {
            idFaltanteOSiguiente = arreglo[arreglo.length - 1].Nivel1_id + 1;
        }

        return idFaltanteOSiguiente;
    }

    const onChangeInputInt = (e) => {

        const name = e.target.name;
        const value = e.target.value;

        const valido = validarInt(value);
        if (valido) {
            let newAttributes = datos[name].attributes;
            const Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })
            setDatos(Datos);
        }
    }
    const onChangeEditar = (e) => {

        const name = e.target.name;
        const value = (datos[name].value.toString().trim().length > 0) ? datos[name].value : 0;// e.target.value;
        let newAttributes = datos[name].attributes;
        const _Editando = !newAttributes.Editando;
        newAttributes.Editando = _Editando;
        const Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })
        if (_Editando) {
            event.target.type = 'text';
            event.target.value = value;
            event.target.setSelectionRange(0, event.target.value.toString().length);
            event.target.type = 'number';
        }
        setDatos(Datos);
    }
    const onFormatoInt = (valor) => {
        return valor;
    }
    const onChangeInput = (e) => {
        const name = e.target.name;
        const value = e.target.value;
        let newAttributes = datos[name].attributes;
        const Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })
        setDatos(Datos);
    }

    const validaSeleccionado = () => {
        let _id = id;
        if (_id >= 0) {
            return true;
        }
        else {
            Notificacion.error('Debe seleccionar un registro');
            return false;
        }
    }

    //Seguridad
    const cargarMenuOpciones = async (pModuloId, pUsuarioId, pMenuId) => {
        try {

            let listMO = await Obtener_MenuOpciones_Lista_Request(token, pModuloId, pUsuarioId, pMenuId);
            if (listMO.Exitoso === false) {
                manageError(listMO, props);
                return null;
            }
            return listMO.Datos;
        }
        catch (err) {
            Notificacion.error(`Error: cargarMenuOpciones`);
        }
    }

    const cargarMenuNombre = async (pModulo, pMenuNombre) => {
        try {
            let listMON = await Obtener_MenuNombre_Request(token, pModulo, pMenuNombre);
            if (listMON.Exitoso == false) {
                manageError(listMON, props);
                return null;
            }
            return listMON.Datos;
        }
        catch (err) {
            Notificacion.error(`Error: cargarMenuNombre`);
        }
    }

    const validarMenuOpcion = (pOpcion) => {
        let validar = false;
        let _menuOpciones = menuOpciones;
        const optSegopt = optSeg.TOpciones_Menu;
        let resultado = _menuOpciones.filter((item) => item.Opcion_Nombre == pOpcion);
        if (resultado.length > 0) {
            if (resultado[0].Opcion_Validar) {
                setShowModalSeguridad(true); setOpcionValidar(resultado[0].Opcion_Id); setOpcionValidarNombre(pOpcion);
                validar = true;
            }
        } else {
            setShowModalSeguridad(true); setOpcionValidar(resultado[0].Opcion_Id); setOpcionValidarNombre(pOpcion);
            validar = true;
        }
        return validar;
    };

    const handleCerrarModal = () => setShowModalSeguridad(false);

    const handleModificarSel = () => {
        let resultado = false;

        if (validaSeleccionado()) {

            Swal.fire({
                title: 'Modificar ' + datosPG.Nivel1_Nombre,
                html: '<h4>¿Está seguro que desea modificar el registro?</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) {
                    resultado = true;
                    ingresarDatosSel();
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    resultado = false;
                }
            })
        }

        return resultado;
    }

    const onActionResultModal = (pValido) => {
        if (pValido) {
            let _OpcionNom = opcionValidarNombre;
            setShowModalSeguridad(false); setOpcionValidar(0); setOpcionValidarNombre('');
            const _optSegopt = optSeg.TOpciones_Menu;
            switch (_OpcionNom) {
                case _optSegopt.Nuevo.value:
                    ingresarDatosSel();
                    break;
                case _optSegopt.Editar.value:
                    handleModificarSel();
                    break;
                default:
                    break;
            }
        }
    }

    return (
        <Fragment>
            <MantNivel1Int
                botones={botones}
                Titulo={datosPG.Nivel1_Nombre}
                Datos={datos}
                onChangeInputInt={onChangeInputInt}
                onChangeEditar={onChangeEditar}
                onFormatoInt={(onFormatoInt)}
                onChangeInput={onChangeInput}
            />
            <ModalSpinner
                selectedModal={spinnerModal}
                contentLabel={'spinnerModalProgress'}
                label={spinnerLabel}
                tipoSpinner={spinnerTipo}
            />
            <ModalSeguridad
                modalTitle={'Requiere Permisos'}
                menuId={menuId}
                opcionId={opcionValidar}
                show={showModalSeguridad}
                onActionResult={onActionResultModal}
                onHide={handleCerrarModal}
                {...props}
            />
        </Fragment>
    );

};
export default withRouter(memo(MantNivel1))