﻿import React, { Fragment, memo, useState, useEffect, } from 'react';
import { useHistory, withRouter } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faReply, faSave, faSearch, faFileWord, faList, faFolderPlus, faCalculator, faClipboardList } from '@fortawesome/free-solid-svg-icons';

import { SiteRutas } from '../../../request/RutasConfig.jsx';

import Config from '../../../components/Util/constantes.js';
import { Notificacion } from '../../../components/Util/Notificacion/Notificacion.jsx';
import ModalSpinner from '../../../components/UI/modalSpinner/modalSpinner.jsx';
import BotonArriba from '../../../components/UI/botonArriba/botonArriba.jsx';


import {
    farmatearMontos, validarDecimal, Round, farmatearFechaEstandar,
    itemSelect, validarIntVig, validaCuenta, datosArbol, validaCCosto
} from '../../../components/Util/Util.jsx';
import { useSessionStorage } from '../../../components/Util/Hooks/useSessionStorage.jsx';
import Swal from 'sweetalert2';
import { Type } from 'react-bootstrap-table2-editor';
import moment from 'moment';


import {
    TipoAsiento_Listar_Request, EncabezadoAsiento_ObtenerContador_Request,
    DetalleAsiento_Listar_Request, EncabezadoAsiento_Guardar_Request,
    EncabezadoAsiento_ObtenerAsiento_Request, DetallePlantillas_Listar_Request, EncaPlantillas_Consultar_Request,
    EncaPlantillas_Guardar_Request, EncaPlantillas_ModificarFechaAct_Request,
    Contabilidad_ObtenerContadorAsiento_Request, EncabezadoAsiento_Modificar_Request, EncabezadoAsiento_ModificarUtilizado_Request
} from '../../../request/MantenimientosRequest.jsx';
import { Catalogo_Lista_Request, CentroCosto_Lista_CCC_Request, CentroCosto_Lista_CXCC_Request, CentroCosto_Lista_CXCCEmpresa_Request, CentroCostos_CentroDefault_Request } from '../../../request/ServicioRequest.jsx';
import { Empresa_Consulta_Request } from "../../../request/SeguridadRequest.jsx";

import DetalleAsientoInt from './DetalleAsientoInt.jsx';
import ModalBitacora from './modalBitacora.jsx';
import { config } from '@fortawesome/fontawesome-svg-core';

