import React, { Fragment, memo, useEffect, useState, useRef } from 'react';
import { useHistory, withRouter } from 'react-router-dom';
import { useLocation } from 'react-router-dom';

import { farmatearFechaEstandar, farmatearMontos, fechaPrimerDia, fechaUltimoDia, listaRangoNumeros, validaCuenta, datosArbol, Round } from '../../components/Util/Util.jsx';
import Config from '../../components/Util/constantes.js';
import { SiteRutas, ImagenesRutas } from '../../request/RutasConfig.jsx';

import CargaAsientoExcelInt from './cargaAsientoExcelInt.jsx';
import BotonArriba from '../../components/UI/botonArriba/botonArriba.jsx';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCheck, faReply, faDownload, faSave, faCalculator, faClipboardList, faTimes, faFileExcel } from '@fortawesome/free-solid-svg-icons';

import { useSessionStorage } from '../../components/Util/Hooks/useSessionStorage.jsx';
import { Notificacion } from '../../components/Util/Notificacion/Notificacion.jsx';
import ModalSpinner from '../../components/UI/modalSpinner/modalSpinner.jsx';
import Swal from 'sweetalert2';

import ModalCargaAsiento from '../../components/UI/modalCargaAsientos/modalCargaAsientos.jsx';
import ModalBusquedaTree from '../../components/UI/modalBusqueda/modalBusquedaTree.jsx';
import ModalBusqueda from '../../components/UI/modalBusqueda/modalBusqueda.jsx';

import ModalBitacora from '../Asientos/Mantenimiento/modalBitacora.jsx';

import {
    TipoAsiento_Listar_Request, EncabezadoAsiento_ModificarDesdeExcel_Request, EncabezadoAsiento_ObtenerAsiento_Request,
    EncabezadoAsiento_ModificarUtilizado_Request, DetalleAsiento_Listar_Request, Contabilidad_ObtenerContadorAsiento_Request,
    EncabezadoAsiento_Guardar_Request, EncabezadoAsiento_Modificar_Request
} from '../../request/MantenimientosRequest.jsx';
import { Empresa_Consulta_Request } from "../../request/SeguridadRequest.jsx";
import { Obtener_MenuOpciones_Lista_Request, Obtener_MenuNombre_Request } from "../../request/MenuRequest.jsx";
import { Catalogo_Lista_Request, CentroCosto_ConsultaCCosto_Request, CentroCosto_Lista_CCC_Request, CentroCosto_Lista_CXCC_Request, CentroCosto_Lista_CXCCEmpresa_Request, CentroCostos_CentroDefault_Request } from "../../request/ServicioRequest.jsx";
import ModalSeguridad from "../Seguridad/ModalSeguridad.jsx";
import optSeg from '../../components/Util/seg-menu-opciones.js';
import moment from 'moment';

import * as XLSX from "xlsx";

import { Type } from 'react-bootstrap-table2-editor';
import ModalDescripcionCarga from '../../components/UI/modalDescripcionCarga/modalDescripcionCarga.jsx';

