﻿import React, { Fragment, memo, useEffect, useRef, 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 MantEmpresasInt from './mantEmpresasInt.jsx';
import { SiteRutas, ImagenesRutas } from '../../../request/RutasConfig.jsx';
import { validaCorreo, validaTelefono, itemSelect, fechaPrimerDia, fechaUltimoDia, listaRangoNumeros, addMonths, datosArbol } from '../../../components/Util/Util.jsx';
//Invocaciones datos
import { Corporacion_Listar_Request, EmpresasImagen_SubirImagen_Request, EmpresasImagen_Consulta_Request, ParametroCadena_Listar_Request } from "../../../request/MantenimientosRequest.jsx"
import { Empresa_Consulta_Request, Empresa_Guardar_Request, Empresa_Modificar_Request, Empresa_ModificarImagen_Request, Empresa_Foto_Request } from "../../../request/SeguridadRequest.jsx"
import { CentroCosto_Lista_CXCC_Request, Catalogo_Lista_Request, Catalogo_Consulta_Request, CentroCosto_Consulta_CXCC_Request, CentroCostos_CentroDefault_Request,DatosGral_Consulta_Request } from '../../../request/ServicioRequest.jsx';
import { useSessionStorage } from '../../../components/Util/Hooks/useSessionStorage.jsx';
//utilitarios
import { Notificacion } from '../../../components/Util/Notificacion/Notificacion.jsx';
import ModalSpinner from '../../../components/UI/modalSpinner/modalSpinner.jsx';
import ModalBusqueda from '../../../components/UI/modalBusqueda/modalBusqueda.jsx';
import ModalBusquedaTree from '../../../components/UI/modalBusqueda/modalBusquedaTree.jsx';

//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';
import ModalImagen from '../../../components/UI/Imagen/modalImagen.jsx'


function mantEmpresas(props) {
    let historyMenu = useHistory();
    const [token, setToken] = useSessionStorage('tokenCON', '');
    const [usuario, setUsuario] = useSessionStorage('usuarioCON');
    const [empresaNombre, setEmpresaNombre] = useSessionStorage('');
    const mounted = useRef();
    const [codigo, setCodigo] = useState('');
    const [id, setId] = useState('');
    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 botonesFoto = [
        {
            name: " btnSelecFoto",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => handleClickSelFoto(),
            leyenda: "",
            iclase: "fa fa-image",
            tooltip: "Seleccionar foto"
        }
        , {
            name: "btnSubirFoto",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => handleSubirFoto(),
            leyenda: "",
            iclase: "fa fa-upload",
            tooltip: "Subir foto"
        },

    ]
    const _AnnoActual = new Date().getFullYear();
    const _ListaAnnos = listaRangoNumeros(Config.anoAntiguedad, _AnnoActual);
    const listaCampos = {
        Id: { value: 0, attributes: { readOnly: true, focus: false, label: 'Identificador', hidden: 'unset', Editando: false, maxLength: "20" } },
        Nombre: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: 'unset', Editando: false, maxLength: "120" } },
        Cedula_Juridica: { value: "", attributes: { readOnly: false, focus: false, label: 'Cédula Jurídica', hidden: 'unset', Editando: false, maxLength: "25" } },
        Telefono: { value: "", attributes: { readOnly: false, focus: false, label: 'Teléfono', hidden: 'unset', Editando: false, maxLength: "15" } },
        Direccion: { value: "", attributes: { readOnly: false, focus: false, label: 'Dirección', hidden: 'unset', Editando: false, maxLength: "255" } },
        EMail: { value: "", attributes: { readOnly: false, focus: false, label: 'Correo', hidden: 'unset', Editando: false, maxLength: "100" } },
        Comentario: { value: "", attributes: { readOnly: false, focus: false, label: 'Descripción', hidden: 'unset', Editando: false, maxLength: "255" } },
        Periodo: { value: new Date(), attributes: { readOnly: false, focus: false, label: 'Mes Inicio', hidden: 'unset', minDate: fechaPrimerDia(new Date(Config.anoAntiguedad, 0, 1)), maxDate: fechaUltimoDia(new Date(_AnnoActual, 11, 1)), ListaAnnos: _ListaAnnos, formatDate: Config.formatoMesAno } },
        InicioPeriodo: { value: new Date(), attributes: { readOnly: false, focus: false, label: 'Desde', hidden: 'unset', minDate: fechaPrimerDia(new Date(Config.anoAntiguedad, 0, 1)), maxDate: fechaUltimoDia(new Date(_AnnoActual, 11, 1)), ListaAnnos: _ListaAnnos, formatDate: Config.formatoMesAno } },
        FinPeriodo: { value: new Date(), attributes: { readOnly: false, focus: false, label: 'Hasta', hidden: 'unset', minDate: fechaPrimerDia(new Date(Config.anoAntiguedad, 0, 1)), maxDate: fechaUltimoDia(new Date(_AnnoActual, 11, 1)), ListaAnnos: _ListaAnnos, formatDate: Config.formatoMesAno } },
        Logo: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: 'unset', Editando: false, maxLength: "120" } },
        PerdGanan: { value: 0, attributes: { readOnly: false, focus: false, label: 'Pérdidas y Ganancias', hidden: 'unset', Editando: false, maxLength: "120" } },
        PerdGananCC: { value: 0, attributes: { readOnly: false, focus: false, label: 'Centro de Costo', hidden: 'unset', Editando: false, maxLength: "120" } },
        PerdGananNombre: { value: '', attributes: { readOnly: true, focus: false, label: 'Pérdidas y Ganancias', hidden: 'none', Editando: false, maxLength: "120" } },
        PerdGananCCNombre: { value: '', attributes: { readOnly: true, focus: false, label: 'Centro de Costo', hidden: 'none', Editando: false } },
        Corporacion_id: { value: 0, attributes: { readOnly: false, focus: false, label: 'Corporación', hidden: 'unset', Editando: false } },
        UtilizaCentroCosto: { value: false, attributes: { readOnly: false, focus: false, label: 'Utiliza funcionalidad de Centro de Costo', hidden: 'unset', Editando: false, maxLength: "120" } },
        Usuario_Modifica: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: 'unset', Editando: false, maxLength: "120" } },
        Nombre_Comercial: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre Comercial', hidden: 'unset', Editando: false, maxLength: "60" } },
        UbicacionImagen: { value: "", attributes: { readOnly: false, focus: false, label: 'Ubicacion imagen', hidden: 'unset', Editando: false, maxLength: "255" } },
        MsgError: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: 'unset', Editando: false, maxLength: "120" } },
        SAPServer: { value: "", attributes: { readOnly: false, focus: false, label: 'Servidor', hidden: 'unset', Editando: false, maxLength: "200" } },
        SAPCompany: { value: "", attributes: { readOnly: false, focus: false, label: 'Base Datos', hidden: 'unset', Editando: false, maxLength: "200" } },
        SAPUserName: { value: "", attributes: { readOnly: false, focus: false, label: 'Usuario', hidden: 'unset', Editando: false, maxLength: "200" } },
        SAPPassword: { value: "", attributes: { readOnly: false, focus: false, label: 'Password', hidden: 'unset', Editando: false, maxLength: "200" } },
        SAPTipoBD: { value: "", attributes: { readOnly: false, focus: false, label: 'Tipo Base Datos', hidden: 'unset', Editando: false } },
        Site: { value: "", attributes: { readOnly: false, focus: false, label: 'Site Empresa', hidden: 'unset', Editando: false, maxLength: "150" } },
    }

    const listaMod = {
        "Id": "",
        "Nombre": "",
        "Cedula_Juridica": "",
        "Telefono": "",
        "Direccion": "",
        "EMail": "",
        "Comentario": "",
        "Periodo": "",
        "InicioPeriodo": "",
        "Logo": "",
        "PerdGanan": "",
        "PerdGananCC": "",
        "Corporacion_id": "",
        "UtilizaCentroCosto": "",
        "Usuario_Modifica": "",
        "Nombre_Comercial": "",
        "Site" :"",
        "MsgError": "",
    }
    const listMdoPC = {
        "Emp_Id": "",
        "Cadena_Id": "",
        "SAPServer": "",
        "SAPCompany": "",
        "SAPTipoBD": "",
        "SAPUserName": "",
        "SAPPassword": "",
        "SAPPassEncrip": "",
        "MsgError": ""
    }
    const [datos, setDatos] = useState(listaCampos);
    const [listaModel, setListaModel] = useState(listaMod);
    const [listaModelPC, setListaModelPC] = useState(listMdoPC);
    const [listaCorporacion, setListaCorporacion] = useState([]);
    const [selectedOptionCorp, setSelectedOptionCorp] = useState(null);
    const [EmpresaOrig, setEmpresaOrig] = useState([]);


    //Seguridad
    const [usuarioS, setUsuarioS] = useSessionStorage('UsuarioSCON');
    const [menuId, setMenuId] = useState(0);
    const [menuOpciones, setMenuOpciones] = useState([]);
    const [showModalSeguridad, setShowModalSeguridad] = useState(false);
    const [opcionValidar, setOpcionValidar] = useState(0);
    const [opcionValidarNombre, setOpcionValidarNombre] = useState('');

    const [rowsSelected, setRowsSelected] = useState(undefined);
    const [selectModalTree, setSelectModalTree] = useState(false);
    const [listCuentasCont, setListCuentasCont] = useState([]);
    const [selectModal, setSelectModal] = useState(false);
    const [listCentroCosto, setListCentroCosto] = useState([]);
    const [listCentroCostoFiltro, setListCentroCostoFiltro] = useState([]);
    const [header, setHeader] = useState([{ title: 'Centro Costo', field: 'CentroCosto' }, { title: 'Nombre', field: 'Nombre' }, { title: 'id', field: 'ID', hidden: true },]);
    const [selectedCentroCosto, setSelectedCentroCosto] = useState(undefined);
    const [selectedCuenta, setSelectedCuenta] = useState(undefined)

    //foto empresa
    const [archivoFoto, setArchivoFoto] = useState(null);
    const [fotoSrc, setFotoSrc] = useState(ImagenesRutas.PicDefault);
    const [archivoImagen, setArchivoImagen] = useState(null);
    const [verBotonesFoto, setVerBotonesFoto] = useState({ display: 'none' });
    const [showModalImagen, setShowModalImagen] = useState(false);
    const DatosImagen = {
        "Consecutivo": 0,
        "Empresa": 0,
        //"Empleado":0,
        "Nombre": "",
        "Fecha_Ultima_Actualizacion": new Date()
    };
    const hiddenFileInput = React.createRef();

    //Datos parametros cadena
    const [selectedSAPTipoBD, setSelectedSAPTipoBD] = useState();

    const spinnerModalMostrar = (pSpinnerModal, pSpinnerLabel, pSpinnerTipo) => {
        setSpinnerModal(pSpinnerModal);
        setSpinnerLabel(pSpinnerLabel);
        setSpinnerTipo(pSpinnerTipo);
    }

    const llenarListaDatos = () => {
        let _Campos = datos;
        let _Datos = listaModel;

        _Datos.Id = _Campos.Id.value;
        _Datos.Nombre = _Campos.Nombre.value;
        _Datos.Cedula_Juridica = _Campos.Cedula_Juridica.value;
        _Datos.Telefono = _Campos.Telefono.value;
        _Datos.Direccion = _Campos.Direccion.value;
        _Datos.EMail = _Campos.EMail.value;
        _Datos.Comentario = _Campos.Comentario.value;
        _Datos.Periodo = _Campos.Periodo.value;
        _Datos.InicioPeriodo = _Campos.InicioPeriodo.value;
        _Datos.Logo = _Campos.Logo.value;
        _Datos.PerdGanan = _Campos.PerdGanan.value;
        _Datos.PerdGananCC = _Campos.PerdGananCC.value;
        _Datos.Corporacion_id = selectedOptionCorp.value;//_Campos.Corporacion_id.value;
        _Datos.UtilizaCentroCosto = _Campos.UtilizaCentroCosto.value;
        _Datos.Usuario_Modifica = usuario;
        _Datos.Nombre_Comercial = _Campos.Nombre_Comercial.value;
        _Datos.Site = _Campos.Site.value;
        _Datos.MsgError = _Campos.MsgError.value;

        return _Datos;
    }

    const llenarListaDatosPC = () => {
        let _Campos = datos;
        let _Datos = listaModelPC;

        _Datos.Emp_Id = _Campos.Id.value;
        _Datos.Cadena_Id = _Campos.Id.value;
        _Datos.SAPServer = _Campos.SAPServer.value;
        _Datos.SAPCompany = _Campos.SAPCompany.value;
        _Datos.SAPTipoBD = selectedSAPTipoBD.value;
        _Datos.SAPUserName = _Campos.SAPUserName.value;
        _Datos.SAPPassword = _Campos.SAPPassword.value;
        _Datos.SAPPassEncrip = "SI";
        return _Datos;
    }

    const asociarDatos = async (pDatos) => {
        let _Campos = listaCampos;
        _Campos.Id.value = pDatos.Id;
        _Campos.Nombre.value = pDatos.Nombre;
        _Campos.Cedula_Juridica.value = pDatos.Cedula_Juridica;
        _Campos.Telefono.value = pDatos.Telefono;
        _Campos.Direccion.value = pDatos.Direccion;
        _Campos.EMail.value = pDatos.EMail;
        _Campos.Comentario.value = pDatos.Comentario;
        _Campos.Periodo.value = new Date(pDatos.Periodo);
        _Campos.InicioPeriodo.value = new Date(pDatos.InicioPeriodo);
        _Campos.FinPeriodo.value = addMonths(new Date(pDatos.InicioPeriodo), 11);// ver como se calula en delphi
        _Campos.Logo.value = pDatos.Logo;
        _Campos.PerdGanan.value = pDatos.PerdGanan;
        _Campos.PerdGananCC.value = pDatos.PerdGananCC;
        _Campos.Corporacion_id.value = pDatos.Corporacion_id;
        _Campos.UtilizaCentroCosto.value = pDatos.UtilizaCentroCosto;
        _Campos.Usuario_Modifica.value = pDatos.Usuario_Modifica;
        _Campos.Nombre_Comercial.value = pDatos.Nombre_Comercial;
        _Campos.Site.value = pDatos.Site;
        _Campos.UbicacionImagen.value = pDatos.UbicacionImagen;
        const catalogoL = await Catalogo_Consulta_Request(token, _Campos.Id.value, _Campos.PerdGanan.value);
        if (catalogoL.Exitoso) {
            _Campos.PerdGananNombre.value = `${catalogoL.Datos.Cuenta} - ${catalogoL.Datos.Nombre}`;
        }
        else {
            Notificacion.error(catalogoL.Mensaje);
            volverAtras();
        }

        const centroCL = await CentroCosto_Consulta_CXCC_Request(token, _Campos.Id.value, _Campos.PerdGanan.value, _Campos.PerdGananCC.value);
        if (centroCL.Exitoso) {
            _Campos.PerdGananCCNombre.value = `${centroCL.Datos.CentroCosto} - ${centroCL.Datos.Nombre}`;
        }
        else {
            Notificacion.error(centroCL.Mensaje);
            volverAtras();
        }

        //esatado de controles
        _Campos.Corporacion_id.attributes.readOnly = true;
        _Campos.UtilizaCentroCosto.attributes.readOnly = true;
        _Campos.Periodo.attributes.readOnly = true;
        _Campos.InicioPeriodo.attributes.readOnly = true;
        _Campos.FinPeriodo.attributes.readOnly = true;
        _Campos.PerdGananNombre.attributes.hidden = 'unset';
        _Campos.PerdGananCCNombre.attributes.hidden = 'unset';

        return _Campos;
    }




    const volverAtras = () => {
        historyMenu.push(SiteRutas.Empresa);
    }

    const cargarDatos = async () => {
        let spinnerLabel = 'Cargando datos...';
        let _fotoSrc = ImagenesRutas.PicDefault;
        spinnerModalMostrar(true, spinnerLabel, 3)
        let _id = (props.match.params.id == '0') ? '' : props.match.params.id;
        const listaCorp = await cargarCorporacion();
        setListaCorporacion(listaCorp);
        const DatosGral = await DatosGenerales_Cargar(token);
        if (_id.length > 0) {
            const response = await Empresa_Consulta_Request(token, _id);
            if (response.Exitoso) {


                let _datos = await asociarDatos(response.Datos);
                _datos = await cargaParametrosCadena(token, _datos, _id);
                let _EmpresaImagen = DatosImagen;
                _EmpresaImagen = await EmpresasImagen_Consulta(token, _id);
                _datos = await cargaFotoEmpresa(token, _datos, _EmpresaImagen);
                _fotoSrc = _datos.UbicacionImagen.value;
                _datos = HabilitarCampos(_datos, DatosGral);
                setDatos(_datos);
                setCodigo(_id);
                setListaModel(response.Datos);
                setFotoSrc(_fotoSrc);

            }
            else {
                Notificacion.error(response.Mensaje);
                spinnerModalMostrar(false, '', 3)
                volverAtras();
            }

        } else {
            let _lstCampos = listaCampos;
            _lstCampos = HabilitarCampos(_lstCampos, DatosGral);
            setDatos(_lstCampos);
            setCodigo(_id);
            setSelectedSAPTipoBD(itemSelect(listaTipoBaseDatos[0].value, listaTipoBaseDatos));
        }
        const _VerBotfoto = { display: 'unset' };// (_id > 0) ? { display: 'unset' } : { display: 'none' };
        setVerBotonesFoto(_VerBotfoto);
        const _SelectedOptionCorp = (_id > 0 ? itemSelect(datos.Corporacion_id.value, listaCorp) : listaCorp[0]);
        setId(_id);
        setSelectedOptionCorp(_SelectedOptionCorp);

        const _MenuNomb = await cargarMenuNombre(Config.Modulo, optSeg.TMenuSistema.Corporacion.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)
    }

    const cargaFotoEmpresa = async (pToken, pEmpresa, pEmpresaImagen) => {
        let response = [];
        response = await Empresa_Foto_Request(pToken, pEmpresaImagen.Nombre);
        pEmpresa.UbicacionImagen.value = (response.Exitoso == true ? response.Mensaje : ImagenesRutas.PicDefault);
        return pEmpresa;
    }
    const cargaParametrosCadena = async (pToken, pEmpresa, pId) => {
        let response = [];
        response = await ParametroCadena_Listar_Request(pToken, pId);
        if (response.Exitoso) {
            //parametro Cadena
            pEmpresa.SAPServer.value = response.Datos.SAPServer;
            pEmpresa.SAPCompany.value = response.Datos.SAPCompany;
            pEmpresa.SAPUserName.value = response.Datos.SAPUserName;
            pEmpresa.SAPPassword.value = response.Datos.SAPPassword;
            setSelectedSAPTipoBD(itemSelect(response.Datos.SAPTipoBD, listaTipoBaseDatos));
            setListaModelPC(response.Datos);
        } else {
            Notificacion.error(`Carga Parámetro cadena: ${response.Mensaje}`);
        }
        return pEmpresa;
    }

    useEffect(() => {

        if (!mounted.current) {
            const carga = async () => {
                await cargarDatos()
            }
            carga();
            mounted.current = true;
        }

    }, [])


    //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()) {
            let spinnerLabel = id.length > 0 ? 'Actualizando datos' : 'Ingresando datos';
            spinnerModalMostrar(true, spinnerLabel, 3)
            const _data = llenarListaDatos();
            const _dataPC = llenarListaDatosPC();
            let resultado = '';

            //console.log(`ingresarDatosSel _data:${_data}`);
            if (codigo.length > 0) {
                resultado = await Empresa_Modificar_Request(token, JSON.stringify(_data), JSON.stringify(_dataPC));
            }
            else {
                resultado = await Empresa_Guardar_Request(token, JSON.stringify(_data),JSON.stringify(_dataPC));
            };
            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}`);
                }
                else {
                    Notificacion.success('Se almacenó la información con éxito.');
                }
            }
            volverAtras();
        }
    }

    const validarDatos = () => {
        const _datos = datos;
        if (_datos.Nombre.value.trim().length == 0) {
            Notificacion.error('Error: Debe ingresar el dato: Nombre.');
            return false;
        }
        if (_datos.Telefono.value.trim().length > 0) {
            if (!validaTelefono(_datos.Telefono.value.trim())) {
                Notificacion.error(`Error: Debe ingresar un número de teléfono válido.`);
                return false;
            }
        }
        if (_datos.EMail.value.trim().length > 0) {
            if (!validaCorreo(_datos.EMail.value.trim())) {
                Notificacion.error(`Error: Debe ingresar un correo electrónico válido.`);
                return false;
            }
        }

        return true;
    }


    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);
    }

    //Seguridad
    const cargarMenuOpciones = async (pModuloId, pUsuarioId, pMenuId) => {
        try {

            let listMO = await Obtener_MenuOpciones_Lista_Request(token, pModuloId, pUsuarioId, pMenuId);
            if (listMO.Exitoso === false) {
                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) {
                return null;
            }
            return listMON.Datos;
        }
        catch (err) {
            Notificacion.error(`Error: cargarMenuNombre.`);
        }
    }

    const cargarCorporacion = async () => {
        try {
            const listCop = await Corporacion_Listar_Request(token);
            if (listCop.Exitoso == false) {
                Notificacion.error(`Error: ${listCop.Mensaje}`);
                volverAtras();
            } else {
                let listaCombo = [];
                listaCombo = validarArreglo(listCop.Datos, 'Nombre', 'Id', 'Carga lista de corporaciones');
                return listaCombo;

            };
        }
        catch (err) {
            Notificacion.error(`Error: cargarCorpotacion.`);
            volverAtras();
        }
    }
    const validarArreglo = (arreglo, columnaTexto, columnaValor, descripcion) => {

        let arregloRetorno = [];

        if (Array.isArray(arreglo) && arreglo.length > 0) {
            if ((arreglo[0].MsgError === null || arreglo[0].MsgError === undefined ? '' : arreglo[0].MsgError) === '') {
                if (columnaTexto !== '') {
                    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}.`);
                    volverAtras();
                }
            }
        }

        return arregloRetorno;

    }

    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 onhandleSelectedCorporacion = (pSelect) => {
        setSelectedOptionCorp(pSelect);

    }

    const handleCheckBox = async (event) => {
        const name = event.target.name;
        const value = event.target.checked;
        let newAttributes = datos[name].attributes;
        // newAttributes.focus = true; //Se asigna foco al componente
        let Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } })

        setDatos(Datos);
    }

    const onhandleChangeDate = async (date, id) => {
        const name = id;
        const value = date;

        let newAttributes = datos[name].attributes;
        const _Datos = Object.assign({}, datos, { [name]: { value: value, attributes: newAttributes } });

        if (name == 'InicioPeriodo') {
            //console.log(`onhandleChangeDate:${name}`);
            _Datos.FinPeriodo.value = addMonths(new Date(value), 11);
        }
        if (name == 'FinPeriodo') {
            //console.log(`onhandleChangeDate:${name}`);
            _Datos.InicioPeriodo.value = addMonths(new Date(value), -11);
        }

        setDatos(_Datos);
    }
    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;
            }
        }
    }



    //modal cuentas y centro costo
    const handleModalTree = async () => {
        spinnerModalMostrar(true, 'Cargando datos', 3);
        const listCuentasCont = await carga_ListTree();
        spinnerModalMostrar(false, '', 3);
        setSelectModalTree(true);
        setListCuentasCont(listCuentasCont);

    }
    const handleModal = async () => {
        let Datos = datos;
        if (!!Datos.PerdGanan.value) {
            spinnerModalMostrar(true, 'Cargando datos', 3);
            const response = await CentroCosto_Lista_CXCC_Request(token, Datos.Id.value, Datos.PerdGanan.value);
            spinnerModalMostrar(false, '', 3);

            if (response.Exitoso) {
                const listCentroCosto = response.Datos;
                const _listCentroCostoFiltro = listCentroCosto;
                setSelectModal(true);
                setListCentroCosto(listCentroCosto);
                setListCentroCostoFiltro(_listCentroCostoFiltro);
            }
            else {
                Notificacion.error(response.Mensaje);
            }
        } else {
            Notificacion.warning('Debe seleccionar una cuenta contable.');
        }

    }
    const carga_ListTree = async () => {
        const _Dtos = datos;
        const response = await Catalogo_Lista_Request(token, _Dtos.Id.value, 0);
        let _lista = [];
        if (response.Exitoso) {
            const listCuentas = response.Datos;
            const listCuentasCont = llenadoListaArbol(listCuentas);
            //console.log(`listCuentasCont: ${JSON.stringify(listCuentasCont)}`);
            //const _DatosArbol = state.listCuentasCont;
            _lista = datosArbol(listCuentasCont);
            //console.log(`listCuentasCont: ${JSON.stringify(_lista)}`);            
        }
        else {
            Notificacion.error(`Catálogo de cuentas: ${response.Mensaje}, se deben crear cuentas.`);
            volverAtras();
        }

        return _lista;

    }
    const llenadoListaArbol = (pLista) => {
        let _Datos = [];
        const _Dtos = datos;
        const _Lista = pLista;
        _Datos.push({ "title": _Dtos.Nombre.value, "subtitle": "", "padre": -1, "value": 0 });

        _Lista.map(function (item, index) {
            _Datos.push({ "title": item.Cuenta + " " + item.Nombre, "subtitle": "", "padre": (item.Padres.length > 0 ? parseInt(item.Padres.substring(item.Padres.length - 6, item.Padres.length)) : 0), "value": item.ID });
        });

        return _Datos;
    }



    //procedimientos del modal

    const onRowSelectBusqueda = (row) => {
        let _rowsSelected = [];
        _rowsSelected.push(row);
        setRowsSelected(_rowsSelected);
        setSelectedCentroCosto(row);
    }

    const onRowSelectBusquedaTree = (row) => {
        setSelectedCuenta(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 cerrarModal = () => {
        setRowsSelected(undefined);
        setSelectedCentroCosto(undefined);
        setSelectModal(undefined);
    }

    const cerrarModalTree = () => {
        setSelectModalTree(undefined);
    }

    const seleccionModal = () => {
        if (!!selectedCentroCosto) {
            let Datos = datos;;
            setSelectModal(undefined);
            Datos.PerdGananCCNombre.value = selectedCentroCosto.CentroCosto + '-' + selectedCentroCosto.Nombre;
            Datos.PerdGananCC.value = selectedCentroCosto.ID;
            setSelectModalTree(undefined);
            setDatos(Datos);
        }
        else {
            Notificacion.warning('Debe seleccionar un registro.');
        }
    }

    const seleccionModalTree = async () => {
        if (!!selectedCuenta) {
            if (!selectedCuenta.node.children) {
                let Datos = datos;
                Datos.PerdGananNombre.value = selectedCuenta.node.title;
                Datos.PerdGanan.value = selectedCuenta.node.value;
                setSelectedCuenta(undefined)
                spinnerModalMostrar(true, 'Cargando datos', 3);
                const response = await CentroCostos_CentroDefault_Request(token, Datos.Id.value, Datos.PerdGanan.value);
                spinnerModalMostrar(false, '', 3);
                if (response.Exitoso) {
                    const _CC = response.Datos;
                    Datos.PerdGananCC.value = _CC.ID;
                    Datos.PerdGananCC.value = _CC.CentroCosto + '-' + _CC.Nombre;
                    setDatos(Datos);
                    setSelectModalTree(undefined);
                }
                else {
                    Notificacion.error(response.Mensaje);
                }
            }
            else {
                Notificacion.error('La cuenta selccionada es padre.');
                setSelectedCuenta(undefined);
                setSelectModalTree(undefined);
            }
        }
        else {
            Notificacion.warning('Debe seleccionar un registro.');
        }
    }
    //foto de empresa

    const handleClickSelFoto = (e) => {

        setShowModalImagen(true);

    }

    const handleSubirFoto = async () => {
        try {
            if (!archivoFoto) {
                Notificacion.error('Dede seleccionar una imagen.');
                return;
            }

            let spinnerLabel = 'Subiendo imagen...';
            spinnerModalMostrar(true, spinnerLabel, 3)

            //Notificacion.info('Subiendo foto');    
            let formData = new FormData();
            formData.append('pDatos', JSON.stringify(_datosImagen));
            formData.append('pFile', archivoImagen);
            let _datosImagen = DatosImagen;
            const _fotoSrc = fotoSrc;
            const _datos = datos;
            _datosImagen.Empresa = _datos.Id.value;
            //_datosImagen.Empleado = _datos.Id.value;
            let response = await EmpresasImagen_SubirImagen_Request(token, JSON.stringify(_datosImagen), _fotoSrc);
            spinnerModalMostrar(false, '', 3);
        }
        catch (err) {
            spinnerModalMostrar(false, '', 3);
            Notificacion.error(`Error: Subiendo imagen.`);
        }
    }


    const handleFile = (e) => {
        const content = e.target.result;
        setFotoSrc(content)
        // You can set content in state and show it in render.
    }

    const handleChangeFile = (file) => {
        setArchivoFoto(file);
        let fileData = new FileReader();
        fileData.onloadend = handleFile;
        fileData.readAsDataURL(file);

    }


    const cargaArchivoFoto = async (e) => {

        //Notificacion.info('Seleccionando Foto');
        e.preventDefault();

        if (e.target.files != undefined) {
            this, setArchivoImagen(e)
            let files = e.target.files, f = files[0];
            let self = this;
            const _ID = codigo;
            const exts = `${_ID}.jpeg`;//{ '.jpeg': 1 };
            let re = /\..+$/;
            let ext = f.name;//f.name.match(re);

            //if (exts[ext]) {
            if (exts === ext) {
                handleChangeFile(f);
                // this.setState({archivoFoto: f});
            } else {
                Notificacion.warning(`Dede seleccionar un archivo de imagen con el siguiente nombre y formato: ${exts}.`);
                e.target.value = null;
            }
        }
        //e.target.value = null;

    }

    const EmpresasImagen_Consulta = async (pToken, pEmpresa) => {
        let datos = [];
        const response = await EmpresasImagen_Consulta_Request(pToken, pEmpresa);
        if (response.Exitoso) {
            datos = response.Datos;
        } else {
            Notificacion.error(`EmpresasImagen_Consulta_Request ${response.Mensaje}`);
            //volverAtras();
        }
        return datos;
    };

    const DatosGenerales_Cargar= async(pToken)=>{
        let _datos =[] ;
        const response = await DatosGral_Consulta_Request(pToken);
        if(response.Exitoso){
            _datos = response.Datos;
        }else{
            Notificacion.error(`Datos Generales: ${response.Mensaje}`);
        }
        return _datos;
    }
    const HabilitarCampos = (pDatos, pDatosGral)=>{

        pDatos.SAPServer.attributes.hidden = (pDatosGral.ExportarSAP ?'unset': 'none');
        pDatos.SAPCompany.attributes.hidden = (pDatosGral.ExportarSAP ?'unset': 'none');
        pDatos.SAPTipoBD.attributes.hidden = (pDatosGral.ExportarSAP ?'unset': 'none');
        pDatos.SAPUserName.attributes.hidden = (pDatosGral.ExportarSAP ?'unset': 'none');
        pDatos.SAPPassword.attributes.hidden = (pDatosGral.ExportarSAP ?'unset': 'none');
        
        return pDatos;
    }
    //modal fotos 
    const nuevaImagen = async (canvas) => {
        setFotoSrc(canvas);
        setArchivoFoto(canvas);
        setShowModalImagen(false);
    }

    const handleCerrarModalImg = () => setShowModalImagen(false);
    const listaTipoBaseDatos = Config.listaTipoBaseDatos;

    //Datos parametros cadena
    const onhandleSelectedSAPTipoBD = (selSeccion) => { setSelectedSAPTipoBD(selSeccion); };



    return (
        <Fragment>
            <MantEmpresasInt
                botones={botones}

                Titulo={'Empresa'}
                Datos={datos}
                onChangeInput={onChangeInput}
                listaCorporacion={listaCorporacion}
                selectedOptionCorp={selectedOptionCorp}
                onhandleSelectedCorporacion={onhandleSelectedCorporacion}
                handleCheckBox={handleCheckBox}
                onhandleChangeDate={onhandleChangeDate}
                handleModalTree={handleModalTree}
                handleModal={handleModal}

                botonesFoto={botonesFoto}
                fotoSrc={fotoSrc}
                cargaArchivoFoto={cargaArchivoFoto}
                hiddenFileInput={hiddenFileInput}
                verBotonesFoto={verBotonesFoto}

                onhandleSelectedSAPTipoBD={onhandleSelectedSAPTipoBD}
                selectedSAPTipoBD={selectedSAPTipoBD}
                listaTipoBaseDatos={listaTipoBaseDatos}

            />
            <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}
            />
            <ModalBusqueda
                selectedModal={selectModal}
                contentLabel={'selectedBusquedas'}
                listaFiltro={listCentroCostoFiltro}
                columnas={header}
                keyRow={'ID'}
                label={'Lista de Centros de Costos Asociados'}
                onSelectedRow={onRowSelectBusqueda}
                handleChangeSearch={handleChangeSearch}
                cerrarModal={cerrarModal}
                seleccionModal={seleccionModal}
                rowsSelected={rowsSelected}

            />
            <ModalBusquedaTree
                selectedModal={selectModalTree}
                contentLabel={'selectedBusquedasTree'}
                label={'Catálogo'}
                onSelectedRow={onRowSelectBusquedaTree}
                cerrarModal={cerrarModalTree}
                seleccionModal={seleccionModalTree}
                maxDepth={5}
                carga_ListTree={carga_ListTree}
                listatree={listCuentasCont}
            />
            <ModalImagen
                modalTitle={'Logo de Empresa'}
                show={showModalImagen}
                onHide={handleCerrarModalImg}
                nuevaImagen={nuevaImagen}
            />
        </Fragment>
    );
};
export default withRouter(memo(mantEmpresas));