﻿import React, { Fragment, memo, useEffect, useState } from 'react';
import { useHistory, withRouter } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faReply, faSave,faCheck } from '@fortawesome/free-solid-svg-icons';
import MantOficinasInt from './MantOficinasInt.jsx';
import { SiteRutas } from '../../../request/RutasConfig.jsx';
import { muestraArbolEmpleados, validarInt, validarDecimal, farmatearMontos } from '../../../components/Util/Util.jsx';
//Invocaciones datos
import { Oficina_Consulta_Request, Oficinas_Guardar_Request, Oficinas_Modificar_Request, Oficinas_PlzasDisponibles_Request, ParametrosGenerales_Consulta_Request } from "../../../request/MantenimientosRequest.jsx";
import { CentroCosto_Consulta_CXCC_Request, CentroCosto_Lista_CCC_Request, CentroCosto_Consulta_Request,SAPDimensiones_Listar_Request } from "../../../request/ServicioRequest.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 ModalBusqueda from '../../../components/UI/modalBusqueda/modalBusqueda.jsx';
import ModalSpinner from '../../../components/UI/modalSpinner/modalSpinner.jsx';
import ModalCentroCostoDimensiones  from '../../../components/UI/modalCentroCosto/modalCentroCostoDimensiones.jsx';

//Seguridad
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 MantOficinas(props) {
    let historyMenu = useHistory();
    const [token, setToken] = useSessionStorage('token', '');
    const [usuario, setUsuario] = useSessionStorage('usuario');
    const [codigo, setCodigo] = useState('');
    const [categoria, setCategoria] = useState([]);
    const [id, setId] = useState('');
    const [empresa, setEmpresa] = useSessionStorage('empresa');
    const [exportarSAP, setExportarSAP] = useSessionStorage('ExportarSAPRH');
    const [ubicacion, setUbicacion] = useLocalStorage('Ubicacion', null);
    const [selectModal, setSelectModal] = useState(false);
    const [listCentroCosto, setListCentroCosto] = useState([]);
    const [listCentroCostoFiltro, setListCentroCostoFiltro] = useState([]);
    const [selectedCentroCosto, setSelectedCentroCosto] = useState(undefined);
    const [cantPlazas, setCantPlazas] = useState(0);
    const [header, setHeader] = useState([{ title: 'Centro Costo', field: 'CentroCosto' }, { title: 'Nombre', field: 'Nombre' }, { title: 'id', field: 'ID', hidden: true },]);
    const [spinnerModal, setSpinnerModal] = useState(undefined);
    const [spinnerLabel, setSpinnerLabel] = useState('');
    const [spinnerTipo, setSpinnerTipo] = useState(1);
    const [rowsSelected,setRowsSelected]= useState(undefined);
    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: 'unset', Editando: false, maxLength: "20" } },
        Descripcion: { value: '', attributes: { readOnly: false, focus: false, label: 'Descripción', hidden: 'unset', maxLength: "30" } },
        CentroCosto: { value: 0, attributes: { readOnly: false, focus: false, label: 'Centro de Costo', hidden: 'unset', maxLength: "30", hidden: 'none' } },
        CantidadPlazas: { value: 0, attributes: { readOnly: true, focus: false, label: 'Cantidad de Plazas', hidden: 'unset', maxLength: "30" } },
        CantidadPlazasRest: { value: 0, attributes: { readOnly: true, focus: false, label: 'Disponibles', hidden: 'unset', maxLength: "30" } },
        CentroCostoNombre: { value: '', attributes: { readOnly: true, focus: false, label: 'Centro Costo', hidden: 'unset', Editando: false } },
        MsgError: { value: ' ', attributes: { readOnly: false, focus: false } },
        Control_Marcas: { value: false, attributes: { readOnly: false, focus: false, label: 'Control de Marcas', hidden: 'unset' } },
        CentroCosto2: { value: 0, attributes: { readOnly: false, focus: false } },
        CentroCosto3: { value: 0, attributes: { readOnly: false, focus: false } },
        CentroCosto4: { value: 0, attributes: { readOnly: false, focus: false } },
        CentroCosto5: { value: 0, attributes: { readOnly: false, focus: false } },
        CentroCostoNombre1: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoNombre2: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoNombre3: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoNombre4: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoNombre5: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoDecripcion1: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoDecripcion2: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoDecripcion3: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoDecripcion4: { value: "", attributes: { readOnly: true, focus: false } },
        CentroCostoDecripcion5: { value: "", attributes: { readOnly: true, focus: false } },         
    }

    const listaMod = {
        "Empresa": 0,
        "Area": 0,
        "Depto": 0,
        "Seccion": 0,
        "id": "",
        "Descripcion": "",
        "CentroCosto": 0,
        "CantidadPlazas": 0,
        "UsuarioModifica": "",
        "UsuarioFechaActualiza": "",
        "Control_Marcas": false,
        "CentroCosto2" :0,
        "CentroCosto3" :0,
        "CentroCosto4" :0,
        "CentroCosto5" :0,
                
    }
    const [datos, setDatos] = useState(listaCampos);
    const [listaModel, setListaModel] = useState(listaMod);

    const _Area = ubicacion.substring(ubicacion.search("A") + 1, ubicacion.search("D"));
    const _Depto = ubicacion.substring(ubicacion.search("D") + 1, ubicacion.search("S"));
    const _Seccion = ubicacion.substring(ubicacion.search("S") + 1, ubicacion.search("O"));
    const _Oficina = ubicacion.substring(ubicacion.search("O") + 1, ubicacion.length);

    //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 [listaDimensiones, setListaDimensiones] = useState([]);
    const botonesCC = [
        {
            name: "btnHomeCC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () =>cerrarModal(),
            leyenda: "",
            iclase: faReply,
            tooltip: "Volver"
        }
        , {
            name: "btnGuardarCC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => seleccionModal(),
            leyenda: "",
            iclase: faCheck,
            tooltip: "Guardar"
        }
    ];

    const spinnerModalMostrar = (pSpinnerModal, pSpinnerLabel, pSpinnerTipo) => {
        setSpinnerModal(pSpinnerModal);
        setSpinnerLabel(pSpinnerLabel);
        setSpinnerTipo(pSpinnerTipo);
    }
    const llenarListaDatos = () => {
        let _Campos = datos;
        let _Datos = listaModel;
        _Datos.Empresa = empresa;
        _Datos.Area = _Area;
        _Datos.Depto = _Depto;
        _Datos.Seccion = _Seccion;
        _Datos.id = _Campos.Codigo.value;
        _Datos.Descripcion = _Campos.Descripcion.value.trim();
        _Datos.CentroCosto = _Campos.CentroCosto.value;
        _Datos.CantidadPlazas = _Campos.CantidadPlazas.value;
        _Datos.UsuarioModifica = usuario;
        _Datos.Control_Marcas = _Campos.Control_Marcas.value;
        _Datos.CentroCosto2 = _Campos.CentroCosto2.value;
        _Datos.CentroCosto3 = _Campos.CentroCosto3.value;
        _Datos.CentroCosto4 = _Campos.CentroCosto4.value;
        _Datos.CentroCosto5 = _Campos.CentroCosto5.value;
        return _Datos;
    }

    const asociarDatos = async (pDatos, pGeneral,pExportarSAP) => {
        let _Campos = listaCampos;
        const _DefulatCC = {"Datos":{ CentroCosto: '', Nombre: '' }};
        let _CCValue = '';
        let centroCL2 = _DefulatCC;
        let centroCL3 = _DefulatCC;
        let centroCL4 = _DefulatCC;
        let centroCL5 = _DefulatCC;
        _Campos.Codigo.value = pDatos.id;
        _Campos.Descripcion.value = pDatos.Descripcion.trim();
        _Campos.CentroCosto.value = pDatos.CentroCosto;
        _Campos.CantidadPlazas.value = pDatos.CantidadPlazas;
        _Campos.CantidadPlazas.attributes.readOnly = pGeneral.ControlaCantidadPlazaOficinas;
        _Campos.CantidadPlazasRest.value = pDatos.CantidadPlazasRest;
        // _Campos.CantidadPlazasRest.attributes.readOnly = pGeneral.ControlaCantidadPlazaOficinas;
        _Campos.Control_Marcas.value = pDatos.Control_Marcas;

        const centroCL = await CentroCosto_Consulta_Request(token, empresa, pDatos.CentroCosto);
        if (centroCL.Exitoso) {
            //_Campos.CentroCostoNombre.value = `${centroCL.Datos.CentroCosto} - ${centroCL.Datos.Nombre}`;
            _CCValue =  centroCL.Datos.CentroCosto + ' [ ' + centroCL.Datos.Nombre + ' ] ';
            if (pExportarSAP) {

                if (pDatos.CentroCosto2 > 0) {
                     centroCL2 = await CentroCosto_Consulta_Request(token,empresa, pDatos.CentroCosto2);
                     if(!centroCL2.Exitoso > 0){ centroCL2 =_DefulatCC};
                }
                if (pDatos.CentroCosto3 > 0) {
                     centroCL3 = await CentroCosto_Consulta_Request(token,empresa, pDatos.CentroCosto3);
                     if(!centroCL3.Exitoso > 0){ centroCL3 =_DefulatCC};
                }
                if (pDatos.CentroCosto4 > 0) {
                     centroCL4 = await CentroCosto_Consulta_Request(token,empresa, pDatos.CentroCosto4);
                     if(!centroCL4.Exitoso > 0){ centroCL4 =_DefulatCC};
                }
                if (pDatos.CentroCosto5 > 0) {
                     centroCL5 = await CentroCosto_Consulta_Request(token,empresa, pDatos.CentroCosto5);
                     if(!centroCL5.Exitoso > 0){ centroCL5 =_DefulatCC};
                }
                _CCValue =  centroCL.Datos.CentroCosto;
                _CCValue = (centroCL2.Datos.CentroCosto.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + centroCL2.Datos.CentroCosto) : _CCValue;
                _CCValue = (centroCL3.Datos.CentroCosto.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + centroCL3.Datos.CentroCosto) : _CCValue;
                _CCValue = (centroCL4.Datos.CentroCosto.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + centroCL4.Datos.CentroCosto) : _CCValue;
                _CCValue = (centroCL5.Datos.CentroCosto.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + centroCL5.Datos.CentroCosto) : _CCValue;

            }
            _Campos.CentroCostoNombre.value = _CCValue;
            _Campos.CentroCosto2.value = pDatos.CentroCosto2;
            _Campos.CentroCosto3.value = pDatos.CentroCosto3;
            _Campos.CentroCosto4.value = pDatos.CentroCosto4;
            _Campos.CentroCosto5.value = pDatos.CentroCosto5;
            _Campos.CentroCostoNombre1.value = centroCL.Datos.CentroCosto ;
            _Campos.CentroCostoNombre2.value = centroCL2.Datos.CentroCosto;
            _Campos.CentroCostoNombre3.value = centroCL3.Datos.CentroCosto;
            _Campos.CentroCostoNombre4.value = centroCL4.Datos.CentroCosto;
            _Campos.CentroCostoNombre5.value = centroCL5.Datos.CentroCosto;
            _Campos.CentroCostoDecripcion1.value =  centroCL.Datos.Nombre ;
            _Campos.CentroCostoDecripcion2.value =  centroCL2.Datos.Nombre;
            _Campos.CentroCostoDecripcion3.value =  centroCL3.Datos.Nombre;
            _Campos.CentroCostoDecripcion4.value =  centroCL4.Datos.Nombre;
            _Campos.CentroCostoDecripcion5.value =  centroCL5.Datos.Nombre;

        }
        else {
            const _login = manageError(centroCL, props, '');
            spinnerModalMostrar(false, '', 3);
            if (!_login) { volverAtras(); }
            return false;
        }


        return _Campos;
    }




    const volverAtras = () => {
        historyMenu.push(SiteRutas.ListaOficinas);
    }

    const cargarDatos = async () => {
        let _id = (props.match.params.id == '0') ? '' : props.match.params.id;
        let spinnerLabel = 'Cargando datos...';
        spinnerModalMostrar(true, spinnerLabel, 3);
        const _General = await ParametrosGenerales_Consulta_Request(token, empresa);
        if (!_General.Exitoso) {
            const _login = manageError(_General, props, 'Cargando prámetros generales: ');
            spinnerModalMostrar(false, '', 3);
            if (!_login) { volverAtras(); }
            return false;
        }

        if (_id.length > 0) {
            const response = await Oficina_Consulta_Request(token, empresa, _Area, _Depto, _Seccion, _id);
            if (response.Exitoso) {
                const CantPlazas = await Oficinas_PlzasDisponibles_Request(token, empresa, _Area, _Depto, _Seccion, _id);
                if (CantPlazas.Exitoso) {
                    if (response.Datos.CantidadPlazas <= 0) {
                        response.Datos.CantidadPlazas = Math.abs(CantPlazas.Datos.CantidadPlazasRest);
                        response.Datos.CantidadPlazasRest = 0;
                    } else {
                        response.Datos.CantidadPlazasRest = response.Datos.CantidadPlazas - Math.abs(CantPlazas.Datos.CantidadPlazasRest);
                    }
                    let _datos = await asociarDatos(response.Datos, _General, exportarSAP);
                    _datos.CantidadPlazas.attributes.readOnly = _General.ControlaCantidadPlazaOficinas;
                    //_datos.CantidadPlazasRest.attributes.readOnly = _General.ControlaCantidadPlazaOficinas;
                    setDatos(_datos);
                    setCodigo(_id);
                    setCantPlazas(_datos.CantidadPlazas.value);
                } else {
                    const _login = manageError(CantPlazas, props, '');
                    spinnerModalMostrar(false, '', 3);
                    if (!_login) { volverAtras(); }
                    return false;
                }
            }
            else {
                const _login = manageError(response, props, '');
                spinnerModalMostrar(false, '', 3);
                if (!_login) { volverAtras(); }
                return false;
            }
        } else {
            let _listaCampos = listaCampos;
            _listaCampos.CantidadPlazas.attributes.readOnly = _General.ControlaCantidadPlazaOficinas;
            //_listaCampos.CantidadPlazasRest.attributes.readOnly = _General.ControlaCantidadPlazaOficinas;
            setDatos(_listaCampos);
            setCodigo(_id);
        }
        setId(_id);

        const _MenuNomb = await cargarMenuNombre(Config.Modulo, optSeg.TMenuSistema.Oficinas.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()
    }, [])

    //procesar datos
    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 Oficinas_Modificar_Request(token, JSON.stringify(_data));
            }
            else {
                resultado = await Oficinas_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())) {
                    Notificacion.error(`Error: ${resultado.Mensaje}`);
                    const _login = manageError(resultado, props,'Error: ');
                    if (_login) { return };
                }
                else {
                    Notificacion.success('Se almacenó la información con éxito');
                }
            }
            volverAtras();
        }
    }

    const validarDatos = () => {
        const _datos = datos;
        if (_datos.Descripcion.value.trim().length == 0) {
            Notificacion.error('Error: Debe ingresar el dato: Descripcion');
            return false;
        }
        if (_datos.CentroCostoNombre.value <= 0) {
            Notificacion.error('Error: Debe ingresar el dato: centro de costo');
            return false;
        }
        return true;
    }

    const onChangeInputInt = (e) => {

        const name = e.target.name;
        const value = e.target.value;

        const valido = validarInt(value);
        if (valido) {
            let newAttributes = datos[name].attributes;
            // newAttributes.focus = true; //Se asigna foco al componente
            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;// e.target.value;
        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);
        //state.Datos[name].attributes;
    }

    const onChangeEditarCantPlazas = async (e) => {
        const name = e.target.name;
        //const value = datos[name].value;// e.target.value;
        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;
        let 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';
        }

        let _id = (id == '') ? -1 : id;
        const CantPlazas = await Oficinas_PlzasDisponibles_Request(token, empresa, _Area, _Depto, _Seccion, _id);
        let _disponible = 0;
        if (CantPlazas.Exitoso) {
            _disponible = value - CantPlazas.Datos.CantidadPlazasRest;

        } else {
            const _login = manageError(CantPlazas, props, '');
            spinnerModalMostrar(false, '', 3);
            if (!_login) { volverAtras(); }
            return false;
        }
        if (_disponible < 0) {
            Notificacion.error('No se puede poner menos plazas de las disponibles actualmente');
            Datos.CantidadPlazas.value = cantPlazas;
        } else {
            Datos.CantidadPlazasRest.value = _disponible;
            setCantPlazas(value);
        }


        setDatos(Datos);
        //state.Datos[name].attributes;
    }

    const onFormatoInt = (valor) => {
        return valor;
    }
    const onChangeInput = (e) => {
        const name = e.target.name;
        const value = e.target.value;
        let newAttributes = datos[name].attributes;
        // newAttributes.focus = true; //Se asigna foco al componente
        const Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })
        setDatos(Datos);
    }

    const handleCheckBox = (event) => {

        const name = event.target.name;
        const value = event.target.checked;
        let newAttributes = datos[name].attributes;
        // newAttributes.focus = true; //Se asigna foco al componente
        const Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })
        setDatos(Datos);
    }

    //modal 

    const cerrarModal = () => {
        setRowsSelected(undefined);
        setSelectedCentroCosto(undefined);
        setSelectModal(undefined);
    }

    const seleccionModal = () => {
            let _Datos = datos;
            setSelectModal(undefined);
            _Datos = cargaCCDimensionesDatos(_Datos,listaDimensiones);
            setDatos(_Datos);
    }

    const onRowSelectBusqueda = (row) => {
        let _rowsSelected = [];
        _rowsSelected.push(row);
        setRowsSelected(_rowsSelected);
        setSelectedCentroCosto(row);
    }

    const handleChangeSearch = (event) => {

        let _listCentroCostoFiltro = [];
        _listCentroCostoFiltro = listCentroCosto;
        _listCentroCostoFiltro = _listCentroCostoFiltro.filter(function (item) {
            return item.CentroCosto.toLowerCase().search(
                event.target.value.toLowerCase()) !== -1;
        });
        if (_listCentroCostoFiltro.length == 0) {
            _listCentroCostoFiltro = listCentroCosto;

            _listCentroCostoFiltro = _listCentroCostoFiltro.filter(function (item) {
                return item.Nombre.toLowerCase().search(
                    event.target.value.toLowerCase()) !== -1;
            });
        }
        setListCentroCostoFiltro(_listCentroCostoFiltro);
    }
    const handleModal = async () => {

        let Datos = datos;
        const response = await SAPDimensiones_Listar_Request(token,empresa);
        let _listaDimensiones = {...listaDimensiones};
        _listaDimensiones = [
            {
                "Empresa": empresa,
                "Dimension_ID": 0,
                "Dimension_Nombre": "Único",
                "Dimension_Activa": true,
                "Centro_CostoStr": "", // pRegistro.Centro_CostoStr;
                "Centro_CostoNom": "", // pRegistro.Centro_CostoNom;
                "CentroCosto": -1, //pRegistro.CentroCosto
                "llave": "-1",
            }];
        if (response.Exitoso) {
            if (exportarSAP) {
                _listaDimensiones = response.Datos;
            }

        } else {
            if (exportarSAP){
                const _login = manageError(response, props, 'SAP Dimensiones:');
                spinnerModalMostrar(false, '', 3);
                spinnerModalMostrar(false, '', 3);
                if (_login) { return false; };
            }
        }
        _listaDimensiones = cargaCCDimensiones(Datos, _listaDimensiones);
        setListaDimensiones(_listaDimensiones);
        setSelectModal(true);       

    }
    //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;
            //Notificacion.error('No existe opción en la seguridad');
        }
        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.Nuevo.value:
                    ingresarDatosSel();
                    break;
                case _optSegopt.Editar.value:
                    ingresarDatosSel();
                    break;
                default:
                    break;
            }
        }
    }

     const onSelectedRow = async (row) => {
         if (row.Empleado !== "") {
             let rowsSelected = [];
             rowsSelected.push(row);
             setRowsSelected(rowsSelected);

         }
     }
