﻿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, faPencilAlt, faTrash } from '@fortawesome/free-solid-svg-icons';
import AsociarCentroCostoInt from './asociarCentroCostoInt.jsx';
import { SiteRutas } from '../../../request/RutasConfig.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 ModalBusquedaTree from '../../../components/UI/modalBusqueda/modalBusquedaTree.jsx';
import { datosArbol, validaCorreo, validaTelefono, itemSelect } from '../../../components/Util/Util.jsx';

import ModalDetalle from '../../../components/UI/modalErrores/modalErrores.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 { CentroCosto_Lista_CCC_Request, Catalogo_Consulta_Request } from "../../../request/ServicioRequest.jsx";
import { CatalogoXCentroCosto_ListarAsociarCC_Request, CatalogoXCentroCosto_ModificarEstado_Request, CatalogoXCentroCosto_Eliminar_Request, Catalogo_AsociarCuenta_CentroCostoSP_Request } from "../../../request/MantenimientosRequest.jsx"
import ModalSeguridad from "../../Seguridad/ModalSeguridad.jsx";
import optSeg from '../../../components/Util/seg-menu-opciones.js';

import Swal from 'sweetalert2';
import { config } from '@fortawesome/fontawesome-svg-core';



const asociarCentroCosto = (props) => {
    let historyMenu = useHistory();
    const [token, setToken] = useSessionStorage('tokenCON', '');
    const [empresa, setEmpresa] = useSessionStorage('empresaCON', 0);
    const [empresaNombreCON, setEmpresaNombreCON] = useSessionStorage('empresaNombreCON', 'ND')
    const [usuario, setUsuario] = useSessionStorage('usuarioCON');
    const mounted = useRef();

    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"
        },
        {
            name: "btnEstadoCC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => cambiarEstado(),
            leyenda: "",
            iclase: faPencilAlt,
            tooltip: "Modificar Estado"
        },
        {
            name: "btnBorrarCC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => borrarDatos(),
            leyenda: "",
            iclase: faTrash,
            tooltip: "Borrar Centro Costo"
        }
    ]




    const listaCampos = {
        Cuenta: { value: '', attributes: { readOnly: true, focus: false, label: 'Cuenta', hidden: 'unset', Editando: false, maxLength: "255" } },
        Nombre: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: 'unset', Editando: false, maxLength: "255" } },
        CentroCosto: { value: "", attributes: { readOnly: false, focus: false, label: 'Centro Costo', hidden: 'unset', Editando: false, maxLength: "255" } },
        CentroCostoID: { value: "", attributes: { readOnly: false, focus: false, label: 'Tipo', hidden: 'unset', Editando: false, maxLength: "255" } },
        CentroCostoNombre: { value: "", attributes: { readOnly: true, focus: false, label: 'Nombre', hidden: 'unset', Editando: false, maxLength: "255" } },
        CtaContable: { value: 0, attributes: { readOnly: false, focus: false, label: 'Cuenta Contable', hidden: 'unset', Editando: false } },
        CtaContableNombre: { value: '', attributes: { readOnly: true, focus: false, label: 'Cuenta Contable', hidden: 'unset', Editando: false } },

    }

    const [datos, setDatos] = useState(listaCampos);

    //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 spinnerModalMostrar = (pSpinnerModal, pSpinnerLabel, pSpinnerTipo) => {
        setSpinnerModal(pSpinnerModal);
        setSpinnerLabel(pSpinnerLabel);
        setSpinnerTipo(pSpinnerTipo);
    }

    //Centro de costo modal
    const [selectModalTree, setSelectModalTree] = useState(false);
    const [listCuentasCont, setListCuentasCont] = useState([]);
    const [listCentroCosto, setListCentroCosto] = useState([]);
    const [listCatalogoXCC, setListCatalogoXCC] = useState([]);
    const [selectedCentroCosto, setSelectedCentroCosto] = useState(undefined);
    const [listCC, setListCC] = useState([]);
    const [esPadre, setEsPadre] = useState(false);
    const [esPadreCC, setESPadreCC] = useState(false);


    //tabla de aosicacion catalogo x Centro COsto

    const columnasTablaCCC = [{
        dataField: 'llave',
        text: 'llave',
        hidden: true,
        csvText: 'llave',
        sort: false
    }, {
        dataField: 'Centro_CostoCC',
        text: 'Centro Costo',
        csvText: 'Centro Costo',
        sort: true,
    }, {
        dataField: 'NombreCC',
        text: 'Nombre',
        csvText: 'Nombre',
        sort: true,
        align: 'left',
    }, {
        dataField: 'Estado',
        text: 'Estado',
        csvText: 'Estado',
        sort: true,
        align: 'center',
        formatter: (row, cell) => { return BuscaEstadoCCC(cell.Estado) },
    }, {
        dataField: 'Estado',
        text: 'Estado',
        hidden: true,
        csvText: 'Estado',
        sort: false,
        align: 'center',
    }]

    const [selectCC, setSelectCC ] = useState([]);
    const selectRowTabla = { mode: 'radio', clickToSelect: true, hideSelectColumn: true,selected: selectCC, onSelect: (row, isSelected) => onRowSelect(row, isSelected), bgColor: '#d73220' };
    const [rowSelected, setRowSelected] = useState({});
    const [borrando, setBorrando] = useState(false);
    //modal detalle
    const [selectModalEr, setSelectModalEr] = useState(undefined);
    const [listaErrores, setListaErrores] = useState([]);
    const columnasEr = [{ dataField: 'Cuenta_Contable', text: 'Cuenta', csvText: 'Cuenta', sort: true, hidden: false }, { dataField: 'Centro_CostoCC', text: 'Centro Costo', sort: true }, { dataField: 'NombreCuentaC', text: 'nombre', sort: true }];
    const selectRowEr = { mode: '', clickToSelect: false, hideSelectColumn: true, onSelect: () => { } };
    const [cellEditEr, setCellEditEr] = useState({ mode: '', blurToSave: false, autoSelectText: false });    

    useEffect(() => {

        if (!mounted.current) {
            const carga = async () => {
                await cargarDatos()
            }
            carga();
            mounted.current = true;
        }

    }, [])

    const cargarDatos = async () => {
        let spinnerLabel = 'Cargando datos...';
        let Datos = { ...datos };
        spinnerModalMostrar(true, spinnerLabel, 3)

        const _pCuenta = parseInt(props.match.params.id);
        const _EsPadre = (parseInt(props.match.params.padre) > 0);

        const _ListaCuentas = await carga_ListTreeC(_pCuenta);
        const _ListCentroCosto = await carga_ListTree();
        Datos.CtaContable.value = _ListaCuentas.ID;
        Datos.CtaContableNombre.value = _ListaCuentas.Cuenta;
        Datos.Cuenta.value = _ListaCuentas.Cuenta;

        setListCentroCosto(_ListCentroCosto);
        setListCuentasCont(_ListaCuentas);
        setEsPadre(_EsPadre);
        setDatos(Datos);

        if (!_EsPadre) {
            const _ListaCatalogoXCC = await carga_ListaCatalgoXCC(_ListaCuentas.ID);
            setListCatalogoXCC(_ListaCatalogoXCC);
        }

        //SEGURIDAD
        const _MenuNomb = await cargarMenuNombre(Config.Modulo, optSeg.TMenuSistema.CatalogodeCuentas.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 volverAtras = () => {
        historyMenu.push(SiteRutas.CatalogoCuentas);
    }


    const validarDatos = () => {
        const _datos = datos;
        if (_datos.CentroCostoNombre.value.trim().length == 0) {
            Notificacion.error('Error: Debe ingresar el dato: Centro Costo.');
            return false;
        }
        return true;
    }

    const validarDatosDel = () => {
        if (!rowSelected.ID) {
            Notificacion.error('Error: Debe selecionar un Centro Costo.');
            return false;
        }
        return true;
    }
    const validarDatosAct = () => {
        if (!rowSelected.ID) {
            Notificacion.error('Error: Debe selecionar un Centro Costo.');
            return false;
        }

        if(rowSelected.Estado == Config.c_x_ccInactivo ){
            Notificacion.error('Error: El centro de costo está INACTIVO, por tanto no se puede modificar.');
            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);
    }

    const onChangeInputCC = (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 } });
        Datos.CentroCostoNombre.value = "";
        Datos.CentroCostoID.value = "";
        setDatos(Datos);
    }

    const onBlurCC = async () => {
        let Datos = { ...datos };
        if ((Datos.CentroCosto.value.toString().trim().length > 0) && (Datos.CentroCostoNombre.value.toString().trim().length == 0)) {
            const _ListCC = listCC.filter(item => item.CentroCosto == Datos.CentroCosto.value);
            if (_ListCC.length > 0) {
                Datos.CentroCosto.value = _ListCC[0].CentroCosto;
                Datos.CentroCostoNombre.value = _ListCC[0].Nombre;
                Datos.CentroCostoID.value = _ListCC[0].ID;
                setDatos(Datos);
                //setListaHijos(listaHijos);
            } else {
                Datos.CentroCosto.value = '';
                setDatos(Datos);
                Notificacion.warning('Centro Costo no existe.');
            }
        }
    }
    //Procesos

    const mensajeAsociacion = (pMensaje) => {
        let _Mensaje = pMensaje;
        if ((esPadre) && (esPadreCC)) {
            _Mensaje = 'La cuenta y centro de costo digitados corresponden a un padre ¿Desea agregar las cuentas y centros de costo hijos?'
            return _Mensaje;
        }

        if ((esPadre)) {
            _Mensaje = 'La cuenta digitada corresponde a un padre ¿Desea agregar las cuentas hijas?'
            return _Mensaje;
        }

        if ((esPadreCC)) {
            _Mensaje = 'El centro de costo digitado corresponde a un padre ¿Desea agregar los centros de costo hijos?'
            return _Mensaje;
        }

        return _Mensaje;
    }

    const ingresarDatos = async () => {
        if (validarDatos()) {
            const optSegopt = optSeg.TOpciones_Menu;
            const _value = optSegopt.GuardarCentroCosto.value;
            let validar = validarMenuOpcion(_value);
            if (!validar) {
                await ingresarDatosSel();
            }
        }
    }

    const ingresarDatosSel = () => {
        let _Mensaje = '¿Está seguro de querer crear la nueva cuenta ?';
        _Mensaje = mensajeAsociacion(_Mensaje);
        let resultado = false;
        Swal.fire({
            title: 'Atención',
            html: `<h4>${_Mensaje}</h4>`,
            type: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10a599',
            cancelButtonColor: '#d33',
            confirmButtonText: '<h5><i class="fa fa-check fa-fw"></i> Sí</h5>',
            cancelButtonText: '<h5><i class="fa fa-remove fa-fw"></i> No</h5>',
            reverseButtons: true,
            allowOutsideClick: false,
        }).then((result) => {
            if (result.value) {
                resultado = true;
                ingresarDatosAsociar();
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                resultado = false;
            }
        });
        return resultado;
    }


    const ingresarDatosAsociar = async () => {
        if (validarDatos()) {
            let spinnerLabel = 'Ingresando datos';
            spinnerModalMostrar(true, spinnerLabel, 3)

            //let resultado = {Exitoso:true};
            let _Desplegar = (esPadre) ? false : (esPadreCC) ? false : true;
            const _CuentaID = datos.CtaContable.value;
            const _CentroC = datos.CentroCostoID.value;

            let resultado = await Catalogo_AsociarCuenta_CentroCostoSP_Request(token, empresa, _CuentaID, _CentroC);

            spinnerModalMostrar(false, '', 3)
            if (resultado.Exitoso == true) {
                Notificacion.success('Se almacenó la información con éxito.');
                if ((_Desplegar) &&(resultado.Datos.length > 0)){
                    setListaErrores(resultado.Datos);
                    setSelectModalEr(true);
                }
        
                if (!esPadre) {
                    const _ListaCatalogoXCC = await carga_ListaCatalgoXCC(listCuentasCont.ID);
                    setListCatalogoXCC(_ListaCatalogoXCC);
                }

            }
            else {
                Notificacion.error(`Error: ${resultado.Mensaje}`);
                spinnerModalMostrar(false, '', 3);
                setListaErrores([]);
            }

            let _Datos = {...datos};
            _Datos.CentroCosto.value = "";
            _Datos.CentroCostoNombre.value ="";
            setDatos(_Datos);
        }
    }


    const cambiarEstado = async () => {
        if (validarDatosAct()) {
            const optSegopt = optSeg.TOpciones_Menu;
            const _value = optSegopt.EstadoCentroCosto.value;
            let validar = validarMenuOpcion(_value);
            if (!validar) {
                await cambiarEstadoSel();
            }
        }

    }

    const cambiarEstadoSel = () => {
        let resultado = false;
        let _Mensaje = `El centro de costo está ${BuscaEstadoCCC(rowSelected.Estado)}. `;
        _Mensaje =  `${_Mensaje} ${((rowSelected.Estado == Config.c_x_ccBloqueado) ? "¿Desea activarlo?" : "¿Desea bloquearlo?")}` ;
        Swal.fire({
            title: 'Atención',
            html: `<h4>${_Mensaje}</h4>`,
            type: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10a599',
            cancelButtonColor: '#d33',
            confirmButtonText: '<h5><i class="fa fa-check fa-fw"></i> Sí</h5>',
            cancelButtonText: '<h5><i class="fa fa-remove fa-fw"></i> No</h5>',
            reverseButtons: true,
            allowOutsideClick: false,
        }).then((result) => {
            if (result.value) {
                resultado = true;
                cambiarEstadoAsociar();
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                resultado = false;
            }
        });
        return resultado;
    }


    const cambiarEstadoAsociar = async () => {
        if (validarDatosAct()) {
            let spinnerLabel = 'Actualizando datos';
            spinnerModalMostrar(true, spinnerLabel, 3)


            rowSelected.Estado = (rowSelected.Estado == Config.c_x_ccBloqueado) ? Config.c_x_ccActivo : Config.c_x_ccBloqueado;
            let resultado = await CatalogoXCentroCosto_ModificarEstado_Request(token, JSON.stringify(rowSelected));

            spinnerModalMostrar(false, '', 3)
            if (resultado.Exitoso == true) {
                Notificacion.success('Se actualizó la información con éxito.');
                setRowSelected({});
                if (!esPadre) {
                    const _ListaCatalogoXCC = await carga_ListaCatalgoXCC(listCuentasCont.ID);
                    setListCatalogoXCC(_ListaCatalogoXCC);
                }
            }
            else {
                Notificacion.error(`Error: ${resultado.Mensaje}`);
                spinnerModalMostrar(false, '', 3);
                setRowSelected({});
                if (!esPadre) {
                    const _ListaCatalogoXCC = await carga_ListaCatalgoXCC(listCuentasCont.ID);
                    setListCatalogoXCC(_ListaCatalogoXCC);
                }
            }
        }
    }


    const borrarDatos = async () => {
        if (validarDatosDel()) {
            const optSegopt = optSeg.TOpciones_Menu;
            const _value = optSegopt.EliminarCentroCosto.value;
            let validar = validarMenuOpcion(_value);
            if (!validar) {
                await borrarDatosSel();
            }
        }

    }

    const borrarDatosSel = () => {
        let resultado = false;
        Swal.fire({
            title: 'Atención',
            html: '<h4>¿Está seguro de querer eliminar el centro de costo.?</h4>',
            type: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10a599',
            cancelButtonColor: '#d33',
            confirmButtonText: '<h5><i class="fa fa-check fa-fw"></i> Sí</h5>',
            cancelButtonText: '<h5><i class="fa fa-remove fa-fw"></i> No</h5>',
            reverseButtons: true,
            allowOutsideClick: false,
        }).then((result) => {
            if (result.value) {
                resultado = true;
                borrarDatosAsociar();
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                resultado = false;
            }
        });
        return resultado;
    }


    const borrarDatosAsociar = async () => {
        if (validarDatosDel()) {
            let spinnerLabel = 'Eliminando datos';
            spinnerModalMostrar(true, spinnerLabel, 3)
            const _CuentaID = rowSelected.ID; datos.CtaContable.value;
            const _CentroC = rowSelected.Centro_Costo;

            let resultado = await CatalogoXCentroCosto_Eliminar_Request(token,empresa,_CuentaID, _CentroC);

            spinnerModalMostrar(false, '', 3)
            if (resultado.Exitoso == true) {
                Notificacion.success('Se eliminó la información con éxito.');
                setRowSelected({});
                if (!esPadre) {
                    const _ListaCatalogoXCC = await carga_ListaCatalgoXCC(listCuentasCont.ID);
                    setListCatalogoXCC(_ListaCatalogoXCC);
                }                
            }
            else {
                    Notificacion.error(`Error: ${resultado.Mensaje}`);
                    spinnerModalMostrar(false, '', 3);
                    setRowSelected({});
                    if (!esPadre) {
                        const _ListaCatalogoXCC = await carga_ListaCatalgoXCC(listCuentasCont.ID);
                        setListCatalogoXCC(_ListaCatalogoXCC);
                    }                                        
            }
        }
    }

    //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 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.GuardarCentroCosto.value:
                    ingresarDatosSel();
                    break;
                case _optSegopt.EstadoCentroCosto.value:
                    cambiarEstadoSel();
                    break;
                case _optSegopt.EliminarCentroCosto.value:
                    borrarDatosSel();
                    break;
                default:
                    break;
            }
        }
    }


    //modal centro costo


    const carga_ListTree = async () => {

        const response = await CentroCosto_Lista_CCC_Request(token, empresa);
        let _lista = [];
        if (response.Exitoso) {
            const listCuentas = response.Datos;
            const listCuentasCont = llenadoListaArbol(listCuentas);

            //const _DatosArbol = state.listCuentasCont;
            _lista = datosArbol(listCuentasCont);
            setListCC(listCuentas);
        }
        else {
            const _login = manageError(response, props, '');
            spinnerModalMostrar(false, '', 3);
            if (!_login) { volverAtras(); }
            return false;
        }

        return _lista;

    }
    const llenadoListaArbol = (pLista) => {
        let _Datos = [];
        const _Lista = pLista;
        _Datos.push({ "title": empresaNombreCON, "subtitle": "", "padre": -1, "value": 0 });

        _Lista.map(function (item, index) {
            _Datos.push({ "title": item.CentroCosto + " " + 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;
    }


    const carga_ListTreeC = async (pCuenta) => {

        const response = await Catalogo_Consulta_Request(token, empresa, pCuenta);
        let _lista = {};
        if (response.Exitoso) {
            _lista = response.Datos;
        }
        else {
            Notificacion.error(response.Mensaje);
            await volverAtras();
        }

        return _lista;

    }


    const carga_ListaCatalgoXCC = async (pCuenta) => {
        setSelectCC([]);
        const response = await CatalogoXCentroCosto_ListarAsociarCC_Request(token, empresa, pCuenta);        
        let _lista = [];
        if (response.Exitoso) {
            _lista = response.Datos;
        }
        else {
            Notificacion.warning('No tiene Centros de Costo Asociados.');
        }

        return _lista;
    }

    const handleModalTree = async () => {
        //spinnerModalMostrar(true, 'Cargando datos', 3);
        //const listCuentasCont = await carga_ListTree();
        //spinnerModalMostrar(false, '', 3);
        setSelectModalTree(true);
        //setListCuentasCont(listCuentasCont);

    }

    const onRowSelectBusquedaTree = (row) => {
        //setSelectedCuenta(row);
        setSelectedCentroCosto(row);

    }
    const cerrarModalTree = () => {
        setSelectModalTree(undefined);
    }


    const seleccionModalTree = async () => {
        if (!!selectedCentroCosto) {
            let Datos = { ...datos };

            Datos.CentroCostoID.value = selectedCentroCosto.node.value;

            let _listCC = listCC.filter(item => item.ID == selectedCentroCosto.node.value);
            if (_listCC.length > 0) {
                Datos.CentroCosto.value = _listCC[0].CentroCosto;
                Datos.CentroCostoNombre.value = _listCC[0].Nombre;
            }

            let _padre = { ...esPadreCC };
            _padre = (!selectedCentroCosto.node.children) ? false : true;
            setESPadreCC(_padre);

            setSelectedCentroCosto(undefined)
            setDatos(Datos);
            setSelectModalTree(undefined);
        }
        else {
            Notificacion.warning('Debe seleccionar un registro.');
        }
    }

    const onKeyPressCC = async (e) => {
        const _CC = e.target.value.toString().trim();
        if (e.charCode == 13) {
            if (_CC.length > 0) {
                const _ListCC = listCC.filter(item => item.CentroCosto == _CC);
                let Datos = { ...datos };
                if (_ListCC.length > 0) {
                    Datos.CentroCosto.value = _ListCC[0].CentroCosto;
                    Datos.CentroCostoNombre.value = _ListCC[0].Nombre;
                    Datos.CentroCostoID.value = _ListCC[0].ID;
                    setDatos(Datos);
                } else {
                    Datos.CentroCosto.value = '';
                    setDatos(Datos);
                    Notificacion.warning('Centro Costo no existe.');
                }
            }
        }
    }

    //Lista Catalogo Centro costo 
    const onRowSelect = (row, isSelected) => {
        setRowSelected(row);
        //if (isSelected){
            //setSelectCC(row.llave);
        //}else{
         //   setSelectCC([]);
        //}
    }
    const BuscaEstadoCCC = (pEstado) => {
        let _EstadoNomb = ""
        const _Estado = Config.ListaCatalogoXCentroCosto_Estado.filter(item => item.value == pEstado);
        if (_Estado.length > 0) {
            _EstadoNomb = _Estado[0].label;
        }
        return _EstadoNomb;
    }


//Modal detalle

//modal de errores

const cerrarModalEr = () => {
    setSelectModalEr(undefined);
    setListaErrores([]);
}

    return (
        <Fragment>
            <AsociarCentroCostoInt
                botones={botones}
                Titulo={'Asociar Centro de Costo'}
                Datos={datos}
                EsPadre={esPadre}
                onChangeInput={onChangeInput}
                handleModalTree={handleModalTree}
                onKeyPressCC={onKeyPressCC}
                onChangeInputCC={onChangeInputCC}
                onBlurCC={onBlurCC}
                listCatalogoXCC={listCatalogoXCC}
                columnasTablaCCC={columnasTablaCCC}
                selectRowTabla={selectRowTabla}
                borrando={borrando}

            />
            <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}
            />
            <ModalBusquedaTree
                selectedModal={selectModalTree}
                contentLabel={'selectedBusquedasTree'}
                label={'Centro Costo'}
                onSelectedRow={onRowSelectBusquedaTree}
                cerrarModal={cerrarModalTree}
                seleccionModal={seleccionModalTree}
                maxDepth={5}
                carga_ListTree={() => { }}
                listatree={listCentroCosto}
            />
            <ModalDetalle
                selectedModal={selectModalEr}
                contentLabel={'selectedListaErrores'}
                datos={listaErrores}
                id={'Campo2'}
                columnas={columnasEr}
                striped={false}
                hover={true}
                condensed={false}
                selectRow={selectRowEr}
                label={'Creación de Cuentas'}
                cellEdit={cellEditEr}
                cerrarModal={cerrarModalEr}
                verLHOC={false}
            />
        </Fragment>
    );
};
export default withRouter(memo(asociarCentroCosto))