function DetalleAsiento(props) {
    const pDatos = {
        Tipo: { value: "", attributes: { readOnly: true, focus: false, label: 'Número', hidden: "unset" } },
        Numero: { value: "0", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        Descripcion: { value: "", attributes: { readOnly: true, focus: false, label: 'Descripción', hidden: "unset", maxLength: 510 } },
        FechaAnio: { value: "0", attributes: { readOnly: true, focus: false, label: '\u00a0', hidden: "unset" } },
        FechaMes: { value: "", attributes: { readOnly: true, focus: false, label: 'Fecha', hidden: "unset" } },
        Monto: { value: 0, attributes: { readOnly: true, focus: false, label: 'Monto', hidden: "unset" } },
        NombrePl: { value: "", attributes: { readOnly: true, focus: false, label: 'Nombre', hidden: "unset" } },
        DescripcionPl: { value: "", attributes: { readOnly: true, focus: false, label: 'Descripción', hidden: "unset", maxLength: 255 } },
        TipoPl: { value: true, attributes: { readOnly: true, focus: false, label: 'Tipo', hidden: "unset" } },
        EstadoPl: { value: true, attributes: { readOnly: true, focus: false, label: 'Estado', hidden: "unset" } },
        DescripcionPlCk: { value: "", attributes: { readOnly: true, 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: true, focus: false, label: 'Montos', hidden: "unset" } },
        DocPorLineaPl: { value: true, attributes: { readOnly: true, focus: false, label: 'Doc. por línea', hidden: "unset" } },
        DescPorLineaPl: { value: true, attributes: { readOnly: true, focus: false, label: 'Desc. por línea', hidden: "unset" } },
        FechaPorLineaPl: { value: true, attributes: { readOnly: true, 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 spinner = { mostrar: false, texto: '', tipo: 3 };
    const [Datos, setDatos] = useState(pDatos);
    const [SpinnerModal, setSpinnerModal] = useState(spinner);
    const [empresa, setEmpresa] = useSessionStorage('empresaCON');
    const [empresaNombre, setEmpresaNombre] = useSessionStorage('empresaNombreCON');
    const [datosEmpresa, setDatosEmpresa] = useState(undefined);
    const [token, setToken] = useSessionStorage('tokenCON', '');
    const [usuario, setUsuario] = useSessionStorage('usuarioCON');
    const [usuarioS, setUsuarioS] = useSessionStorage('UsuarioSCON', '');
    const [Pais, setPais] = useSessionStorage('paisCON');
    const [id, setId] = useState(0);
    let historyMenu = useHistory();
    const [listaDatos, setListaDatos] = useState([]);
    const [listaTipo, setListaTipo] = useState([]);
    const [selectedTipo, setSelectedTipo] = useState(undefined);
    const listaMeses = Config.listaMeses;
    const [selectedOptionMes, setSelectedOptionMes] = useState(undefined);



    //Datos formulario
    const [pColumn, setPColumn] = useState(undefined);
    const [actTabla, setActTabla] = useState(false);
    const [filaSeleccionada, setFilaSeleccionada] = useState(undefined);
    const [listCuentas, setListCuentas] = useState([]);
    const [listCCosto, setListCCosto] = useState([]);
    const [listCXCC, setListCXCC] = useState([]);
    const [selectedCentroCosto, setSelectedCentroCosto] = useState(undefined);
    const tipoCreacion = [{ id: 1, value: 'Normal' }, { id: 2, value: 'De Plantilla' }, { id: 3, value: 'De Excel' }];
    const [selectedTipoCreacion, setSelectedTipoCreacion] = useState(tipoCreacion[0]);
    const [asiento, setAsiento] = useState(undefined);
    const [totalDebe, setTotalDebe] = useState(0);
    const [totalHaber, setTotalHaber] = useState(0);
    const [selectModalBi, setSelectModalBi] = useState(false);


    const columnas = [
        { dataField: 'llave', text: '', csvExport: false, hidden: true },
        { dataField: 'llave', text: '', csvExport: false, hidden: true },
        {
            dataField: 'CuentaStr', text: 'Cuenta', csvText: 'Cuenta', sort: true, footer: '',
            editable: false, 
        },
        { dataField: 'NombreCuenta', text: 'Nombre de Cuenta', sort: true, editable: false, footer: '', },
        { dataField: 'Centro_Costo', text: 'Centro Costo', hidden: true, csvExport: true, sort: true, editable: false, footer: '', },
        {
            dataField: 'Centro_CostoStr', text: 'Centro Costo', csvExport: false, sort: true, editable: false, footer: '',
        },
        {
            dataField: 'Fecha', text: 'Fecha', sort: true, editable: false, footer: '',
            formatter: (row, cell) => { return cell.Fecha !== '' ? farmatearFechaEstandar(cell.Fecha) : '' },
            editor: {
                type: Type.DATE
            }
        },
        {
            dataField: 'Documento', text: 'Documento', csvText: 'Documento', editable: false, sort: true, align: 'left', 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: false, 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', sort: true, csvText: 'Debe', headerAlign: 'right', formatter: (row, cell) => farmatearMontos(cell.Debe), hidden: false, editable: false, align: 'right',
            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', sort: true, csvText: 'Haber', headerAlign: 'right', hidden: false, editable: false, 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' },
        },];

    const botones = [
        { name: "btnVolver", clase: "btn btn-sm pull-right flipInX animated", evento: () => volverAtras(), leyenda: "", iclase: faReply, tooltip: "Volver" },
        { name: "btnBitacora", clase: "btn btn-sm pull-right flipInX animated", evento: () => handleBitacora(), leyenda: "", iclase: faClipboardList, tooltip: "Bitácora" },
    ];

    const botonesModif = [
        { name: "btnVolver", clase: "btn btn-sm pull-right flipInX animated", evento: () => volverAtras(), leyenda: "", iclase: faReply, tooltip: "Volver" },
        { name: "btnBitacora", clase: "btn btn-sm pull-right flipInX animated", evento: () => handleBitacora(), leyenda: "", iclase: faClipboardList, tooltip: "Bitácora" },
    ];


    const volverAtras = async () => {
        historyMenu.push(SiteRutas.Asientos);

        let _id = parseInt(props.match.params.id);

        if (_id > 0) {
            await CambiarUtilizado(_id, false);
        }

    }

    const spinnerModalMostrar = (mostrar, texto, tipo = 3) => {
        setSpinnerModal({ mostrar: mostrar, texto: texto, tipo: tipo });
    }


    //Seguridad


    const cargarTiposAsiento = async (_Datos, Periodo, cargarContador) => {

        const response = await TipoAsiento_Listar_Request(token, empresa);
        let lista = [];
        if (response.Exitoso) {
            if (Array.isArray(response.Datos) && response.Datos.length > 0) {
                lista = [...response.Datos].map(x => ({ value: x.ID, label: x.Nombre, mensual: x.Mensual }));
                setListaTipo(lista);

                setSelectedTipo(lista[0]);

                if (cargarContador) {
                    await obtenerContador(parseInt(_Datos.FechaAnio.value), Periodo.getMonth() + 1, lista[0], _Datos);
                }

            } else {
                Notificacion.error("No se encontraron datos para: Tipo de Asiento.");
                await volverAtras();
            }
        }
        else {
            Notificacion.error(response.Mensaje);
            await volverAtras();
        }
        return lista;
    }


    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 cargarDetalleAsiento = async (Asiento, Fecha) => {

        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);

                setListaDatos(_lista);

            } else {
                Notificacion.error(`${response.Mensaje}`);
                let _lista = [];
                _lista.push(item);
            }
        }
        else {
            Notificacion.error(response.Mensaje);
            if(response.Mensaje != 'No hay datos por mostrar.'){
                await volverAtras();
                return false
            }else{
                let _lista = [];
                _lista.push(item);
                setListaDatos(_lista);
                return true;
            }
        }
    }

    const cargarAsiento = async (Asiento, _Datos) => {

        let Fecha = new Date();
        let response = await EncabezadoAsiento_ObtenerAsiento_Request(token, Asiento);

        if (response.Exitoso) {
            let _asiento = { ...response.Datos };


                const _estado = _asiento.Estado;
                const _resultado = (_asiento.id > 0);

                if (_resultado) {

  

                            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.FechaMes.attributes.readOnly = true;
                            _Datos.FechaAnio.attributes.readOnly = true;
                            _Datos.Numero.value = response.Datos.Numero.toString().padStart(5, '0');
                            _Datos.FechaAnio.value = Fecha.getFullYear();
                            setSelectedOptionMes(itemSelect(Fecha.getMonth() + 1, listaMeses));
                            _Datos.Descripcion.value = response.Datos.Descripcion;

                            await cargarDetalleAsiento(Asiento, Fecha);

                            setDatos(_Datos);
                } else {
                    Notificacion.warning('No se encontró el Asiento.');
                    await volverAtras();
                }

        } else {
            Notificacion.error(response.Mensaje);
            await volverAtras();
        }

    }

    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 cargarDatos = async (limpiar = false) => {
        let _Datos = { ...Datos }
        let Periodo = null;

        try {
            spinnerModalMostrar(true, 'Cargando Datos');
            const _id = parseInt(props.match.params.id);

            setId(_id);

            let response = await Empresa_Consulta_Request(token, empresa);

            if (response.Exitoso) {
                setDatosEmpresa(response.Datos);
                Periodo = new Date(response.Datos.Periodo);
            } else {
                Notificacion.error(response.Mensaje);
                await volverAtras();
            }


            if (_id > 0) {
                await cargarAsiento(_id, _Datos);
            } 
            else {

                setSelectedTipoCreacion(tipoCreacion[0]);

                if (limpiar) {
                    _Datos.Descripcion.value = "";
                    setTotalDebe(0);
                    setTotalHaber(0);
                }

                if (parseInt(_Datos.FechaAnio.value) === 0) {
                    _Datos.FechaAnio.value = Periodo.getFullYear();
                    setSelectedOptionMes(itemSelect(Periodo.getMonth() + 1, listaMeses));
                    setDatos(_Datos);
                }

                const _listaTipo = await cargarTiposAsiento(_Datos, Periodo, true);
                ingresarDetalle(Periodo, limpiar);
                if (parseInt(_Datos.FechaAnio.value) === 0) {
                    _Datos.FechaAnio.value = Periodo.getFullYear();
                    setSelectedOptionMes(itemSelect(Periodo.getMonth() + 1, listaMeses));
                    setDatos(_Datos);
                }
            }

        } catch (ex) {
            Notificacion.error(ex.message);
        } finally {
            spinnerModalMostrar(false, '', 3);
        }

    }

    useEffect(() => {
        const carga = async () => {
            await cargarDatos()
        }
        carga()
    }, [])

    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 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();
            }
        } else {
            Periodo = new Date(datosEmpresa.Periodo);
            IniPeriodo = new Date(datosEmpresa.InicioPeriodo);
        }

        FinPeriodo = obtenerFinPeriodo(IniPeriodo);

        if (params.Fecha.getMonth() <= FinPeriodo.getMonth()) {
            if ((IniPeriodo.getMonth() + 1) === 1) {
                params.Inicio = new Date(params.Fecha.getFullYear(), IniPeriodo.getMonth(), 1);
                params.Fin = moment(new Date(params.Fecha.getFullYear() + 1, IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
            } else {
                params.Inicio = new Date(params.Fecha.getFullYear() - 1, IniPeriodo.getMonth(), 1);
                params.Fin = moment(new Date(params.Fecha.getFullYear(), IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
            }
        } else {
            params.Inicio = new Date(params.Fecha.getFullYear(), IniPeriodo.getMonth(), 1);
            params.Fin = moment(new Date(params.Fecha.getFullYear() + 1, IniPeriodo.getMonth(), 1)).add(-1, 'days').toDate();
        }

        return params;

    }

    const obtenerContador = async (Anio, Mes, selTipo = undefined, _Datos = undefined) => {

        let Nombre = '';
        let Periodo = new Date();

        if (_Datos === undefined) {
            _Datos = { ...Datos };
        }

        if (Anio === 0) {
            Periodo = moment(_Datos.FechaAnio.value.toString() + '/' + selectedOptionMes.value.toString().padStart(2, '0') + '/01').toDate();
        } else {
            Periodo = Periodo = moment(Anio.toString() + '/' + Mes.toString().padStart(2, '0') + '/01').toDate();
        }

        if (selTipo == undefined) {
            selTipo = selectedTipo;
        }

        if (selTipo.mensual) {
            Nombre = selTipo.label.trim() + '_' + moment(Periodo).format('MM');
        } else {
            Nombre = selTipo.label.trim() + '_01';
        }

        let Fechas = { Fecha: Periodo, Inicio: new Date(), Fin: new Date() };
        await buscarFronteras(Fechas);

        let response = await EncabezadoAsiento_ObtenerContador_Request(token, empresa, moment(Fechas.Inicio).format('YYYY/MM/DD'), Nombre);

        if (response.Exitoso) {
            const Numero = response.Datos.id;
            _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 siguienteContador = async () => {

        let Nombre = '';
        let Periodo = new Date();

        let _Datos = { ...Datos };

        Periodo = moment(_Datos.FechaAnio.value.toString() + '/' + (parseInt(selectedOptionMes.value) <= 9 ? '0' : '') + selectedOptionMes.value.toString() + '/01').toDate();

        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 handleSelectedTipo = async (selTipo) => {
        setSelectedTipo(selTipo);

        await obtenerContador(0, undefined, selTipo, undefined);

    }

    const onhandleSelectedOptionMes = async (SelOptionMes) => {
        setSelectedOptionMes(SelOptionMes);

        await obtenerContador(Datos.FechaAnio.value, SelOptionMes.value, selectedTipo, undefined);

    }

    const onhandleAnioChange = async (event) => {
        let _Datos = { ...Datos }

        const valido = validarIntVig(event.target.value);

        if (valido) {
            _Datos.FechaAnio.value = event.target.value;
            await obtenerContador(_Datos.FechaAnio.value, selectedOptionMes.value, selectedTipo, _Datos);
        }

    }

    const validarAnio = (ev) => {
        const text = /^[0-9]+$/;
        const year = ev.target.value;

        let _Datos = { ...Datos };

        if (
            ev.type == "blur" ||
            (year.length == 4 && ev.keyCode != 8 && ev.keyCode != 46)
        ) {
            if (year != 0) {
                const current_year = new Date().getFullYear();

                if (year != "" && !text.test(year)) {

                    _Datos.FechaAnio.value = current_year;

                    setDatos(_Datos);

                    Notificacion.warning("Debe ingresar un valor numérico.");

                    return false;
                }

                if (year.length != 4) {

                    _Datos.FechaAnio.value = current_year;
                    setDatos(_Datos);
                    Notificacion.warning("Debe ingresar un año válido.");

                    return false;
                }

                if (year < 1900 || year > current_year) {

                    _Datos.FechaAnio.value = current_year;

                    setDatos(_Datos);

                    Notificacion.warning("Debe ingresar un año válido.");

                    return false;
                }
                return true;
            }
        }
    }

    const validarSoloNumeros = (ev) => {
        const text = /^[0-9]+$/;

        const value = ev.target.value;

        if (ev.type == "blur" && ev.keyCode != 8 && ev.keyCode != 46) {
            if (value != "" && !text.test(value)) {
                Notificacion.warning("Debe ingresar un valor numérico.");
                return false;
            } else if (value == "") {
                return false;
            }
        }

        return true;
    }

    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 },
        });

        if (name === 'Descripcion') {
            let _listaDatos = [].concat(listaDatos);
            if (_listaDatos.length === 1) {
                _listaDatos[0].Referencia = value;
                setListaDatos(_listaDatos);
            }
        }

        setDatos(_Datos);

    }

    const onChangeInputPorMonto = (e) => {
        const name = e.target.name;
        const value = e.target.value;

        const valido = validarDecimal(value);

        if (valido) {

            let newAttributes = Datos[name].attributes;

            const _Datos = Object.assign({}, Datos, {
                [name]: {
                    value: value,
                    attributes: newAttributes,
                    id: name,
                    name: name,
                },
            });

            setDatos(_Datos);
        }
    }

    const onChangeEditar = (e) => {
        const name = e.target.name;

        const value = parseFloat(Datos[name].value.toString() === "" ? "0" : Datos[name].value.toString());
        let newAttributes = Datos[name].attributes;
        const _Editando = !newAttributes.Editando;
        newAttributes.Editando = _Editando;
        const _Datos = Object.assign({}, Datos, {
            [name]: { value: value, attributes: newAttributes },
        });
        if (_Editando) {
            e.target.type = "text";
            e.target.value = value;
            e.target.setSelectionRange(0, e.target.value.toString().length);
            e.target.type = "number";
        }

        setDatos(_Datos);
    }

    const onFormato = (valor) => {
        return farmatearMontos(valor);
    };

    const onRowSelect = (row) => {
        setFilaSeleccionada(row);
    };


    const selectRow = { onSelect: onRowSelect, hideSelectColumn: true, mode: "radio", clickToSelect: true, clickToEdit: true, bgColor: '#d73220', style: { color: '#ffffff' } };

    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(new Date(parseInt(Datos.FechaAnio.value), parseInt(selectedOptionMes.value) - 1, 1));
                }
            }
        },
    };


    const rowStyleLista = (row, rowIndex) => {
        const style = {};
        if (row.DebeGuardar == -1) {
            style.color = '#21aba0';
        } else {
            style.color = 'black';
        }

        return style;
    }

    const SumeMontos = (Debe) => {

        let Result = parseFloat(0);

        for (let i = 0; i < listaDatos.length - 1; i++) {
            if (Debe)
                Result = Result + parseFloat(listaDatos[i].Debe);
            else
                Result = Result + parseFloat(listaDatos[i].Haber);
        }
        return Result;
    }

    const handleCerrarModalBi = () => {
        setSelectModalBi(false);
    };



    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);

        }
    }

    return (<Fragment>
        <DetalleAsientoInt
            titulo={'Ver Asiento'}
            botones={botones}
            handleSelectedTipo={handleSelectedTipo}
            selectedTipo={selectedTipo}
            listaTipo={listaTipo}
            onhandleSelectedOptionMes={onhandleSelectedOptionMes}
            selectedOptionMes={selectedOptionMes}
            listaMeses={listaMeses}
            onhandleAnioChange={onhandleAnioChange}
            validarAnio={validarAnio}
            validarSoloNumeros={validarSoloNumeros}
            Datos={Datos}
            onChangeInput={onChangeInput}
            listaDatos={listaDatos}
            columnas={columnas}
            selectRow={selectRow}
            cellEdit={cellEdit}
            actTabla={false}
            rowStyleLista={rowStyleLista}
            pColumn={pColumn}
        />
        <BotonArriba Delay={10} Visible={100} />
        <ModalSpinner
            selectedModal={SpinnerModal.mostrar}
            contentLabel={'spinnerModalProgress'}
            label={SpinnerModal.texto}
            tipoSpinner={SpinnerModal.tipo}
        />
        <ModalBitacora
            contentLabel={''}
            Datos={Datos}
            cerrarModal={handleCerrarModalBi}
            showModal={selectModalBi}
        />
    </Fragment>)

};
export default withRouter(memo(DetalleAsiento));