//Modal dimensiones
const cargaCCDimensionesDatos = (pDatos, pLista) => {
    let _CCValue = "";
    pLista.map(function (item) {
        if (exportarSAP) {
            switch (item.Dimension_ID) {
                case Config.DimensionesSAP.Dim1:
                    pDatos.CentroCosto.value = item.CentroCosto;
                    pDatos.CentroCostoNombre1.value = item.Centro_CostoStr;
                    pDatos.CentroCostoDecripcion1.value = item.Centro_CostoNom;
                    _CCValue = item.Centro_CostoStr;
                    break;
                case Config.DimensionesSAP.Dim2:
                    pDatos.CentroCosto2.value = item.CentroCosto;
                    pDatos.CentroCostoNombre2.value = item.Centro_CostoStr;
                    pDatos.CentroCostoDecripcion2.value = item.Centro_CostoNom;
                    console.log(`Config.DimensionesSAP.Dim2: item.Centro_CostoStr : ${item.Centro_CostoStr}, _CCValue: ${_CCValue}`);
                    _CCValue = (item.Centro_CostoStr.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + item.Centro_CostoStr) : _CCValue;
                    console.log(`Config.DimensionesSAP.Dim2: despues  _CCValue: ${_CCValue}`);
                    break;
                case Config.DimensionesSAP.Dim3:
                    pDatos.CentroCosto3.value = item.CentroCosto;
                    pDatos.CentroCostoNombre3.value = item.Centro_CostoStr;
                    pDatos.CentroCostoDecripcion3.value = item.Centro_CostoNom;
                    _CCValue = (item.Centro_CostoStr.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + item.Centro_CostoStr) : _CCValue;
                    break;
                case Config.DimensionesSAP.Dim4:
                    pDatos.CentroCosto4.value = item.CentroCosto;
                    pDatos.CentroCostoNombre4.value = item.Centro_CostoStr ;
                    pDatos.CentroCostoDecripcion4.value = item.Centro_CostoNom;
                    _CCValue = (item.Centro_CostoStr.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + item.Centro_CostoStr) : _CCValue;
                    break;
                case Config.DimensionesSAP.Dim5:
                    pDatos.CentroCosto5.value = item.CentroCosto;
                    pDatos.CentroCostoNombre5.value = item.Centro_CostoStr;
                    pDatos.CentroCostoDecripcion5.value = item.Centro_CostoNom;
                    _CCValue = (item.Centro_CostoStr.length > 0) ? (_CCValue +  ((_CCValue.length > 0) ? "," : "" ) + item.Centro_CostoStr) : _CCValue;
                    break;
                default:
                    break;
            }
            
        } else {
            pDatos.CentroCosto.value = item.CentroCosto ;
            _CCValue = `${item.Centro_CostoStr} [ ${item.Centro_CostoNom} ]`;
            pDatos.CentroCostoNombre1.value = item.Centro_CostoStr;
            pDatos.CentroCostoDecripcion1.value = item.Centro_CostoNom ;
            pDatos.CentroCosto2.value =0;
            pDatos.CentroCosto3.value =0;
            pDatos.CentroCosto4.value =0;
            pDatos.CentroCosto5.value =0;
        }
    })
    pDatos.CentroCostoNombre.value = _CCValue;
    return pDatos
}
const cargaCCDimensiones = (pDatos, pLista) => {
    pLista.map(function (item) {
        if (exportarSAP) {
            switch (item.Dimension_ID) {
                case Config.DimensionesSAP.Dim1:
                    item.CentroCosto = pDatos.CentroCosto.value;
                    item.Centro_CostoStr = pDatos.CentroCostoNombre1.value;
                    item.Centro_CostoNom = pDatos.CentroCostoDecripcion1.value;
                    break;
                case Config.DimensionesSAP.Dim2:
                    item.CentroCosto = pDatos.CentroCosto2.value;
                    item.Centro_CostoStr = pDatos.CentroCostoNombre2.value;
                    item.Centro_CostoNom = pDatos.CentroCostoDecripcion2.value;
                    break;
                case Config.DimensionesSAP.Dim3:
                    item.CentroCosto = pDatos.CentroCosto3.value;
                    item.Centro_CostoStr = pDatos.CentroCostoNombre3.value;
                    item.Centro_CostoNom = pDatos.CentroCostoDecripcion3.value;
                    break;
                case Config.DimensionesSAP.Dim4:
                    item.CentroCosto = pDatos.CentroCosto4.value;
                    item.Centro_CostoStr = pDatos.CentroCostoNombre4.value;
                    item.Centro_CostoNom = pDatos.CentroCostoDecripcion4.value;
                    break;
                case Config.DimensionesSAP.Dim5:
                    item.CentroCosto = pDatos.CentroCosto5.value;
                    item.Centro_CostoStr = pDatos.CentroCostoNombre5.value;
                    item.Centro_CostoNom = pDatos.CentroCostoDecripcion5.value;
                    break;
                default:
                    break;
            }
        } else {
            item.CentroCosto = pDatos.CentroCosto.value;
            item.Centro_CostoStr = pDatos.CentroCostoNombre1.value;
            item.Centro_CostoNom = pDatos.CentroCostoDecripcion1.value;
        }

    })
    return pLista
}


    return (
        <Fragment>
            <MantOficinasInt
                botones={botones}
                Titulo={'Oficina'}
                Datos={datos}
                onChangeInputInt={onChangeInputInt}
                onChangeEditar={onChangeEditar}
                onFormatoInt={(onFormatoInt)}
                onChangeInput={onChangeInput}
                handleModal={handleModal}
                onChangeEditarCantPlazas={onChangeEditarCantPlazas}
                handleCheckBox={handleCheckBox}
            />
            <ModalCentroCostoDimensiones
            listaDimensiones ={listaDimensiones}
            cerrarModal ={cerrarModal}
            Titulo ={'Selección Centro Costos'}
            botones ={botonesCC}
            show={selectModal}
            CtaContable = {-1}
            ValidaCta ={false}
        />            
            {/*<ModalBusqueda
                selectedModal={selectModal}
                contentLabel={'selectedBusquedas'}
                listaFiltro={listCentroCostoFiltro}
                columnas={header}
                keyRow={'ID'}
                label={'Lista de Centros de Costos'}
                onSelectedRow={onRowSelectBusqueda}
                handleChangeSearch={handleChangeSearch}
                cerrarModal={cerrarModal}
                seleccionModal={seleccionModal}
                rowsSelected={rowsSelected}

    />*/}
            <ModalSpinner
                selectedModal={spinnerModal}
                contentLabel={'spinnerModalProgress'}
                label={spinnerLabel}
                tipoSpinner={spinnerTipo}
            />
            <ModalSeguridad
                //token={this.props.token}
                modalTitle={'Requiere Permisos'}
                menuId={menuId}
                opcionId={opcionValidar}
                show={showModalSeguridad}
                onActionResult={onActionResultModal}
                onHide={handleCerrarModal}
                {...props}
            />
        </Fragment>
    );
};
export default withRouter(memo(MantOficinas));