﻿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 GeneralesInt from './generalesInt.jsx';
import { SiteRutas } from '../../request/RutasConfig.jsx';
import { muestraArbolEmpleados, validarInt, validarDecimal, farmatearMontos, datosArbol } from '../../components/Util/Util.jsx';
//Invocaciones datos
import { ParametrosGenerales_Consulta_Request, ParametrosGenerales_GuardarAct_Request } from "../../request/MantenimientosRequest.jsx";
import { useSessionStorage } from '../../components/Util/Hooks/useSessionStorage.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 Config from '../../components/Util/constantes.js';

//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';

function generales(props) {
    let historyMenu = useHistory();
    const [token, setToken] = useSessionStorage('token', '');
    const [usuario, setUsuario] = useSessionStorage('usuario');
    const [empresa, setEmpresa] = useSessionStorage('empresa');
    const [empresaNombre, setEmpresaNombre] = useSessionStorage('empresaNombre');
    const [genPaisModulo, setGenPaisModulo] = useSessionStorage('pais');
    const [codigo, setCodigo] = useState('');
    const [categoria, setCategoria] = useState([]);
    const [id, setId] = useState('');
    const [fileSelector, setFileSelector] = useState(undefined);
    const [spinnerModal, setSpinnerModal] = useState(undefined);
    const [spinnerLabel, setSpinnerLabel] = useState('');
    const [spinnerTipo, setSpinnerTipo] = useState(1);
    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 = {
        ID: { value: '', attributes: { readOnly: false, focus: false, label: 'Descripción', hidden: 'unset', maxLength: "80" } },
        UbicacionFotos: { value: '', attributes: { readOnly: false, focus: false, label: 'Carpeta para administrar archivos del colaborador', hidden: 'unset', maxLength: "255" } },
        ImpresionesAccionPersonal: { value: 0, attributes: { readOnly: false, focus: false, label: 'Cantidad de Impresiones de acción de personal', hidden: 'unset', maxLength: "80" } },
        ControlaCantidadPlazaOficinas: { value: false, attributes: { readOnly: false, focus: false, label: 'Controla cantidad de Plazas por Oficina', hidden: 'unset', maxLength: "80" } },
        MuestraDiasVacaciones: { value: false, attributes: { readOnly: false, focus: false, label: 'Muestra días de vacaciones en colillas de pago', hidden: 'unset', maxLength: "80" } },
        MuestraAntiguedad: { value: false, attributes: { readOnly: false, focus: false, label: 'Muestra datos de Antigüedad en colillas de pago.', hidden: 'unset', maxLength: "80" } },
        Permite_Indicar_Beneficiario: { value: '', attributes: { readOnly: false, focus: false, label: 'Permite indicar beneficiario para liquidaciones', hidden: 'unset', maxLength: "80" } },
        Permite_Vacacion_Fraccionada: { value: '', attributes: { readOnly: false, focus: false, label: 'Permite vacaciones fraccionadas', hidden: (genPaisModulo == Config.PaisCostaRica) ? 'unset' : 'none', maxLength: "80" } },
        Habilita_GuardadoNube: { value: false, attributes: { readOnly: false, focus: false, label: 'Guardar Documentos en Azure Blob Storage', hidden: 'unset' } },
        Cadena_Conexion_AzureBlobStorage: { value: '', attributes: { readOnly: true, focus: false, label: 'Cadena de conexión', hidden: 'unset', maxLength: "250" } },
        Nombre_Contenedor_AzureBlobStorage: { value: '', attributes: { readOnly: true, focus: false, label: 'Nombre del contenedor en Azure Blob Storage', hidden: 'unset', maxLength: "50" } },
        URL_ServicioArchivos: { value: '', attributes: { readOnly: true, focus: false, label: 'Url de servicio de archivos', hidden: 'none', maxLength: "100" } },
        Nivel1_Nombre: { value: '', attributes: { readOnly: false, focus: false, label: 'Descripción Nivel 1 de ubicaciones', hidden: 'unset', maxLength: "50" } },
        Nivel2_Nombre: { value: '', attributes: { readOnly: false, focus: false, label: 'Descripción Nivel 2 de ubicaciones', hidden: 'unset', maxLength: "50" } },
        Nivel3_Nombre: { value: '', attributes: { readOnly: false, focus: false, label: 'Descripción Nivel 3 de ubicaciones', hidden: 'unset', maxLength: "50" } },
        MsgError: { value: '', attributes: { readOnly: false, focus: false, label: 'Descripción', hidden: 'unset', maxLength: "80" } },
    }

    const DatosM = {
        "ID": 0,
        "MontoEsposa": 0,
        "MontoHijo": 0,
        "SalInembargable": 0,
        "PorcPensionado": 0,
        "UbicacionFotos": '',
        "ImpresionesAccionPersonal": 0,
        "PorcExoneracionCargSoc": 0,
        "ControlaCantidadPlazaOficinas": false,
        "MuestraDiasVacaciones": false,
        "UsuarioModifica": '',
        "UsuarioFechaActualiza": '',
        "TipoCambio": 0,
        "MuestraAntiguedad": false,
        "Permite_Indicar_Beneficiario": false,
        "Permite_Vacacion_Fraccionada": false,
        "Habilita_GuardadoNube": false,
        "Cadena_Conexion_AzureBlobStorage": '',
        "Nombre_Contenedor_AzureBlobStorage": '',
        "URL_ServicioArchivos": '',
        "Nivel1_Nombre": '',
        "Nivel2_Nombre": '',
        "Nivel3_Nombre": '',
    }


    const [datos, setDatos] = useState(listaCampos);
    const [listaDatosM, setListadatosM] = useState(listaDatosM);
    const volverAtras = () => {
        historyMenu.push(SiteRutas.Empleados);
    }

    //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 = listaDatosM;

        _Datos.UbicacionFotos = _Campos.UbicacionFotos.value.trim();
        _Datos.ImpresionesAccionPersonal = _Campos.ImpresionesAccionPersonal.value === '' ? 0 : _Campos.ImpresionesAccionPersonal.value;
        _Datos.ControlaCantidadPlazaOficinas = _Campos.ControlaCantidadPlazaOficinas.value;
        _Datos.MuestraDiasVacaciones = _Campos.MuestraDiasVacaciones.value;
        _Datos.MuestraAntiguedad = _Campos.MuestraAntiguedad.value;
        _Datos.Permite_Indicar_Beneficiario = _Campos.Permite_Indicar_Beneficiario.value;
        _Datos.Permite_Vacacion_Fraccionada = _Campos.Permite_Vacacion_Fraccionada.value;
        _Datos.Habilita_GuardadoNube = _Campos.Habilita_GuardadoNube.value;
        _Datos.Cadena_Conexion_AzureBlobStorage = _Campos.Cadena_Conexion_AzureBlobStorage.value;
        _Datos.Nombre_Contenedor_AzureBlobStorage = _Campos.Nombre_Contenedor_AzureBlobStorage.value;
        _Datos.URL_ServicioArchivos = _Campos.URL_ServicioArchivos.value;
        _Datos.Nivel1_Nombre = _Campos.Nivel1_Nombre.value;
        _Datos.Nivel2_Nombre = _Campos.Nivel2_Nombre.value;
        _Datos.Nivel3_Nombre = _Campos.Nivel3_Nombre.value;
        _Datos.UsuarioModifica = usuario;
        _Datos.ID = _Campos.ID.value;
        return _Datos;
    }

    const asociarDatos = (pDatos) => {
        let _Campos = listaCampos;
        _Campos.ID.value = pDatos.ID;
        _Campos.UbicacionFotos.value = pDatos.UbicacionFotos.trim();
        _Campos.ImpresionesAccionPersonal.value = pDatos.ImpresionesAccionPersonal;
        _Campos.ControlaCantidadPlazaOficinas.value = pDatos.ControlaCantidadPlazaOficinas;
        _Campos.MuestraDiasVacaciones.value = pDatos.MuestraDiasVacaciones;
        _Campos.MuestraAntiguedad.value = pDatos.MuestraAntiguedad;
        _Campos.Permite_Indicar_Beneficiario.value = pDatos.Permite_Indicar_Beneficiario;
        _Campos.Permite_Vacacion_Fraccionada.value = pDatos.Permite_Vacacion_Fraccionada;
        _Campos.Habilita_GuardadoNube.value = pDatos.Habilita_GuardadoNube;
        _Campos.Cadena_Conexion_AzureBlobStorage.value = pDatos.Cadena_Conexion_AzureBlobStorage;
        _Campos.Nombre_Contenedor_AzureBlobStorage.value = pDatos.Nombre_Contenedor_AzureBlobStorage;
        _Campos.URL_ServicioArchivos.value = pDatos.URL_ServicioArchivos;
        _Campos.Nivel1_Nombre.value = pDatos.Nivel1_Nombre;
        _Campos.Nivel2_Nombre.value = pDatos.Nivel2_Nombre;
        _Campos.Nivel3_Nombre.value = pDatos.Nivel3_Nombre;
        //habilitar o deshabilitar campos Azure
        _Campos.Cadena_Conexion_AzureBlobStorage.attributes.readOnly = !pDatos.Habilita_GuardadoNube;
        _Campos.Nombre_Contenedor_AzureBlobStorage.attributes.readOnly = !pDatos.Habilita_GuardadoNube;
        _Campos.URL_ServicioArchivos.attributes.readOnly = !pDatos.Habilita_GuardadoNube;



        return _Campos;
    }
    const cargarDatos = async () => {
        let _id = empresa;
        let spinnerLabel = 'Cargando datos...';
        spinnerModalMostrar(true, spinnerLabel, 3);
        const response = await ParametrosGenerales_Consulta_Request(token, _id);
        if (response.Exitoso) {
            const _datos = asociarDatos(response.Datos);
            setDatos(_datos);
            setListadatosM(response.Datos);

        }
        else {
            const _login = manageError(response, props, '');
            spinnerModalMostrar(false, '', 3);
            if (!_login) { volverAtras(); }
            return false;
        }

        const _MenuNomb = await cargarMenuNombre(Config.Modulo, optSeg.TMenuSistema.ParametrosGenerales.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()
    }, [])
    //eventos
    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 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 onChangeInputDecimal = (e) => {

        const name = e.target.name;
        const value = e.target.value;

        const valido = validarDecimal(value);
        if (valido) {
            let newAttributes = datos[name].attributes;

            let Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })
            setDatos(Datos);
        }
    }

    const onFormato = (valor) => {
        return farmatearMontos(valor);
    }
    const onFormatoInt = (valor) => {
        return valor;
    }
    const onChangeEditar = (e) => {

        const name = e.target.name;
        const value = datos[name].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) {
            e.target.type = 'text';
            e.target.value = value;
            e.target.setSelectionRange(0, e.target.value.toString().length);
            e.target.type = 'number';
        }
        setDatos(Datos);

    }

    //procesar datos

    const ingresarDatos = async () => {
        if (validarDatos()) {
            const optSegopt = optSeg.TOpciones_Menu;
            const _value = optSegopt.Guardar.value;
            let validar = validarMenuOpcion(_value);
            if (!validar) {
            await ingresarDatosSel();
            }
        }
    }

    const ingresarDatosSel = async () => {
        if (validarDatos()) { 
        const _data = llenarListaDatos();
        let resultado = '';
        let spinnerLabel = 'Ingresando datos';
        spinnerModalMostrar(true, spinnerLabel, 3)
        resultado = await ParametrosGenerales_GuardarAct_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;
        if ((_datos.Nivel1_Nombre.value == "") || (_datos.Nivel1_Nombre.value == '') || (_datos.Nivel1_Nombre.value.trim() == '') || (_datos.Nivel1_Nombre.value == null)) {
            Notificacion.error(`Error: Debe ingresar el dato ${_datos.Nivel1_Nombre.attributes.label} `);
            return false;
        }
        if ((_datos.Nivel2_Nombre.value == "") || (_datos.Nivel2_Nombre.value == '') || (_datos.Nivel2_Nombre.value.trim() == '') || (_datos.Nivel2_Nombre.value == null)) {
            Notificacion.error(`Error: Debe ingresar el dato ${_datos.Nivel2_Nombre.attributes.label} `);
            return false;
        }
        if ((_datos.Nivel3_Nombre.value == "") || (_datos.Nivel3_Nombre.value == '') || (_datos.Nivel3_Nombre.value.trim() == '') || (_datos.Nivel3_Nombre.value == null)) {
            Notificacion.error(`Error: Debe ingresar el dato ${_datos.Nivel3_Nombre.attributes.label} `);
            return false;
        }
        return true;
    }

    const handleCheckBox = (event) => {

        const name = event.target.name;
        const value = event.target.checked;
        let newAttributes = datos[name].attributes;

        const Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })

        if (name === "Habilita_GuardadoNube") {
            Datos.Cadena_Conexion_AzureBlobStorage.attributes.readOnly = !value;
            Datos.Nombre_Contenedor_AzureBlobStorage.attributes.readOnly = !value;
            Datos.URL_ServicioArchivos.attributes.readOnly = !value;
        }

        setDatos(Datos);
    }

    //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 onActionResultModal = (pValido) => {

        if (pValido) {
            let _OpcionNom = opcionValidarNombre;
            setShowModalSeguridad(false); setOpcionValidar(0); setOpcionValidarNombre('');
            const _optSegopt = optSeg.TOpciones_Menu;
            switch (_OpcionNom) {
                case _optSegopt.Guardar.value:
                    ingresarDatosSel();
                    break;
                default:
                    break;
            }
        }
    }


    return (
        <Fragment>
            <GeneralesInt
                botones={botones}
                Titulo={'Parámetros Generales'}
                Datos={datos}
                onChangeInput={onChangeInput}
                onChangeInputInt={onChangeInputInt}
                onChangeInputDecimal={onChangeInputDecimal}
                onChangeEditar={onChangeEditar}
                onFormatoInt={(onFormatoInt)}
                onFormato={onFormato}
                handleCheckBox={handleCheckBox}
            />
            <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(generales));