function cargaAsientoExcel(props) {

    let historyMenu = useHistory();
    const [empresa, setEmpresa] = useSessionStorage('empresaCON', 0);
    const [empresaNombre, setEmpresaNombre] = useSessionStorage('empresaNombreCON');
    const [datosEmpresa, setDatosEmpresa] = useState(null);
    const [token, setToken] = useSessionStorage('tokenCON', '');
    const [usuario, setUsuario] = useSessionStorage('usuarioCON');
    const _AnnoActual = new Date().getFullYear();
    const _ListaAnnos = listaRangoNumeros(Config.anoAntiguedad, _AnnoActual);

    const locationRouter = useLocation();

    const [Datos, setDatos] = useState({
        fecMesAno: { value: moment().toDate(), attributes: { readOnly: false, focus: false, label: 'Período', hidden: 'unset', minDate: fechaPrimerDia(new Date(Config.anoAntiguedad, 0, 1)), maxDate: fechaUltimoDia(new Date(_AnnoActual, 11, 1)), ListaAnnos: _ListaAnnos, formatDate: Config.formatoMesAno } },
        Descripcion: { value: "", attributes: { readOnly: true, focus: false, label: 'Descripción', hidden: "unset", maxLength: 510 } },
        Tipo: { value: "", attributes: { readOnly: true, focus: false, label: 'Tipo', hidden: "unset", } },
        fecMesAno: { value: moment().toDate(), attributes: { readOnly: true, focus: false, label: 'Período', hidden: 'unset', minDate: fechaPrimerDia(new Date(Config.anoAntiguedad, 0, 1)), maxDate: fechaUltimoDia(new Date(_AnnoActual, 11, 1)), ListaAnnos: _ListaAnnos, formatDate: Config.formatoMesAno } },
        Descripcion: { value: "", attributes: { readOnly: true, focus: false, label: 'Descripción', hidden: "unset", maxLength: 510 } },
        Tipo: { value: "", attributes: { readOnly: false, focus: false, label: 'Tipo', hidden: "unset", } },
        Numero: { value: "0", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        FechaAnio: { value: "0", attributes: { readOnly: false, focus: false, label: '\u00a0', hidden: "unset" } },
        FechaMes: { value: "", attributes: { readOnly: false, focus: false, label: 'Fecha', hidden: "unset" } },
        Monto: { value: 0, attributes: { readOnly: false, focus: false, label: 'Monto', hidden: "unset" } },
        NombrePl: { value: "", attributes: { readOnly: false, focus: false, label: 'Nombre', hidden: "unset" } },
        DescripcionPl: { value: "", attributes: { readOnly: false, focus: false, label: 'Descripción', hidden: "unset", maxLength: 255 } },
        TipoPl: { value: true, attributes: { readOnly: false, focus: false, label: 'Tipo', hidden: "unset" } },
        EstadoPl: { value: true, attributes: { readOnly: false, focus: false, label: 'Estado', hidden: "unset" } },
        DescripcionPlCk: { value: "", attributes: { readOnly: false, focus: false, label: 'Descripción', hidden: "unset" } },
        DescripcionPl2: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset", maxLength: 255 } },
        MontosPl: { value: true, attributes: { readOnly: false, focus: false, label: 'Montos', hidden: "unset" } },
        DocPorLineaPl: { value: true, attributes: { readOnly: false, focus: false, label: 'Doc. por línea', hidden: "unset" } },
        DescPorLineaPl: { value: true, attributes: { readOnly: false, focus: false, label: 'Desc. por línea', hidden: "unset" } },
        FechaPorLineaPl: { value: true, attributes: { readOnly: false, focus: false, label: 'Fecha por línea', hidden: "unset" } },
        AsientoBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Asiento', hidden: "unset" } },
        DigitadoPorBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Digitado Por', hidden: "unset" } },
        NombreDigitadoBi: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        AprobadoPorBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Aprobado Por', hidden: "unset" } },
        NombreAprobadoBi: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        AplicadoPorBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Aplicado Por', hidden: "unset" } },
        NombreAplicadoBi: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        AnuladoPorBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Anulado Por', hidden: "unset" } },
        NombreAnuladoBi: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        ModificadoPorBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Modificado Por', hidden: "unset" } },
        NombreModificadoBi: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        ReversadoPorBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Reversado Por', hidden: "unset" } },
        NombreReversadoBi: { value: "", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        UltimaActualizacionBi: { value: "", attributes: { readOnly: true, focus: false, label: 'Última Actualización', hidden: "unset" } },
    });

    const tablest = { width: '100%' };
    const cuentaright = { textAlign: 'right', width: '20%' };
    const cuentacenter = { textAlign: 'center', width: '80%' };
    const [spinnerModal, setSpinnerModal] = useState(undefined);
    const [spinnerLabel, setSpinnerLabel] = useState('');
    const [spinnerTipo, setSpinnerTipo] = useState(1);

    //Seguridad
    const [usuarioS, setUsuarioS] = useSessionStorage('UsuarioSCON');
    const [menuId, setMenuId] = useState(0);
    const [menuOpciones, setMenuOpciones] = useState([]);
    const [listaDatosExcel, setListaDatosExcel] = useState([]);
    const [showModalExcel, setShowModalExcel] = useState(false);
    const [showModalSeguridad, setShowModalSeguridad] = useState(false);
    const [opcionValidar, setOpcionValidar] = useState(0);
    const [opcionValidarNombre, setOpcionValidarNombre] = useState('');
    const [listCuentasCont, setListCuentasCont] = useState([]);
    const [BotonesComp, setBotonesComp] = useState([]);
    const [fAgregando, setfAgregando] = useState(false);
    const [fTipoCreacion, setfTipoCreacion] = useState(0);
    const [fModificando, setFModificando] = useState(false);
    const [fModificado, setFModificado] = useState(false);

    //datos del formulario
    const [selectedTipo, setSelectedTipo] = useState(null);
    const [listaTipo, setListaTipo] = useState([]);
    const [listaDatos, setListaDatos] = useState([]);
    const [listaCuentas, setListaCuentas] = useState([]);
    const [listCCosto, setListCCosto] = useState([]);
    const [listCXCC, setListCXCC] = useState([]);
    const [indexC, setIndexC] = useState(undefined);
    const [pColumn, setPColumn] = useState(undefined);
    const [selectedCuenta, setSelectedCuenta] = useState(undefined);
    const [selectModalTree, setSelectModalTree] = useState(false);
    const [selectedModalDesc, setselectedModalDesc] = useState(false);
    const [id, setId] = useState(0);
    const [indexCost, setIndexCost] = useState(undefined);
    const [listCentroCostoFiltro, setListCentroCostoFiltro] = useState([]);
    const [listCentroCosto, setListCentroCosto] = useState([]);
    const [selectModalBusqueda, setSelectModalBusqueda] = useState(false);
    const [selectedCentroCosto, setSelectedCentroCosto] = useState(undefined);
    const [rowsSelected, setRowSelected] = useState(undefined);
    const [fEstadoAsiento, setFEstadoAsiento] = useState(Config.eaDigitado);
    const [selectModalBi, setSelectModalBi] = useState(false);
    const [validarBalanceado, setValidarBalanceado] = useState(false);

    const [asiento, setAsiento] = useState(undefined);

    const [totalDebe, setTotalDebe] = useState(0);
    const [totalHaber, setTotalHaber] = useState(0);

    const tipoCreacion = [{ id: 1, value: 'Normal' }, { id: 2, value: 'De Plantilla' }, { id: 3, value: 'De Excel' }];
    const [selectedTipoCreacion, setSelectedTipoCreacion] = useState(tipoCreacion[0]);
    const hiddenFileInput = React.useRef(null);

    const Header = [
        { title: 'Centro Costo', field: 'CentroCosto' },
        { title: 'Nombre', field: 'Nombre' },
        { title: 'id', field: 'ID', hidden: true },
    ];

    const botones = [
        {
            name: "btnHomeC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => volverAtras(true),
            leyenda: "",
            iclase: faReply,
            tooltip: "Volver"
        },
        {
            name: "btnUtilizar",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => handleAceptar(listaDatos),
            leyenda: "",
            iclase: faCheck,
            tooltip: "Utilizar"
        },
        {
            name: "btnImportarExcel",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: (e) => mostrarModalDesc(),
            leyenda: "",
            iclase: faFileExcel,
            tooltip: "Cargar Asiento"
        },
    ];

    const mostrarModalDesc= () => {
        setselectedModalDesc(true);
    }

    const columnas = [
        { dataField: 'Linea', text: '', csvText: '', sort: false, footer: '', hidden: true },
        {
            dataField: 'CuentaStr', text: 'Cuenta', csvText: 'Cuenta', sort: true, footer: '',
            editable: true, validator: (newValue, row, column) => {
                const valido = validaCuentaTabla(newValue, row, column);
                return valido;
            },
            formatter: (e, column, columnIndex, row, rowIndex) => {
                const _llaveCta = column.Linea;
                const campo =
                    <table style={tablest}>
                        <tbody>
                            <tr style={tablest}>
                                <td id={_llaveCta} style={cuentacenter}>{column.CuentaStr}</td>
                                <td style={cuentaright} > <a type="button" onClick={() => { handleCuentaModal(column, columnIndex, row, rowIndex) }} ><i className="fa fa-search"></i></a></td>
                            </tr>
                        </tbody>
                    </table>
                return campo;
            }
        },
        { dataField: 'NombreCuenta', text: 'Nombre', sort: true, editable: true, footer: '', align: 'center', headerAlign: 'center' },
        { dataField: 'Centro_Costo', text: 'Centro Costo', hidden: true, csvExport: false, sort: true, editable: false, footer: '', },
        {
            dataField: 'Centro_CostoStr', text: 'Centro Costo', csvExport: false, sort: true, editable: true, footer: '',
            validator: (newValue, row, column) => {
                return onValidarCCosto(newValue, row, column);
            },
            formatter: (e, column, columnIndex, row, rowIndex) => {
                const _llave = column.Linea + 'B';
                const campo =
                    <table style={tablest}>
                        <tbody>
                            <tr style={tablest}>
                                <td id={_llave} style={cuentacenter} > {column.Centro_CostoStr} </td>
                                <td style={cuentaright} > <a type="button" onClick={() => { handleModal(column, columnIndex) }} ><i className="fa fa-search"></i></a></td>
                            </tr>
                        </tbody>
                    </table>
                return campo;
            }

        },
        {
            dataField: 'Fecha', text: 'Fecha', sort: true, align: 'center', headerAlign: 'center', editable: true, footer: '',
            formatter: (row, cell) => { return cell.Fecha !== '' ? farmatearFechaEstandar(cell.Fecha) : '' },
            editor: {
                type: Type.DATE
            }
        },
        {
            dataField: 'Documento', text: 'Documento', csvText: 'Documento', editable: true, sort: true, align: 'left', headerAlign: 'center', footer: '',
            editor: { type: Type.TEXTAREA },
            validator: (newValue, row, column) => {
                if (newValue.length > 255) {
                    return {
                        valid: false,
                        message: '¡No puede superar los 255 caracteres!'
                    }
                } else {
                    return true;
                }
            },
        },
        {
            dataField: 'Referencia', text: 'Descripción', csvText: 'Referencia', sort: true, align: 'left',
            headerAlign: 'left', editable: true, editor: { type: Type.TEXTAREA },
            validator: (newValue, row, column) => {
                if (newValue.length > 510) {
                    return {
                        valid: false,
                        message: '¡No puede superar los 510 caracteres!'
                    }
                } else {
                    return true;
                }
            },
        },
        {
            dataField: 'Debe', text: 'Debe', csvText: 'Debe', hidden: false, editable: true, align: 'center', headerAlign: 'center',
            formatter: (row, cell) => farmatearMontos(cell.Debe) ,type: 'number',
            validator: (newValue, row, column) => {
                return validaDebe(newValue, row);
            },
        },
        {
            dataField: 'Haber', text: 'Haber', csvText: 'Haber', hidden: false, editable: true, align: 'center', headerAlign: 'center',
            formatter: (row, cell) => farmatearMontos(cell.Haber),type: 'number',
            validator: (newValue, row, column) => {
                return validaHaber(newValue, row);
            },
        },
        { dataField: 'MsgError', text: 'Error', csvText: 'Error', editable: false, sort: false, footer: '', hidden: false, csvExport: true }
    ];

    const columnasExcel = [/*
        {
            dataField: 'CuentaStr', text: 'Cuenta', csvText: 'Cuenta', sort: true, footer: '',
            editable: true, validator: (newValue, row, column) => {
                const valido = validaCuentaTabla(newValue, row, column);
                return valido;
            },
            formatter: (e, column, columnIndex, row, rowIndex) => {
                const _llaveCta = column.Linea;
                const campo =
                    <table style={tablest}>
                        <tbody>
                            <tr style={tablest}>
                                <td id={_llaveCta} style={cuentacenter}>{column.CuentaStr}</td>
                                <td style={cuentaright} > <a className='hoverBtn' type="button" onClick={() => { handleCuentaModal(column, columnIndex, row, rowIndex) }} ><i className="fa fa-search"></i></a></td>
                            </tr>
                        </tbody>
                    </table>
                return campo;
            }
        },
        {
            dataField: 'Centro_CostoStr', text: 'Centro Costo', csvExport: false, sort: true, editable: true, footer: '',
            validator: (newValue, row, column) => {
                return onValidarCCosto(newValue, row, column);
            },
            formatter: (e, column, columnIndex, row, rowIndex) => {
                const _llave = column.Linea + 'B';
                const campo =
                    <table style={tablest}>
                        <tbody>
                            <tr style={tablest}>
                                <td id={_llave} style={cuentacenter} > {column.Centro_CostoStr} </td>
                                <td style={cuentaright} > <a className='hoverBtn' type="button" onClick={() => { handleModal(column, columnIndex) }} ><i className="fa fa-search"></i></a></td>
                            </tr>
                        </tbody>
                    </table>
                return campo;
            }

        },
        {
            dataField: 'NombreCuentaCC', text: 'Nombre de Cuenta', csvText: 'Nombre de Cuenta', sort: true, footer: '',
            editable: false,
        },
        {
            dataField: 'Fecha', text: 'Fecha', sort: true, align: 'center', headerAlign: 'center', editable: true, footer: '',
            formatter: (row, cell) => { return cell.Fecha !== '' ? farmatearFechaEstandar(cell.Fecha) : '' },
            editor: {
                type: Type.DATE
            }
        },
        {
            dataField: 'Documento', text: 'Documento', csvText: 'Documento', editable: true, sort: true, align: 'left', headerAlign: 'center', footer: '',
            editor: { type: Type.TEXTAREA },
            validator: (newValue, row, column) => {
                if (newValue.length > 255) {
                    return {
                        valid: false,
                        message: '¡No puede superar los 255 caracteres!'
                    }
                } else {
                    return true;
                }
            },
        },
        {
            dataField: 'Referencia', text: 'Descripción', csvText: 'Referencia', sort: true, align: 'left',
            headerAlign: 'left', editable: true, editor: { type: Type.TEXTAREA },
            validator: (newValue, row, column) => {
                if (newValue.length > 510) {
                    return {
                        valid: false,
                        message: '¡No puede superar los 510 caracteres!'
                    }
                } else {
                    return true;
                }
            },
            footerStyle: (column, colIndex) => {
                if (totalDebe - totalHaber < 0) {
                    return { Color: '#ff0000', textAlign: 'right' }
                } else {
                    return { Color: '#000000', textAlign: 'right' }
                }
            },
            footer: farmatearMontos(Round(totalDebe - totalHaber, 2))
        },
        {
            dataField: 'Debe', text: 'Debe', csvText: 'Debe',
            hidden: false, editable: true, align: 'right',
            formatter: (row, cell) => farmatearMontos(cell.Debe),
            validator: (newValue, row, column) => {
                return validaDebe(newValue, row);
            },
            footer: (columnData, column, columnIndex) => {
                const total = columnData.reduce((acc, item) => acc + item, 0);
                setTotalDebe(total);
                return farmatearMontos(Round(total, 2));
            }
            , type: 'number',
            footerStyle: { Color: '#ff0000', textAlign: 'right' }
        },
        {
            dataField: 'Haber', text: 'Haber', csvText: 'Haber', hidden: false, editable: true, align: 'right',
            formatter: (row, cell) => farmatearMontos(cell.Haber), type: 'number',
            footer: (columnData, column, columnIndex) => {
                const total = columnData.reduce((acc, item) => acc + item, 0);
                setTotalHaber(total);
                return farmatearMontos(Round(total, 2));
            },
            footerStyle: { Color: '#ff0000', textAlign: 'right' },
            validator: (newValue, row, column) => {
                return validaHaber(newValue, row);
            },
        },
    */];

    const botonesExcel = [
        {
            name: "btnGuardarC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => guardarDatos(),
            leyenda: "",
            iclase: faSave,
            tooltip: "Guardar"
        },
        {
            name: "btnGuardarC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => abrirCalculadora(),
            leyenda: "",
            iclase: faCalculator,
            tooltip: "Calculadora"
        },
        {
            name: "btnGuardarC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => handleBitacora(),
            leyenda: "",
            iclase: faClipboardList,
            tooltip: "Bitácora"
        },
        {
            name: "btnGuardarC",
            clase: "btn btn-sm pull-right flipInX animated",
            evento: () => handleCerrarModalExcel(),
            leyenda: "",
            iclase: faTimes,
            tooltip: "Salir"
        }
    ];


    const handleBitacora = async () => {

        if (id === 0) {
            Notificacion.error('No hay bitácora para este registro.');
        } else {

            let _Datos = { ...Datos };

            _Datos.AsientoBi.value = `${selectedTipo.label} - ${asiento.Numero.toString().padStart(5, '0')}`;
            _Datos.DigitadoPorBi.value = asiento.DigitadoX;
            _Datos.NombreDigitadoBi.value = asiento.DigitadoXNombre;
            _Datos.AprobadoPorBi.value = asiento.AprobadoX;
            _Datos.NombreAprobadoBi.value = asiento.AprobadoXNombre;
            _Datos.AplicadoPorBi.value = asiento.AplicadoX;
            _Datos.AplicadoPorBi.value = asiento.AplicadoXNombre;
            _Datos.AnuladoPorBi.value = asiento.AnuladoX;
            _Datos.NombreAnuladoBi.value = asiento.AnuladoXNombre;
            _Datos.ModificadoPorBi.value = asiento.Modificado;
            _Datos.NombreModificadoBi.value = asiento.ModificadoNombre;
            _Datos.ReversadoPorBi.value = asiento.Reversado;
            _Datos.UltimaActualizacionBi.value = asiento.Fecha_Actualizacion;

            setDatos(_Datos);
            setSelectModalBi(true);

        }
    };

    const hayErroresLinea = (verifBalanceado = false) => {

        let fila = 0;
        let Error = '';
        let i = 0;
        let Linea = '';
        let Row = 0;
        let _listaDatos = [].concat(listaDatos.filter(x => x.Debe > 0 || x.Haber > 0));

        if (cambioDeFecha()) {
            Error = 'No se puede guardar un asiento en una fecha anterior al mes en curso';
        }

        if (Datos.Descripcion.value.trim() === '' && Error === '') {
            Error = 'No se puede guardar el asiento ya que necesita una descripción';
        }

        while (i < _listaDatos.length && Error === '') {

            if ((_listaDatos[i].CuentaStr !== '') || ((_listaDatos[i].Debe + _listaDatos[i].Haber) > 0)) {
                Linea = 'La línea ' + (i + 1).toString();

                if (_listaDatos[i].CuentaStr === '')
                    Error = Linea + ' tiene montos asociados, pero ninguna cuenta válida que referenciar.';
                else if (_listaDatos[i].Centro_CostoStr === '')
                    Error = Linea + ' tiene montos asociados, pero ningún centro de costo válido que referenciar.';

                if (Error !== '')
                    Row = i;
            }

            i++;

        }

        if (verifBalanceado) {
            if (Error === '' && (SumeMontos(true) - SumeMontos(false)) !== 0)
                Error = 'El asiento no se encuentra balanceado.';
        }

        return Error;

    };

    const SumeMontos = (Debe) => {

        let Result = parseFloat(0);

        for (let i in listaDatos) {
            if (Debe) {
                Result = Result + parseFloat(listaDatos[i].Debe);
            }
            else {
                Result = Result + parseFloat(listaDatos[i].Haber);
            }
        }
        return Result;
    };

    const guardarDatos = async () => {

        const optSegopt = optSeg.TOpciones_Menu;
        const _value = (id > 0) ? optSegopt.Editar.value : optSegopt.Nuevo.value;

        const hayErrores = hayErroresLinea(validarBalanceado);
        if (hayErrores.length > 0) {
            Notificacion.error(hayErrores);
        } else {

            let validar = validarMenuOpcion(_value);
            if (!validar) {
                if (id === 0) {
                    await guardarAsiento(true);
                } else {
                    await modificarAsiento();
                }
            }
        }

    };

    const modificarAsiento = async () => {

        const tipoCreacion = selectedTipoCreacion.value;
        let NomCont = '';
        let Numero = '';

        try {

            spinnerModalMostrar(true, 'Modificando asiento');

            if (!cambioDeFecha()) {

                setFModificado(true);

                const fecha = moment(Datos.fecMesAno.value).format("YYYY/MM/DD");
                const fechaAsiento = moment(asiento.Fecha).toDate();

                if (moment(Datos.fecMesAno.value).format("YYYY/MM/DD") !== moment(fechaAsiento).format("YYYY/MM/DD")) {
                    const _Datos = await siguienteContador()
                    Numero = _Datos.Numero.value;
                }
                else {
                    Numero = asiento.Numero;
                }

                const Descripcion = Datos.Descripcion.value
                //estado digitado
                const estado = validarBalanceado ? Config.eaAprobado : Config.eaDigitado;
                const totalDebitos = SumeMontos(true);
                const totalCreditos = SumeMontos(false);
                const tipo = selectedTipo.value;

                const _datos = {
                    Fecha: fecha, Numero: Numero, Descripcion: Descripcion, TipoCreacion: tipoCreacion,
                    Debitos: totalDebitos, Creditos: totalCreditos, DigitadoX: usuario, Estado: estado,
                    Usuario_Modifica: usuario, Utilizado: false, id: asiento.id, Tipo: tipo, empresa: empresa,
                    AprobadoX: Config.Modulo
                };

                let _lista = listaDatos.filter(x => parseInt(x.Debe) > 0 || parseInt(x.Haber) > 0);

                _lista.forEach((element, i) => {
                    element.Linea = i + 1
                });

                const response = await EncabezadoAsiento_Modificar_Request(token, _datos, _lista);

                if (response.Exitoso) {
                    Notificacion.success('Se modificó el asiento exitosamente.');
                    await volverAtras();
                } else {
                    Notificacion.error(`Error: ${response.Mensaje}`);
                }

            }
        } catch (ex) {
            Notificacion.error(ex.message);
        } finally {
            spinnerModalMostrar(false, '');
        }
    };

    const guardarAsiento = async (guardarYVolver = true) => {

        let Result = false;

        try {

            spinnerModalMostrar(true, 'Guardando asiento');

            if (!cambioDeFecha()) {

                setFModificado(true);
                Result = true;

                const fecha = moment(Datos.fecMesAno.value).format("YYYY/MM/DD");
                const tipo = selectedTipo;
                const _Datos = await siguienteContador()
                const numero = _Datos.Numero.value;
                const Descripcion = Datos.Descripcion.value
                //estado digitado
                const estado = fEstadoAsiento;
                const totalDebitos = SumeMontos(true);
                const totalCreditos = SumeMontos(false);

                const _datos = {
                    Fecha: fecha, Tipo: tipo.value, Numero: numero, Descripcion: Descripcion,
                    Debitos: totalDebitos, Creditos: totalCreditos, DigitadoX: usuario, Estado: estado,
                    empresa: empresa, Usuario_Modifica: usuario, Utilizado: false
                };

                let _lista = listaDatosExcel.filter(x => parseInt(x.Debe) > 0 || parseInt(x.Haber) > 0);

                _lista.forEach((element, i) => {
                    element.Linea = i + 1
                });

                const response = await EncabezadoAsiento_Guardar_Request(token, _datos, _lista);

                if (response.Exitoso) {
                    Notificacion.success('Se guardó el asiento exitosamente.');
                    if (guardarYVolver) {
                        await volverAtras();
                    } else {
                        await limpiarDatos();
                    }
                } else {
                    Notificacion.error(`Error: ${response.Mensaje}`);
                }

            }
        } catch (ex) {
            Notificacion.error(ex.message);
        } finally {
            spinnerModalMostrar(false, '');
        }

        return Result;

    };

    const siguienteContador = async () => {

        let Nombre = '';
        let Periodo = new Date();

        let _Datos = { ...Datos };

        Periodo = moment(Datos.fecMesAno.value).format('YYYY/MM/DD');

        if (selectedTipo.mensual) {
            Nombre = selectedTipo.label.trim() + '_' + moment(Periodo).format('MM');
        } else {
            Nombre = selectedTipo.label.trim() + '_01';
        }

        let Fechas = { Fecha: Periodo, Inicio: new Date(), Fin: new Date() };

        await buscarFronteras(Fechas);

        let response = await Contabilidad_ObtenerContadorAsiento_Request(token, empresa, moment(Fechas.Inicio).format('YYYY/MM/DD'), Nombre);

        if (response.Exitoso) {
            const Numero = response.Datos.Numero;
            _Datos.Numero.value = Numero.toString().padStart(5, '0');
        }
        else {
            const Numero = 1;
            _Datos.Numero.value = Numero.toString().padStart(5, '0');
        }

        setDatos(_Datos);

        return _Datos;

    };

    const buscarFronteras = async (params) => {

        let Periodo = new Date();
        let IniPeriodo = new Date();
        let FinPeriodo = new Date();

        if (datosEmpresa == undefined) {
            let response = await Empresa_Consulta_Request(token, empresa);

            if (response.Exitoso) {
                setDatosEmpresa(response.Datos);
                Periodo = new Date(response.Datos.Periodo);
                IniPeriodo = new Date(response.Datos.InicioPeriodo);
            } else {
                Notificacion.error(response.Mensaje);
                await volverAtras(true);
            }
        } else {
            Periodo = new Date(datosEmpresa.Periodo);
            IniPeriodo = new Date(datosEmpresa.InicioPeriodo);
        }

        FinPeriodo = obtenerFinPeriodo(IniPeriodo);

        if (moment(params.Fecha).format('MM') <= FinPeriodo.getMonth()) {
            if ((IniPeriodo.getMonth() + 1) === 1) {
                params.Inicio = new Date(moment(params.Fecha).format('YYYY'), IniPeriodo.getMonth(), 1);
                params.Fin = moment(new Date(moment(params.Fecha).format('YYYY') + 1, IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
            } else {
                params.Inicio = new Date(moment(params.Fecha).format('YYYY') - 1, IniPeriodo.getMonth(), 1);
                params.Fin = moment(new Date(moment(params.Fecha).format('YYYY'), IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
            }
        } else {
            params.Inicio = new Date(moment(params.Fecha).format('YYYY'), IniPeriodo.getMonth(), 1);
            params.Fin = moment(new Date(moment(params.Fecha).format('YYYY') + 1, IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
        }

        return params;

    };

    const obtenerFinPeriodo = (IniPeriodo) => {
        let Result = new Date();

        if ((IniPeriodo.getMonth() + 1) === 1) {
            Result = new Date(IniPeriodo.getFullYear(), 11, 31);
        }
        else {
            Result = moment(new Date(IniPeriodo.getFullYear() + 1, IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
        }

        return Result;
    };

    const cargarAsiento = async (Asiento, _Datos) => {

        let Fecha = new Date();
        let response = await EncabezadoAsiento_ObtenerAsiento_Request(token, Asiento);

        if (response.Exitoso) {
            let _asiento = { ...response.Datos };

            if (_asiento.Creacionlocal) {

                const _estado = _asiento.Estado;
                const _resultado = (_asiento.id > 0);

                if (_resultado) {

                    if ((_estado === Config.eaDigitado || _estado === Config.eaAprobado)) {

                        if (!_asiento.Utilizado) {

                            setFModificado(false);

                            setAsiento(response.Datos);
                            Fecha = new Date(response.Datos.Fecha);

                            const _listaTipo = await cargarTiposAsiento(_Datos, Fecha, false);

                            setSelectedTipo(_listaTipo.filter(x => x.value === response.Datos.Tipo)[0]);
                            _Datos.Tipo.attributes.readOnly = true;
                            _Datos.fecMesAno.attributes.readOnly = true;
                            //_Datos.FechaAnio.attributes.readOnly = true;
                            _Datos.Numero.value = response.Datos.Numero.toString().padStart(5, '0');
                            setValidarBalanceado(parseInt(response.Datos.Estado) === parseInt(Config.eaAprobado));
                            _Datos.fecMesAno.value = Fecha;
                            //setSelectedOptionMes(itemSelect(Fecha.getMonth() + 1, listaMeses));
                            _Datos.Descripcion.value = response.Datos.Descripcion;

                            await CambiarUtilizado(_asiento.id, true);

                            await cargarDetalleAsiento(Asiento, Fecha, _asiento.id);

                            setDatos(_Datos);

                        } else {
                            Notificacion.warning('Este Asiento está siento utilizado por otro Usuario.');
                            await volverAtras(false,false);
                        }
                    } else {
                        Notificacion.warning('Este Asiento ya no está disponible para modificar, porque otro usuario cambio su estado.');
                        await volverAtras();
                    }
                } else {
                    Notificacion.warning('No se encontró el Asiento.');
                    await volverAtras();
                }
            } else {
                Notificacion.warning('Este asiento fue creado en un auxiliar y no puede modificarse.');
                await volverAtras();
            }
        } else {
            Notificacion.error(response.Mensaje);
            await volverAtras(true);
        }
    };

    const cargarDetalleAsiento = async (Asiento, Fecha, pId) => {

        const response = await DetalleAsiento_Listar_Request(token, Asiento);

        const item = {
            Asiento: 0,
            Centro_Costo: 0,
            Centro_CostoStr: "",
            Credito: false,
            Cuenta: 0,
            CuentaStr: "",
            Debe: 0,
            Documento: "",
            Fecha: Fecha,
            Fecha_Actualizacion: new Date("1900-01-01"),
            Haber: 0,
            Linea: 0,
            Monto: 0,
            MsgError: "",
            NombreCuenta: "",
            Referencia: "",
            Referencia2: "",
            TipoDoc: 0,
            llave: ""
        };

        if (response.Exitoso) {
            if (Array.isArray(response.Datos)) {
                let _lista = [...response.Datos];
                let _debe = 0;
                let _haber = 0;
                _lista.forEach((element, i) => {
                    element.llave = element.Linea.toString();
                    _debe = _debe + parseFloat(element.Debe);
                    _haber = _haber + parseFloat(element.Haber);
                });

                setTotalDebe(_debe);
                setTotalHaber(_haber);

                _lista.push(item);

                //Comentado para no mostrar nada
                //setListaDatos(_lista);

            } else {
                Notificacion.error(`${response.Mensaje}`);
                let _lista = [];
                _lista.push(item);
            }
        }
        else {
            if(response.Mensaje != 'No hay datos por mostrar.'){
                Notificacion.error(response.Mensaje);
                if (pId !== 0) {
                    await CambiarUtilizado(pId, false);
                }
                await volverAtras();
            }else{
                let _lista = [];
                _lista.push(item);
                //setListaDatos(_lista);
                return true;
            }
        }
    }

    const CambiarUtilizado = async (Id, Utilizado) => {
        const _asiento = { id: Id, Utilizado: Utilizado }

        const response = await EncabezadoAsiento_ModificarUtilizado_Request(token, _asiento);

        if (response.Exitoso) {
            return true;
        } else {
            Notificacion.error(`Error: ${response.Mensaje}`);
            return false;
        }

    };

    /*
    const guardarAsiento = async () => {

        let P, NomCont, Fecha, Numero, Llave, Tipo, TipoCreacion;

        switch (fTipoCreacion) {
            case 1:
                TipoCreacion = "Normal";
                break;
            case 2:
                TipoCreacion = "De Plantilla";
                break;
            case 3:
                TipoCreacion = "De Excel";
                break;
        }

        if (!cambioDeFecha()) {
            Tipo = selectedTipo.value;
            P = selectedTipo;
        }

        if (selectedTipo.mensual) {
            Nombre = selectedTipo.label.trim() + '_' + moment(Periodo).format('MM');
        } else {
            Nombre = selectedTipo.label.trim() + '_01';
        }

        console.log(TipoCreacion);
        console.log(NomCont);
        console.log(selectedTipo);
        return true;

    };*/

    const cambioDeFecha = () => {
        if (moment(Datos.fecMesAno.value).format("YYYY/MM/DD") < moment(datosEmpresa.Periodo).format("YYYY/MM/DD")) {
            return true;
        } else {
            return false;
        }
    };

    const abrirCalculadora = () => {
        window.open('Calculator:///');
    }

    const spinnerModalMostrar = (pSpinnerModal, pSpinnerLabel, pSpinnerTipo) => {
        setSpinnerModal(pSpinnerModal);
        setSpinnerLabel(pSpinnerLabel);
        setSpinnerTipo(pSpinnerTipo);
    };

    const handleCuentaModal = (cell, columnIndex, row, rowIndex) => {

        const indexC = listaDatos.findIndex((element) => element.Linea === cell.Linea);

        setIndexC(indexC);
        setSelectModalTree(true);
        setPColumn(cell);
    }

    //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 validaCuentaTabla = (newValue, row, column) => {

        if (row.CuentaStr !== newValue) {

            if (column.dataField === 'CuentaStr') {
                const validacion = validaCuenta(listaCuentas, newValue)

                if (validacion.length > 0) {
                    return {
                        valid: false,
                        message: validacion,
                    };
                } else {

                    const _listaCuenta = listaCuentas.filter(item => item.Cuenta == newValue || item.CuentaStr == newValue);

                    row.CuentaStr = _listaCuenta[0].Cuenta;
                    row.Cuenta = _listaCuenta[0].ID;
                    row.Centro_CostoStr = "";
                    row.Centro_Costo = 0;

                    return { valid: true, mensaje: "" };
                }
            }
        } else {
            return { valid: true, mensaje: "" };
        }
    };

    const validarMenuOpcion = (pOpcion) => {
        let validar = false;
        let _menuOpciones = menuOpciones;
        const optSegopt = optSeg.TOpciones_Menu;
        let resultado = _menuOpciones.filter((item) => item.Opcion_Nombre == pOpcion);
        if (resultado.length > 0) {
            if (resultado[0].Opcion_Validar) {
                setShowModalSeguridad(true); setOpcionValidar(resultado[0].Opcion_Id); setOpcionValidarNombre(pOpcion);
                validar = true;
            }
        } else {
            setShowModalSeguridad(true); setOpcionValidar(resultado[0].Opcion_Id); setOpcionValidarNombre(pOpcion);
            validar = true;
        }
        return validar;
    };

    const onValidarCCosto = (newValue, row, column) => {

        if (row.Centro_CostoStr !== newValue) {
            if (column.dataField == 'Centro_CostoStr') {
                if (!!row.Cuenta) {
                    if (row.Cuenta != -1) {
                        const validacion = validaCCosto(listCCosto, row.Cuenta, newValue, listCXCC)
                        if (validacion.length > 0) {
                            return {
                                valid: false,
                                message: validacion
                            };
                        } else {
                            const listaCCosto = listCCosto.filter(item => item.CentroCosto == newValue);
                            const validaRepetido = listaDatos.filter(item => item.Centro_CostoStr === newValue && item.CuentaStr === row.CuentaStr);

                            if (validaRepetido.length > 0) {
                                return {
                                    valid: false,
                                    message: "El centro de costo y la cuenta están repetidos"
                                };
                            } else {
                                row.Centro_Costo = listaCCosto[0].ID;
                                row.Centro_CostoStr = listaCCosto[0].CentroCosto;
                                return true;
                            }
                        }
                    } else {
                        return {
                            valid: false,
                            message: 'Debe seleccionar una cuenta contable'
                        };
                    }
                } else {
                    return {
                        valid: false,
                        message: 'Debe seleccionar una cuenta contable'
                    };
                }
            }
        } else {
            return true;
        }
    };

    const handleCerrarModal = () => setShowModalSeguridad(false);

    const handleModal = async (cell, row) => {

        const modal = true;
        const _indexCost = row;

        if (!!cell.Cuenta) {
            if (cell.Cuenta != -1) {
                spinnerModalMostrar(true, 'Cargando datos');
                const response = await CentroCosto_Lista_CXCC_Request(token, empresa, cell.Cuenta);
                spinnerModalMostrar(false, '');

                let _listCentroCostoFiltro = [];

                if (response.Exitoso) {
                    _listCentroCostoFiltro = response.Datos;
                } else {
                    Notificacion.error(response.Mensaje);
                    await volverAtras(true);
                    return;
                }

                //const _idCCObj = cell.llave.toString() + 'B';
                setSelectModalBusqueda(modal), setListCentroCosto(_listCentroCostoFiltro), setListCentroCostoFiltro(_listCentroCostoFiltro);
                setIndexCost(_indexCost); //setIdCCObj(_idCCObj);

            } else {
                Notificacion.warning('Debe seleccionar una cuenta contable.');
            }
        } else {
            Notificacion.warning('Debe seleccionar una cuenta contable.');
        }

    };

    const onActionResultModal = (pValido) => {
        if (pValido) {
            let _OpcionNom = opcionValidarNombre;
            setShowModalSeguridad(false); setOpcionValidar(0); setOpcionValidarNombre('');
            const _optSegopt = optSeg.TOpciones_Menu;

            switch (_OpcionNom) {
                case _optSegopt.ImportarExcel.value:
                    handleUtilizarSel();
                    break;
                case _optSegopt.Editar.value:
                    modificarAsiento();
                    break;
                case _optSegopt.Nuevo.value:
                    guardarAsiento();
                    break;
                default:
                    break;
            }
        }
    };

    useEffect(() => {
        const carga = async () => {
            await cargarDatos();
        }
        carga();


    }, []);

    const cargarDatos = async (limpiar = false) => {
        try {
            let spinnerLabel = 'Cargando datos...';
            spinnerModalMostrar(true, spinnerLabel, 3);

            const _datosEmpresa = await cargarEmpresa();
            const _Datos = { ...Datos };

            const _id = (props.match.params.id !== undefined ? parseInt(props.match.params.id) : 0);

            setId(_id);

            let Periodo = new Date(_datosEmpresa.Periodo);

            if (_id > 0) {
                setFModificado(false);
                await cargarAsiento(_id, _Datos);
            } else {

                _Datos.Descripcion.attributes.readOnly = true;
                _Datos.fecMesAno.attributes.readOnly = false;
                _Datos.Tipo.attributes.readOnly = false;

                setValidarBalanceado(false);
                setFModificado(false);
                setSelectedTipoCreacion(tipoCreacion[0]);

                if (limpiar) {
                    _Datos.Descripcion.value = "";
                    setTotalDebe(0);
                    setTotalHaber(0);
                }

                ingresarDetalle(Periodo, limpiar);

                setDatos(_Datos);
            }

            _Datos.fecMesAno.value = moment(_datosEmpresa.Periodo).toDate();

            setDatos(_Datos);

            setDatosEmpresa(_datosEmpresa);

            await cargarTiposAsiento();
            let _listaCuentasCont = await carga_ListTree();

            setListCuentasCont(_listaCuentasCont);
            await cargarCentrosDeCosto();

            const _MenuNomb = await cargarMenuNombre(Config.Modulo, optSeg.TMenuSistema.Asientos.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);

        } catch (e) {
            Notificacion.error(e.message);
        }
        finally {
            spinnerModalMostrar(false, '', 3);
        }
    };

    const carga_ListTree = async () => {

        const response = await Catalogo_Lista_Request(token, empresa, 0);
        let _lista = [];
        if (response.Exitoso) {
            const _listCuentas = response.Datos;
            const _listCuentasCont = llenadoListaArbol(_listCuentas);
            setListaCuentas(_listCuentas);
            _lista = datosArbol(_listCuentasCont);
        }
        else {
            Notificacion.error(`Error: ${response.Mensaje}`);
            await volverAtras(true);
        }

        return _lista;
    };

    const llenadoListaArbol = (pLista) => {
        let _Datos = [];
        const _Lista = pLista;
        _Datos.push({ "title": empresaNombre, "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;
    };

    const cargarCentrosDeCosto = async () => {

        let response = await CentroCosto_Lista_CCC_Request(token, empresa);

        if (response.Exitoso) {
            if (Array.isArray(response.Datos)) {
                setListCCosto(response.Datos);
            } else {
                Notificacion.error('No hay datos para: Centros de Costo.');
                await volverAtras(true);
            }
        }
        else {
            Notificacion.error(response.Mensaje);
            await volverAtras(true);
        }

        response = await CentroCosto_Lista_CXCCEmpresa_Request(token, empresa);

        if (response.Exitoso) {
            if (Array.isArray(response.Datos)) {
                setListCXCC(response.Datos);
            } else {
                Notificacion.error('No hay datos para: Centros de Costo.');
                await volverAtras(true);
            }
        }
        else {
            Notificacion.error(response.Mensaje);
            await volverAtras(true);
        }

    };

    const volverAtras = async (param = false, pDesbloquear) => {
        const _Desbloquear = (pDesbloquear == undefined) ? true : pDesbloquear;
        if (_Desbloquear) {
            let _id = parseInt(props.match.params.id);

            if (_id > 0) {
                await CambiarUtilizado(_id, false);
            }
        }
        historyMenu.push(SiteRutas.Asientos);
    };

    const handleCerrarModalExcel = () => {

        Swal.fire({
            title: 'Importar',
            html: '<h4>¿Desea guardar el asiento?',
            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) {
                true;
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                setShowModalExcel(false);
                volverAtras(true);
            }
        });
    };

    const validaDebe = (newValue, row) => {
        //newValue = (parseFloat(newValue.toString().replace(/,/g, "")));
        if (!isNaN(newValue)) {
            if (parseFloat(newValue) > 0 && parseFloat(row.Haber) == 0) {
                return true;
            } else if (parseFloat(newValue) > 0 && parseFloat(row.Haber) > 0) {
                return {
                    valid: false,
                    message: '¡No puede llenar Debe y Haber en la misma fila!'
                }
            } else {
                if (parseFloat(newValue) >= 0) {
                    return true;
                } else {
                    return {
                        valid: false,
                        message: '¡Debe ingresar un valor numérico!'
                    }
                }
            }
        } else {
            return {
                valid: false,
                message: '¡Debe ingresar un valor numérico!'
            }
        }
        //return true;
    };

    const validaHaber = (newValue, row) => {
        //newValue = (parseFloat(newValue.toString().replace(/,/g, "")));
        if (!isNaN(newValue)) {
            if (parseFloat(newValue) > 0 && parseFloat(row.Debe) == 0) {
                return true;
            } else if (parseFloat(newValue) > 0 && parseFloat(row.Debe) > 0) {
                return {
                    valid: false,
                    message: '¡No puede llenar Debe y Haber en la misma fila!'
                }
            } else {
                if (parseFloat(newValue) >= 0) {
                    return true;
                } else {
                    return {
                        valid: false,
                        message: '¡Debe ingresar un valor numérico!'
                    }
                }
            }
        } else {
            return {
                valid: false,
                message: '¡Debe ingresar un valor numérico!'
            }
        }
        return true;
    };

    const cellEdit = {
        mode: "click",
        blurToSave: true,
        autoSelectText: true,
       /* afterSaveCell: (oldValue, newValue, row, column) => {
            setTotalDebe(SumeMontos(true));
            setTotalHaber(SumeMontos(false));

            if (column.dataField === "Debe" || column.dataField === "Haber") {
                if (parseInt(listaDatos[listaDatos.length - 1].Debe) > 0 || parseInt(listaDatos[listaDatos.length - 1].Haber) > 0) {
                    ingresarDetalle(moment(Datos.fecMesAno.value).format("YYYY/MM/DD"), 1);
                }
            }
        },*/
    };

    //const cellEdit = { mode: 'click', blurToSave: true, autoSelectText: true };

    const selectRow = {
        mode: 'radio', hideSelectColumn: true, clickToEdit: true, bgColor: '#d73220', style: { color: '#ffffff' },
        clickToSelect: true, onSelect: (row, isSelected) => onRowSelect(row, isSelected)
    };

    const selectRowExcel = {
        mode: 'radio', hideSelectColumn: true, clickToEdit: true, bgColor: '#d73220', style: { color: '#ffffff' },
        clickToSelect: true, onSelect: (row, isSelected) => onRowSelect(row, isSelected)
    };

    const onRowSelect = (row, isSelect) => {
        return true;
    };

    const ingresarDetalle = (Periodo, limpiar = false) => {

        let _listaDatos = limpiar ? [] : [].concat(listaDatos);

        let item = {
            Asiento: 0,
            Centro_Costo: 0,
            Centro_CostoStr: "",
            Credito: false,
            Cuenta: 0,
            CuentaStr: "",
            Debe: 0,
            Documento: _listaDatos.length === 0 ? "" : _listaDatos[_listaDatos.length - 1].Documento,
            Fecha: Periodo,
            Fecha_Actualizacion: new Date("1900-01-01"),
            Haber: 0,
            Linea: (_listaDatos.length + 1),
            Monto: 0,
            MsgError: "",
            NombreCuenta: "",
            Referencia: _listaDatos.length === 0 ? Datos.Descripcion.value : _listaDatos[_listaDatos.length - 1].Referencia,
            Referencia2: "",
            TipoDoc: 0,
            llave: (_listaDatos.length + 1).toString()
        };

        _listaDatos.push(item);

        setListaDatos(_listaDatos);

    };

    const cargarEmpresa = async () => {
        let response = await Empresa_Consulta_Request(token, empresa);

        if (response.Exitoso) {
            return (response.Datos);
        } else {
            Notificacion.error(response.Mensaje);
            volverAtras(true);
        }
        return null;
    };

    const validaGuardarFila = (fila) => {

        let msgError = "";

        if (fila.Fecha !== null && moment(fila.Fecha).format("YYYY/MM/DD") === moment('1000/01/01').format("YYYY/MM/DD")) {
            msgError += `La fecha digitada es inválida.`;
        }

        if (fila.Documento.length > 255) {
            msgError += `El largo del documento es mayor a lo permitido. `;
        }

        if (fila.Referencia.length > 255) {
            msgError += `El largo de la referencia es mayor a lo permitido. `;
        }

        if (isNaN(fila.Debe)) {
            msgError += `El Monto de débitos no es númerico. `;
        }

        if (fila.Debe < 0) {
            msgError += `Los débitos no pueden ser negativos. `;
        }

        if (isNaN(fila.Haber)) {
            msgError += `El Monto de créditos no es númerico. `;
        }

        if (fila.Haber < 0) {
            msgError += `Los créditos no pueden ser negativos. `;
        }

        if (!isNaN(fila.Debe) && !isNaN(fila.Haber)) {
            if ((fila.Debe !== 0 && fila.Haber !== 0) || (fila.Debe === fila.Haber) || (fila.Debe === 0 && fila.Haber === 0)) {
                msgError = `Una de las columnas debe ser cero y la otra un monto correcto. `;
            }
        }

        return msgError;

    };

    const validaLista = (_listaDatos) => {

        let valido = true;

        for (let i = 0; i < _listaDatos.length; i++) {

            if (!validaGuardarFila(_listaDatos[i])) {
                valido = false;
                break;
            }

        };

        return valido;

    };

    const handleAceptar = (_listaDatos) => {

        const optSegopt = optSeg.TOpciones_Menu;
        let opcionValidar = optSegopt.ImportarExcel.value;

        try {

            if (_listaDatos.filter(x => parseFloat(x.Debe) > 0 || parseFloat(x.Haber) > 0).length > 0) {

                revisarErrores();

            } else {
                Notificacion.warning(`Debe seleccionar un Archivo con datos válidos para poder importarlos.`);
            }

        } catch (ex) {
            Notificacion.error(`Error: ${ex.message}`);
        }

    };

    const revisarErrores = () => {

        let array = listaDatos, resultado = [], errores = 0, debe, haber;

        if (array.length === 0) {
            return;
        }

        for (let i in array) {

            debe = Number.parseInt((array[i].Debe).toString().replace(/,/g, ''));
            haber = Number.parseInt((array[i].Haber).toString().replace(/,/g, ''))

            array[i].Debe = isNaN(debe) ? array[i].Debe : debe;
            array[i].Haber = isNaN(haber) ? array[i].Haber : haber;

            let fila = procesoCargaFila(array[i], i, resultado, false);

            if (fila.MsgError !== "") {
                errores++;
            }

            resultado.push(fila);
        }

        setListaDatos(resultado);

        if (errores > 0) {
            Notificacion.warning(`Existen errores en las líneas a procesar.`);
        } else {

            setfAgregando(id === 0);
            setFModificando(id !== 0);
            setfTipoCreacion(3);

            if (id !== 0) {
                handleUtilizarSel();
            } else {
                Datos.Descripcion.attributes.readOnly = false;
                setListaDatosExcel(resultado);
                setShowModalExcel(true);
            }
        }
    };

    const handleUtilizarSel = () => {

        let resultado = true;

        Swal.fire({
            title: 'Importar',
            html: '<h4>¿Está seguro de reemplazar el asiento seleccionado con el contenido del excel? este proceso no se podrá reversar. ¿Desea continuar?',
            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;
                guardarDatos();
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                resultado = false;
            }
        });

    };

    const sum = (list, key) => {
        return list.reduce((a, b) => a + (b[key] || 0), 0);
    };

    const Utilizar = async () => {
        try {
            //Tipo Creacion Desde Excel
            const tipoCreacion = 3;

            const tipoAsiento = selectedTipo.value;

            const _datos = {
                Fecha: new Date(), Numero: 0, Descripcion: Datos.Descripcion.value, TipoCreacion: tipoCreacion,
                Debitos: 0, Creditos: 0, DigitadoX: usuario, Estado: 0,
                Usuario_Modifica: usuario, Utilizado: false, id: id, Tipo: tipoAsiento, empresa: empresa,
                Modificado: usuario
            };

            _datos.Debitos = sum(listaDatos, 'Debe');
            _datos.Creditos = sum(listaDatos, 'Haber');

            spinnerModalMostrar(true, `Actualizando Asiento`, 3);
            const response = await EncabezadoAsiento_ModificarDesdeExcel_Request(token, _datos, listaDatos, usuarioS);
            spinnerModalMostrar(false, '', 3);

            if (response.Exitoso) {
                Notificacion.success(`Proceso realizado satisfactoriamente.`);
                volverAtras();
            } else {
                Notificacion.error(`Error: ${response.Mensaje}`);
            }
        } catch (ex) {
            Notificacion.error(`Error: ${ex.message}`);
        }
    };

    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 } });

        setDatos(_Datos);

    };

    const onChangeInput = (e) => {

        const name = e.target.name;
        const value = e.target.value;

        let newAttributes = Datos[name].attributes;
        let _Datos = Object.assign({}, Datos, {
            [name]: { value: value, attributes: newAttributes },
        });

        setDatos(_Datos);

    };

    const handleselectTipo = (selTipo) => {
        //console.log("__");
        setSelectedTipo(selTipo);
    };

    const generarItem = () => {

        return {
            Asiento: 0,
            Centro_Costo: 0,
            Centro_CostoStr: "",
            Centro_CostoNom: "",
            Credito: false,
            Cuenta: 0,
            CuentaStr: "",
            Debe: 0,
            Documento: "",
            Fecha: moment().format("YYYY/MM/DD"),
            Fecha_Actualizacion: moment("1900-01-01").format("YYYY/MM/DD"),
            Haber: 0,
            Linea: 0,
            Monto: 0,
            MsgError: "",
            NombreCuenta: "",
            NombreCuentaCC: "",
            Referencia: "",
            Referencia2: "",
            TipoDoc: 0,
            llave: ""
        };
    };

    const numeroAFecha = (numeroDeDias, esExcel = false) => {
        var diasDesde1900 = esExcel ? 25567 + 1 : 25567;
        return new Date((numeroDeDias - diasDesde1900) * 86400 * 1000);
    };

    const crearItem = (arrayElementos, filaRevisa, esDeExcel) => {
        let fila = {};

        fila = generarItem();
        if (esDeExcel) {
            fila.Linea = filaRevisa - 2;
            fila.CuentaStr = arrayElementos[0];
            fila.Centro_CostoStr = arrayElementos[1];
            fila.NombreCuenta = arrayElementos[2];
            fila.Fecha = arrayElementos[3] == "" ? null : numeroAFecha(arrayElementos[3], true);
            fila.Documento = arrayElementos[4] == undefined ? "" : arrayElementos[4];
            fila.Referencia = arrayElementos[5] == undefined ? "" : arrayElementos[5];
            fila.Debe = arrayElementos[6];
            fila.Haber = arrayElementos[7];
        } else {
            fila.Linea = filaRevisa - 2
            fila.CuentaStr = arrayElementos.CuentaStr;
            fila.Centro_CostoStr = arrayElementos.Centro_CostoStr;
            fila.NombreCuenta = arrayElementos.NombreCuenta;
            fila.Fecha = arrayElementos.Fecha;
            fila.Documento = arrayElementos.Documento == undefined ? "" : arrayElementos.Documento;
            fila.Referencia = arrayElementos.Referencia == undefined ? "" : arrayElementos.Referencia;
            fila.Debe = arrayElementos.Debe;
            fila.Haber = arrayElementos.Haber;
        }
        return fila;
    };

    const validaRepetidos = (arrayDinamico, fila) => {
        let validacion = arrayDinamico.filter(item => item.CuentaStr === (fila.CuentaStr.toString()).trim() && item.Centro_CostoStr === fila.Centro_CostoStr);

        if (validacion.length > 0) {
            return "Repetido";
        } else {
            return "";
        }
    };

    const validarFila = (fila, filaRevisa) => {

        ////Valida la cuenta y luego el centro de costo
        let validaCuenta = validarCuenta(fila.CuentaStr, filaRevisa)

        if (validaCuenta === "") {

            const filtroCuenta = listaCuentas.filter(item => item.Cuenta === fila.CuentaStr.trim());

            if (filtroCuenta.length > 0) {
                fila.Cuenta = filtroCuenta[0].ID;
            }

            let responseValidaCCosto = validarCCostoExcel(fila.Cuenta, fila.Centro_CostoStr);

            if (responseValidaCCosto === "") {
                const filtroCCosto = listCCosto.filter(item => item.CentroCosto == fila.Centro_CostoStr.toString().trim());

                if (filtroCCosto.length > 0) {
                    fila.Centro_Costo = filtroCCosto[0].ID;
                    fila.NombreCuentaCC = filtroCuenta[0].Nombre
                }
            } else {
                fila.MsgError += `${responseValidaCCosto}. `;
            }

        } else {
            fila.Centro_CostoStr = "";
            fila.MsgError += `${validaCuenta} ${validaCuenta === "No se encontró la cuenta" ? fila.CuentaStr : ""}. `;
        }

        /////Valida guardar la fila
        let tempError = validaGuardarFila(fila);

        if (tempError !== "") {
            fila.MsgError += `${tempError}`;
        }

        return fila;

    };

    const procesoCargaFila = (array, posicion, listaDinamica, esDeExcel) => {
        let filaItem = crearItem(array, posicion, esDeExcel);

        let fila = validarFila(filaItem, posicion);

        let validacion = validaRepetidos(listaDinamica, fila);

        if (validacion !== "") {
            fila.MsgError = `La cuenta y el centro de costo están repetidos. ${fila.MsgError} `

            for (let i in listaDinamica) {
                if (listaDinamica[i].CuentaStr === fila.CuentaStr.toString().trim() && listaDinamica[i].Centro_CostoStr === fila.Centro_CostoStr && !(listaDinamica[i].MsgError.includes("La cuenta y el centro de costo están repetidos"))) {
                    listaDinamica[i].MsgError = `La cuenta y el centro de costo están repetidos. ${listaDinamica[i].MsgError}`;
                }
            }

        }

        return fila;
    };

    const leerArchivoExcel = (dataParse) => {

        const _Datos = { ...Datos };
        let errores = 0;

        try {
            _Datos.Descripcion.value = dataParse[0][1];

            let filaRevisa = 3;
            let _listaDatos = [];

            while (dataParse[filaRevisa].length === 8) {
                let fila = procesoCargaFila(dataParse[filaRevisa], filaRevisa, _listaDatos, true);

                if (fila.MsgError !== "") {
                    errores++;
                }

                _listaDatos.push(fila);
                filaRevisa++;
            }

            setListaDatos([]);
            setListaDatos(_listaDatos);

            if (errores === 0) {
                setfAgregando(id === 0);
                setFModificando(id !== 0);
                setfTipoCreacion(3);
                Datos.Descripcion.attributes.readOnly = false;

                if (id !== 0) {

                    handleUtilizarSel();

                } else {
                    setShowModalExcel(true);
                    setListaDatosExcel(_listaDatos);
                }

            }

        } catch (ex) {
            console.log(ex);
            Notificacion.error(`Ocurrió un error procesando el archivo.`);
        }
    };

    const cargaArchivoExcel = (e) => {
        e.preventDefault();
        if (e.target.files != undefined) {

            let files = e.target.files, f = files[0];
            let reader = new FileReader();
            let self = this;
            const exts = { '.xls': 1, '.xlsx': 1 };
            let re = /\..+$/;
            let ext = f.name.match(re);
            if (exts[ext]) {
                reader.onload = function (e) {
                    var data = e.target.result;
                    let readedData = XLSX.read(data, { type: 'binary' });
                    const wsname = readedData.SheetNames[0];
                    const ws = readedData.Sheets[wsname];

                    const dataParse = XLSX.utils.sheet_to_json(ws, { header: 1 });

                    leerArchivoExcel(dataParse)

                };
            } else {
                //setListaDatosDetalle([]);
                Notificacion.warning('Dede seleccionar un archivo del tipo xls o xlsx.');
                e.value = '';
            }
            reader.readAsBinaryString(f);
        }
        e.target.value = '';
    };

    const handleClick = (e) => {
        e.preventDefault();
        hiddenFileInput.current && hiddenFileInput.current.click();
    };

    const cargarTiposAsiento = async () => {
        if (empresa !== 0) {
            const response = await TipoAsiento_Listar_Request(token, empresa);
            let lista = [];
            if (response.Exitoso) {

                if (Array.isArray(response.Datos) && response.Datos.length > 0) {
                    response.Datos.map(x => (lista.push({ value: x.ID, label: x.Nombre, mensual: x.Mensual })));
                    setListaTipo(lista);
                    setSelectedTipo(lista[0]);
                } else {
                    await volverAtras(true);
                }

            }
            else {
                Notificacion.error(response.Mensaje);
                await volverAtras(true);
            }
            return lista;
        }
    };


    const validarCambiarUtilizado = async () => {
        if (id !== 0) {
            await CambiarUtilizado(asiento.id, false);
        }
    };


    const validaCCosto = (plista, pcuenta, pCCosto, pListaCXCC) => {
        let cCosto = new RegExp('^' + pCCosto + '-', 'i');
        let idCC = -1;
        const listCentroCosto = plista.filter(item => item.CentroCosto == pCCosto);
        if (listCentroCosto.length == 0) {
            return 'El centro de costo no existe'
        }
        else {
            const listaCCosto = plista.filter(item => item.CentroCosto.match(cCosto));
            if (listaCCosto.length > 0) {
                return 'El centro de costo es de mayor'
            }
        }
        idCC = listCentroCosto[0].ID;
        // let filtro = { ID: [pcuenta], CentroCosto: [idCC] };
        // const listaCCCosto = multiFilter(pListaCXCC, filtro)


        // if (listaCCCosto.length == 0) {
        //     return 'No existe relacion entre la cuenta y el centro de costo'
        // }

        return '';
    };

    const validarCCosto = (Cuenta, CCosto) => {


        if (Cuenta !== "") {

            const validacion = validaCCosto(listCCosto, Cuenta, CCosto, listCXCC);
            if (validacion.length > 0) {
                Notificacion.error(validacion);
                return false;
            } else {
                const listaCCosto = listCCosto.filter(item => item.Centro_Costo === CCosto);
                return true;
            }
        } else {
            Notificacion.error('No se encontró el centro de costo.');
            return false;
        };

    };

    const validarCCostoExcel = (Cuenta, CCosto) => {
        if (Cuenta !== "") {
            const validacion = validaCCosto(listCCosto, Cuenta, CCosto, listCXCC);
            if (validacion.length > 0) {
                return validacion;
            } else {
                return "";
            }
        } else {
            return "No se encontró el centro de costo";
        };
    };

    const validarCuenta = (Cuenta, Linea) => {

        const validacion = validaCuenta(listaCuentas, Cuenta);

        if (validacion.length > 0) {
            return validacion;
        } else {
            const _listaCuenta = listaCuentas.filter(item => item.Cuenta == Cuenta || item.CuentaStr == Cuenta);
            if (_listaCuenta.length > 0) {
                return "";
            }
            else {
                return "No se encontró la cuenta";
            }
        }
    };

    const onRowSelectBusquedaTree = (row) => {
        setSelectedCuenta(row);
    };

    const cerrarModalTree = () => {
        setIndexC(-1);
        setSelectModalTree(false);
    };

    const seleccionModalTree = async () => {
        if (!!selectedCuenta) {
            if (!selectedCuenta.node.children) {

                const listCCont = listaCuentas.filter(item => item.ID == selectedCuenta.node.value);
                let _pColumn = { ...pColumn };
                //listCuentasLista ///// de todas las cuentas existentes
                //listCCont ///// Lista de la lista filtrada
                //pColumn ////// Es la celda que se manda por parámetro al abrir el modal

                _pColumn.Cuenta = listCCont[0].ID;
                _pColumn.CuentaStr = listCCont[0].Cuenta;
                _pColumn.NombreCuentaCC = listCCont[0].Nombre;
                _pColumn.NombreCuenta = listCCont[0].Nombre;

                spinnerModalMostrar(true, 'Cargando datos', 3);
                const response = await CentroCostos_CentroDefault_Request(token, empresa, _pColumn.Cuenta);
                spinnerModalMostrar(false, '', 3);

                //let _listaDatos = [].concat(listaDatosExcel);
                let _listaDatos = [].concat(listaDatos);
                
                _listaDatos[indexC].CuentaStr = _pColumn.CuentaStr
                _listaDatos[indexC].Cuenta = _pColumn.Cuenta;
                _listaDatos[indexC].NombreCuenta = _pColumn.NombreCuenta;
                _listaDatos[indexC].NombreCuentaCC = _pColumn.NombreCuentaCC

                if (response.Exitoso) {
                    _listaDatos[indexC].Centro_Costo = response.Datos.ID;
                    _listaDatos[indexC].Centro_CostoStr = response.Datos.CentroCosto;
                    _listaDatos[indexC].Centro_CostoNom = response.Datos.Nombre;
                }
                else {
                    Notificacion.error(response.Mensaje);
                }

                setListaDatos(_listaDatos);
                setSelectedCuenta(undefined);
                setSelectModalTree(false);
                setIndexC(-1);
                setPColumn(_pColumn);

            }
            else {
                Notificacion.error('La cuenta selccionada es padre.');
                setSelectModalTree(false);
                setSelectedCuenta(undefined);
            }
        }
        else {
            Notificacion.warning('Debe seleccionar un registro.');
        }
    };

    const onRowSelectBusqueda = (row) => {
        setSelectedCentroCosto(row);
    };

    const handleChangeSearch = (event) => {
        let _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 cerrarModalBusqueda = () => {
        setSelectModalBusqueda(false);
        setSelectedCentroCosto(undefined);
        setIndexCost(indexCost);
        setRowSelected(undefined);
    };

    const seleccionModal = () => {
        if (!!selectedCentroCosto) {
            const listCCost = listCCosto.filter(item => item.ID == selectedCentroCosto.ID);

            let _listaDatos = [].concat(listaDatos);

            _listaDatos[indexCost].Centro_Costo = listCCost[0].ID;
            _listaDatos[indexCost].Centro_CostoStr = listCCost[0].CentroCosto;

            setListaDatos(_listaDatos);
            setSelectedCentroCosto(undefined);
            setSelectModalBusqueda(false);
            setIndexCost(indexCost);
        }
        else {
            Notificacion.warning('Debe seleccionar un registro.');
        }
    };

    const handleCambioTipo = (selTipo) => {

        setSelectedTipo(selTipo);
    };

    const handleCerrarModalBi = () => {
        setSelectModalBi(false);
    };

    const handleClickModal = (e) => {

        setselectedModalDesc(false);

        e.preventDefault();
        hiddenFileInput.current && hiddenFileInput.current.click();
    };

    return (
        <Fragment>
            <CargaAsientoExcelInt
                titulo={"Carga de Asientos"}
                Datos={Datos}
                botones={botones}
                handleselectTipo={handleselectTipo}
                onhandleChangeDate={onhandleChangeDate}
                cargaArchivoExcel={cargaArchivoExcel}
                onChangeInput={onChangeInput}
                selectedTipo={selectedTipo}
                listaTipo={listaTipo}
                listaDatos={listaDatos}
                columnas={columnas}
                cellEdit={cellEdit}
                selectRow={selectRow}
                hiddenFileInput={hiddenFileInput}
            />

            <ModalSpinner
                selectedModal={spinnerModal}
                contentLabel={'spinnerModalProgress'}
                label={spinnerLabel}
                tipoSpinner={spinnerTipo}
            />
            <ModalSeguridad
                modalTitle={'Requiere Permisos'}
                menuId={menuId}
                opcionId={opcionValidar}
                show={showModalSeguridad}
                onActionResult={onActionResultModal}
                onHide={handleCerrarModal}
            />
            <BotonArriba Delay={10} Visible={100} />

            <ModalCargaAsiento
                selectedModal={showModalExcel}
                contentLabel={'selectedCargaIngDedDet'}
                elementos={Datos}
                datos={listaDatosExcel}
                id={'Linea'}
                columnas={columnasExcel}
                striped={false}
                hover={true}
                condensed={false}
                selectRow={selectRowExcel}
                label={'Nuevo Asiento'}
                cellEdit={cellEdit}
                cerrarModal={handleCerrarModalExcel}
                seleccionModal={() => { }}
                datosFiltro={[]}
                verLHOC={false}
                botones={botonesExcel}
                onhandleChangeDate={onhandleChangeDate}
                handleselectTipo={handleselectTipo}
                onChangeInput={onChangeInput}
                selectedTipo={selectedTipo}
                listaTipo={listaTipo}
                handleCambioTipo={handleCambioTipo}
            />

            <ModalBusqueda
                selectedModal={selectModalBusqueda}
                contentLabel={'selectedBusquedas'}
                listaFiltro={listCentroCostoFiltro}
                columnas={Header}
                keyRow={'ID'}
                label={'Lista de Centros de Costos Asociados'}
                onSelectedRow={onRowSelectBusqueda}
                handleChangeSearch={handleChangeSearch}
                cerrarModal={cerrarModalBusqueda}
                seleccionModal={seleccionModal}
                rowsSelected={rowsSelected}
            />

            <ModalBusquedaTree
                selectedModal={selectModalTree}
                contentLabel={'selectedBusquedasTree'}
                label={'Catálogo'}
                onSelectedRow={onRowSelectBusquedaTree}
                cerrarModal={cerrarModalTree}
                seleccionModal={seleccionModalTree}
                maxDepth={5}
                carga_ListTree={() => { }}
                listatree={listCuentasCont}
            />

            <ModalBitacora
                contentLabel={''}
                Datos={Datos}
                cerrarModal={handleCerrarModalBi}
                showModal={selectModalBi}
            />

            <ModalDescripcionCarga
                selectedModal={selectedModalDesc}
                contentLabel={'spinnerModalProgress'}
                label={"Descripción del archivo xls:"}
                imgDescripcion={ImagenesRutas.DescExcel_CargaAsiento}
                cerrarModal={handleClickModal}
            />

        </Fragment>

    );

};

export default withRouter(memo(cargaAsientoExcel));