
Imports System.Data.OleDb
Imports System.IO

Public Class frmResultadoTitularizacion
    Dim Estado As String = String.Empty
    Dim Codigo = Variables.Codigo
    Dim TitularizacionConsulta As New TitularizacionDAO
    Dim oDAOGeneral As New DAOGeneral
    Dim Operaciones As New Operaciones
    Dim IndexBase As Integer = 0
    Public FechaRedencion As Date = Date.Today.Date
    Private Sub txtRendimientoAntesISR_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtRendimientoIntereses_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtRendimientoGananciaPerdida_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtGananciaPerdidaTotal_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtCostosTotales_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtIngresosPorIntereses_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtGananciaPerdidaCapital_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtPrecioVenta_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtPrecioCompra_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtPlazo_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub txtValorNominal_Op_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub Label35_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblRendimientoDespuesISR_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblRendimientoAntesISR_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblRendimientoIntereses_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblRendimientoGananciaPerdida_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblGananciaPerdidaTotal_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblCostosTotales_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblIngresosPorIntereses_Op_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub label27_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Label26_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Label25_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Label24_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Label23_Click(sender As Object, e As EventArgs)

    End Sub



    Private Sub frmResultadoTitularizacion_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AgregarColumnasAmortCap()
        AgregarColumnasAmort()

        CargarTIT()
        CargarAmortCap()
        CargarAmort()

        ExisteInversion()
        ValidarExistencia()
        Formato()
        CargarIndexBase()

        DefinirVigencia()
    End Sub



    Sub CargarIndexBase()
        Dim Index As String = Variables.BaseTIT


        If Index = "0" Then
            IndexBase = CInt(Index)
        ElseIf Index = "1" Then
            IndexBase = CInt(Index)

        ElseIf Index = "2" Then
            IndexBase = CInt(Index)

        ElseIf Index = "3" Then
            IndexBase = CInt(Index)




        End If
    End Sub




    Function ExisteInversion()
        Dim Codigo As String = Variables.Codigo
        Dim TablaINV As String = "INV0"
        Dim TablaPINV As String = "PIN0"
        Dim General As New DAOGeneral
        Dim InvPro = Variables.InvPro



        If InvPro = "I" Then

            Dim INV0 As Boolean = General.ExisteTitulo(Codigo, TablaINV)
            If INV0 Then
                navNuevo.Visible = True
                Return True
            Else
                navNuevo.Visible = False
                Return False
            End If
        End If



        If InvPro = "P" Then
            Dim PINV0 As Boolean = General.ExisteTitulo(Codigo, TablaPINV)
            If PINV0 Then
                navNuevo.Visible = True
                Return True
            Else
                navNuevo.Visible = False
                Return False
            End If
        End If
        Return False
    End Function


    Sub AgregarColumnasAmortCap()
        Dim Correlativo, Fecha, CesionFlujo, AmortCapital, Interes, Amortizacion, Saldos, Vigente As New DataGridViewTextBoxColumn
        Correlativo.Name = " "
        Fecha.Name = "Fecha"
        CesionFlujo.Name = " Cesión de Flujo"
        AmortCapital.Name = "Amortizacion Capital "
        Interes.Name = "Interés"
        Amortizacion.Name = "Amortizacion"
        Saldos.Name = "Saldos"

    End Sub

    Sub ValidarExistencia()
        Dim General As New DAOGeneral
        Dim Codigo As String = Variables.Codigo
        Dim Tabla As String = String.Empty

        Tabla = "TIT0"

        Dim Existe As Boolean = General.ExisteTitulo(Codigo, Tabla)
        If (Existe) Then
            navNuevo.Enabled = False
            TbAmortizacion.Enabled = True
            navModificar.Enabled = True
            navEliminar.Enabled = True
        Else
            navNuevo.Enabled = True
            TbAmortizacion.Enabled = False
            navModificar.Enabled = False
            navEliminar.Enabled = False
        End If
        Estado = String.Empty
        btnTit0.Text = "Aceptar"
    End Sub


    Sub AgregarColumnasAmort()
        Dim Correlativo, Fecha, Dias, Cuota, AmortCapital, Interes, Saldos, Porcentaje, Vigente As New DataGridViewTextBoxColumn

        Correlativo.Name = "Correlativo"
        Fecha.Name = "Fecha"
        Dias.Name = "Dias"
        Cuota.Name = "Cuotas"
        AmortCapital.Name = "Amortizacion de Capital"
        Interes.Name = "Interés"
        Saldos.Name = "Saldos"
        Porcentaje.Name = "Porcentaje"
        Vigente.Name = "Vigente"



        Vigente.Visible = False


        dgvAmortizacion.Columns.Add(Correlativo)
        dgvAmortizacion.Columns.Add(Porcentaje)
        dgvAmortizacion.Columns.Add(Fecha)
        dgvAmortizacion.Columns.Add(Dias)
        dgvAmortizacion.Columns.Add(Cuota)
        dgvAmortizacion.Columns.Add(AmortCapital)
        dgvAmortizacion.Columns.Add(Interes)
        dgvAmortizacion.Columns.Add(Saldos)
        dgvAmortizacion.Columns.Add(Vigente)

    End Sub


    Function ColeccionesTIT()
        Dim coleccion As New Collection
        Dim Tasa, MontoCompra, MontoCompraPrimario As Double
        Dim FechaEmision As Date = Date.Now.Date
        FechaEmision = dtpFechaEmision.Value
        Tasa = CDec(txtTasaEmision.Text.ToString.Trim("%")) / 100
        MontoCompra = txtMontoCompraEmision.Text
        MontoCompraPrimario = txtMontoCompraPrimario.Text
        coleccion.Add(FechaEmision)
        coleccion.Add(Tasa)
        coleccion.Add(MontoCompra)
        coleccion.Add(MontoCompraPrimario)
        Return coleccion
    End Function

    Function ColeccionAmort(ByVal Index As Integer)
        Dim coleccion As New Collection

        Dim Correlativo, Fecha2, Dias, Cuota, AmortCap2, Interes2, Saldo2, Porcentaje, Vigente As String
        If Not coleccion.Count < 0 Then


            Correlativo = dgvAmortizacion.Rows(Index).Cells("Correlativo").Value
            Porcentaje = dgvAmortizacion.Rows(Index).Cells("Porcentaje").Value
            Fecha2 = dgvAmortizacion.Rows(Index).Cells("Fecha").Value
            Dias = dgvAmortizacion.Rows(Index).Cells("Dias").Value
            Cuota = dgvAmortizacion.Rows(Index).Cells("Cuotas").Value
            AmortCap2 = dgvAmortizacion.Rows(Index).Cells("Amortizacion de Capital").Value
            Interes2 = dgvAmortizacion.Rows(Index).Cells("Interés").Value
            Saldo2 = dgvAmortizacion.Rows(Index).Cells("Saldos").Value
            Vigente = dgvAmortizacion.Rows(Index).Cells("Vigente").Value

            If Vigente = "True" Then
                Vigente = "1"
            Else
                Vigente = "0"
            End If


            coleccion.Add(Correlativo)
            coleccion.Add(Fecha2)
            coleccion.Add(Dias)
            coleccion.Add(Cuota)
            coleccion.Add(AmortCap2)
            coleccion.Add(Interes2)
            coleccion.Add(Saldo2)
            coleccion.Add(Porcentaje)
            coleccion.Add(Vigente)
        End If
        Return coleccion
    End Function

    Private Sub navModificar_Click(sender As Object, e As EventArgs) Handles navModificar.Click
        btnTit0.Text = "Modificar"
        Estado = "M"
    End Sub

    Private Sub navNuevo_Click(sender As Object, e As EventArgs) Handles navNuevo.Click
        btnTit0.Text = "Nuevo"
        Estado = "N"
    End Sub

    Private Sub navEliminar_Click(sender As Object, e As EventArgs) Handles navEliminar.Click
        btnTit0.Text = "Eliminar"
        Estado = "B"
    End Sub

    Private Sub btnTit0_Click(sender As Object, e As EventArgs) Handles btnTit0.Click
        Dim codigo As String = Variables.Codigo
        Dim DatosAmortizacion As Collection = ColeccionesTIT()
        Dim Amortizacion As Dictionary(Of String, Collection) = coleccionNueva()

        If (Estado = "N") Then
            TitularizacionConsulta.ProcesoDatos(DatosAmortizacion, codigo, Amortizacion, "Nuevo")
        ElseIf (Estado = "M") Then
            TitularizacionConsulta.ProcesoDatos(DatosAmortizacion, codigo, Amortizacion, "Modificar")
        ElseIf (Estado = "B") Then
            EliminarTIT()

        End If

        ValidarExistencia()
    End Sub

    Sub NuevoTIT()
        Dim coleccion = ColeccionesTIT()
        TitularizacionConsulta.NuevaTIT(coleccion, Codigo)
    End Sub

    Sub NuevoAmortCap()

    End Sub



    Sub ModificarAmort()
        Dim i As Integer = 0
        Dim CantidadRegistrosDB = CanRegistros()

        While i < CantidadRegistrosDB


            Dim coleccion = ColeccionAmort(i)
            If (TitularizacionConsulta.ModificarAmort(coleccion, Codigo) Is Nothing) Then

                Exit Sub
            End If
            i += 1
        End While



        NuevoAmort(CantidadRegistrosDB)
    End Sub





    Sub NuevoAmort(ByVal Cantidad As Integer)

        Dim i As Integer = 0

        Dim Index = dgvAmortizacion.Rows.Count - 1

        i = Cantidad

        While i <= Index


            Dim coleccion = ColeccionAmort(i)
            If TitularizacionConsulta.NuevaAmort(coleccion, Codigo) Is Nothing Then

                Exit Sub
            End If



            i += 1
        End While
        MsgBox("Registro de ingresos actualizados")


    End Sub


    Function coleccionNueva()

        Dim i As Integer = 0

        Dim Index = dgvAmortizacion.Rows.Count - 1
        Dim diccionario As New Dictionary(Of String, Collection)


        While i <= Index


            Dim coleccion = ColeccionAmort(i)

            diccionario.Add(i, coleccion)


            i += 1
        End While


        Return diccionario
    End Function


    Function CanRegistros()
        Dim oDAOGeneral As New DAOGeneral


        Dim Codigo = Variables.Codigo
        Dim Cantidad As Integer = oDAOGeneral.CantidadRegistros(Codigo, "TIT2")

        Return Cantidad
    End Function


    Sub ModificarTIT()
        Dim coleccion = ColeccionesTIT()
        TitularizacionConsulta.ModificarTIT(coleccion, Codigo)
    End Sub

    Sub ModificarAmortCap()

    End Sub




    Sub EliminarTIT()
        Dim Eliminado As Boolean = TitularizacionConsulta.Eliminar(Codigo)
        If Eliminado Then
            dgvAmortizacion.Rows.Clear()
        End If
    End Sub

    Sub EliminarAmortCap()

    End Sub

    Sub EliminarAmort()
        Dim Correlativo = dgvAmortizacion.CurrentRow.Cells("Correlativo").Value
        TitularizacionConsulta.EliminarAmort(Codigo, Correlativo)
    End Sub

    Sub CargarTIT()
        Dim coleccion As Collection = TitularizacionConsulta.CargarTIT(Codigo)

        If (Not coleccion.Count = 0) Then



            dtpFechaEmision.Value = coleccion(1)
            txtTasaEmision.Text = CDec(coleccion(2)) * 100
            txtMontoCompraEmision.Text = coleccion(3)
            txtMontoCompraPrimario.Text = coleccion(4)
        End If
    End Sub

    Sub CargarAmortCap()


        Dim dr = TitularizacionConsulta.CargarAmortCap(Codigo)
        Dim Iterador As Integer = 0

        Dim ConvertirString As String
        While dr.Read
            ConvertirString = Format(dr("Fecha"), "dd/MM/yyyy")

        End While
    End Sub


    Sub CargarAmort()
        Dim dr = TitularizacionConsulta.CargarAmort(Codigo)
        Dim Iterador As Integer = 0

        Dim ConvertirString As String
        While dr.Read
            ConvertirString = Format(dr("Fecha"), "dd/MM/yyyy")
            Dim Vigente As String = dr("Vigente").ToString

            If String.IsNullOrEmpty(Vigente) Then
                Vigente = "1"
            End If
            If Vigente = "1" Then
                Vigente = "True"
            Else
                Vigente = "False"
            End If




            dgvAmortizacion.Rows.Add(dr("Correlativo"), dr("Porcentaje"), ConvertirString, dr("Dias"), dr("Cuota"), dr("AmortCap"), dr("Interes"), dr("Saldos"), Vigente)
        End While
    End Sub

    Private Sub btnAmortCap_Click(sender As Object, e As EventArgs)
        If (Estado = "N") Then
            NuevoAmortCap()
        ElseIf (Estado = "M") Then
            ModificarAmortCap()
        ElseIf (Estado = "B") Then
            EliminarAmortCap()
        End If
    End Sub

    Private Sub btnAmort_Click(sender As Object, e As EventArgs)
        If (Estado = "N") Then
            ModificarAmort()
        ElseIf (Estado = "M") Then
            ModificarAmort()
        ElseIf (Estado = "B") Then
            EliminarAmort()
        End If
    End Sub

    Function GenerarFecha()
        Dim Fecha As Date = Date.Now.Date

        Fecha = Format(Fecha, "dd/MM/yyyy")

        Return Fecha
    End Function

    Sub LLenarFechaAmortCap()
        Dim Fecha As String = GenerarFecha()


    End Sub

    Sub LLenarFechaAmort()
        Dim Cantidad As Integer = dgvAmortizacion.Rows.Count - 1
        Dim Index As Integer = 0
        Dim MesFijo As Date = dtpFechaEmision.Value
        Dim Periodicidad As String = Variables.PeriodicidadTIT
        Dim TipoPeriodicidad As Integer = 0
        If (Periodicidad = "M") Then
            TipoPeriodicidad = 1
        ElseIf (Periodicidad = "T") Then
            TipoPeriodicidad = 3
        ElseIf (Periodicidad = "S") Then
            TipoPeriodicidad = 6
        ElseIf (Periodicidad = "A") Then
            TipoPeriodicidad = 12
        Else
            TipoPeriodicidad = 1
        End If

        While Index <= Cantidad
            Dim FechaIni As Date = Date.Today.Date
            Dim Fecha = Format(FechaIni, "dd/MM/yyyy")
            Dim IndexAnterior As Integer = Index - 1
            If Index = 0 Then
                FechaIni = MesFijo
            Else
                FechaIni = dgvAmortizacion.Rows(IndexAnterior).Cells("Fecha").Value
            End If
            Fecha = Operaciones.Meses(TipoPeriodicidad, FechaIni, MesFijo)
            If (String.IsNullOrEmpty(dgvAmortizacion.Rows(Index).Cells("Fecha").Value)) Then
                dgvAmortizacion.Rows(Index).Cells("Fecha").Value = Format(CDate(Fecha), "dd/MM/yyyy")
            End If




            Index += 1
        End While
    End Sub

    Private Sub dgvAmortizacionCapital_CellClick(sender As Object, e As DataGridViewCellEventArgs)

        LLenarFechaAmortCap()

    End Sub

    Private Sub dgvAmortizacion_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvAmortizacion.CellClick

    End Sub




    Function CalcularSaldos(ByVal Posicion As Double, ByVal Emistot As Double, ByVal AmortCap As Double, ByVal PosicionAnterior As Integer)
        Dim Saldos As Double = 0
        If Posicion = 0 Then
            Saldos = Emistot - AmortCap
        ElseIf (Posicion > 0) Then

        End If
        Return Saldos
    End Function

    Function CalcularAmort(ByVal Total As Double, ByVal AmortCap As Double)
        Dim Amort As Double = 0
        If (Not Total = 0) Then
            Amort = AmortCap / Total
        End If
        Return Amort
    End Function



    Function CalcularInteres(ByVal CF As Double, ByVal AmortCap As Double)
        Dim Interes As Double = 0
        Interes = CF - AmortCap
        Return Interes
    End Function

    Sub CalculosAmort()
        Dim Cantidad = 0, Dias = 0, Fecha = Date.Now.Date, FechaEmis = Date.Now.Date, Cuota = 0.0, Amort = 0.0, Interes = 0.0, Saldo = 0.0, AmortPriTabla = 0.0, SaldoAnterior = 0.0, Posicion, PosicionAnterior, PosicionSiguiente
        Posicion = dgvAmortizacion.Rows.Count - 1



        FechaEmis = dtpFechaEmision.Value
        For index As Integer = 0 To Posicion




            PosicionAnterior = index - 1
            PosicionSiguiente = index + 1




            Fecha = dgvAmortizacion.Rows(index).Cells("Fecha").Value

            SaldoAnterior = CalculosSaldoAnterior(PosicionAnterior)
            Dias = CalculosDias(index, FechaEmis, Fecha, PosicionAnterior)
            Amort = CalculosAmort2(index, Posicion, AmortPriTabla)
            Interes = CalculosInteres2(index, SaldoAnterior, Dias, FechaEmis, Fecha, IndexBase)
            Saldo = CalcularSaldos2(index, SaldoAnterior, Amort)

            Cuota = Amort + Interes

            dgvAmortizacion.Rows(index).Cells("Dias").Value = Dias
            dgvAmortizacion.Rows(index).Cells("Cuotas").Value = Cuota
            dgvAmortizacion.Rows(index).Cells("Amortizacion de Capital").Value = Amort
            dgvAmortizacion.Rows(index).Cells("Interés").Value = Interes
            dgvAmortizacion.Rows(index).Cells("Saldos").Value = Saldo
            dgvAmortizacion.Rows(index).Cells("Vigente").Value = "True"
            FechaEmis = Fecha
        Next
    End Sub
    Function CalcularCuota(ByVal Amort As Double, ByVal Interes As Double)
        Dim Cuota As Double = 0
        Cuota = Amort + Interes
        Return Cuota
    End Function


    Function CalcularSaldos2(ByVal Posicion As Integer, ByVal SaldoAnterior As Double, ByVal Amort As Double)
        Dim Saldo As Double = 0
        If (Posicion = 0) Then
            Saldo = (CDec(txtMontoCompraEmision.Text)) - Amort
        ElseIf (Posicion > 0) Then
            Saldo = SaldoAnterior - Amort
        Else
            Saldo = 0
        End If
        Return Saldo
    End Function




    Function CalculosInteres2(ByVal Posicion As Integer, ByVal SaldoAnterior As Double, ByVal Dias As Integer, ByVal Fecha1 As Date, ByVal Fecha2 As Date, ByVal IndexBase As Integer)
        Dim Saldo As Double = 0
        Dim Tasa As Double = 0


        If (Posicion = 0) Then
            Saldo = CDec(txtMontoCompraEmision.Text)
        ElseIf (Posicion > 0) Then
            Saldo = (CDec(SaldoAnterior))
        Else
            Saldo = 0
        End If
        Tasa = CDec(txtTasaEmision.Text.ToString.Trim("%"))
        Dim Valor As Double = 0

        If (IndexBase = 0) Then
            Valor = (Saldo * (Tasa / 100) * Dias) / 360

            Return Valor
        ElseIf (IndexBase = 1) Then
            Dim PrOpc1 = 0.0, PrOpc2 = 0.0
            Dim DiasPrimeraFecha = 0, DiasSegundaFecha = 0
            DiasPrimeraFecha = Operaciones.DiasDespuesCambioPrimeraFecha366Varios(Fecha1, Fecha2)
            DiasSegundaFecha = Operaciones.DiasDespuesCambioPrimeraFecha365Varios(Fecha1, Fecha2)



            If (DiasPrimeraFecha > 0 And DiasSegundaFecha > 0) Then
                PrOpc1 = (Saldo * (Tasa / 100) * DiasPrimeraFecha) / 366
                PrOpc2 = (Saldo * (Tasa / 100) * DiasSegundaFecha) / 365

                Valor = PrOpc1 + PrOpc2
            ElseIf (Not DiasPrimeraFecha > 0 And DiasSegundaFecha > 0) Then
                Valor = (Saldo * (Tasa / 100) * DiasSegundaFecha) / 365


            ElseIf (DiasPrimeraFecha > 0 And Not DiasSegundaFecha > 0) Then
                Valor = (Saldo * (Tasa / 100) * DiasPrimeraFecha) / 366

            Else
                Valor = 0
            End If
            Return Valor
        ElseIf (IndexBase = 2) Then
            Dim PrOpc1 = 0.0, PrOpc2 = 0.0
            Dim DiasPrimeraFecha = 0, DiasSegundaFecha = 0
            DiasPrimeraFecha = Operaciones.DiasDespuesCambioPrimeraFecha360Bi(Fecha1, Fecha2)
            DiasSegundaFecha = Operaciones.DiasDespuesCambioPrimeraFecha360(Fecha1, Fecha2)

            If (DiasPrimeraFecha > 0 And DiasSegundaFecha > 0) Then
                PrOpc1 = (Saldo * (Tasa / 100) * DiasPrimeraFecha) / 366
                PrOpc2 = (Saldo * (Tasa / 100) * DiasSegundaFecha) / 365
                Valor = PrOpc1 + PrOpc2
            ElseIf (Not DiasPrimeraFecha > 0 And DiasSegundaFecha > 0) Then
                Valor = (Saldo * (Tasa / 100) * DiasSegundaFecha) / 365
            ElseIf (DiasPrimeraFecha > 0 And Not DiasSegundaFecha > 0) Then
                Valor = (Saldo * (Tasa / 100) * DiasPrimeraFecha) / 366
            Else
                Valor = 0
            End If
            Return Valor
        Else
            Dim PrOpc1 = 0.0, PrOpc2 = 0.0
            Dim DiasPrimeraFecha = 0, DiasSegundaFecha = 0
            DiasPrimeraFecha = Operaciones.DiasDespuesCambioPrimeraFecha366Varios(Fecha1, Fecha2)
            DiasSegundaFecha = Operaciones.DiasDespuesCambioPrimeraFecha365Varios(Fecha1, Fecha2)

            If (DiasPrimeraFecha > 0 And DiasSegundaFecha > 0) Then
                PrOpc1 = (Saldo * (Tasa / 100) * DiasPrimeraFecha) / 360
                PrOpc2 = (Saldo * (Tasa / 100) * DiasSegundaFecha) / 360
                Valor = PrOpc1 + PrOpc2
            ElseIf (Not DiasPrimeraFecha > 0 And DiasSegundaFecha > 0) Then
                Valor = (Saldo * (Tasa / 100) * DiasSegundaFecha) / 360
            ElseIf (DiasPrimeraFecha > 0 And Not DiasSegundaFecha > 0) Then
                Valor = (Saldo * (Tasa / 100) * DiasPrimeraFecha) / 360
            Else
                Valor = 0
            End If
            Return Valor

        End If
        Return Valor
    End Function



    Function CalculosAmort2(ByVal Index As Integer, ByVal Cantidad As Integer, ByVal AmortPriTabla As Double)
        Dim Amort As Double = 0

        AmortPriTabla = dgvAmortizacion.Rows(Index).Cells("Porcentaje").Value
        Amort = AmortPriTabla * CDec(txtMontoCompraPrimario.Text)

        Return Amort
    End Function




    Function CalculosDias(ByVal Posicion As Integer, ByVal FechaEmis As Date, ByVal Fecha As Date, ByVal PosicionAnterior As Integer)
        Dim Dias As Integer = 0
        If (Posicion = 0) Then
            Dias = DateDiff(DateInterval.Day, FechaEmis, Fecha)
        ElseIf (Posicion > 0) Then
            Dim FechaAnterior As Date = Date.Now.Date
            FechaAnterior = dgvAmortizacion.Rows(PosicionAnterior).Cells("Fecha").Value
            Dias = DateDiff(DateInterval.Day, FechaAnterior, Fecha)
        End If
        Return Dias
    End Function




    Function CalculosSaldoAnterior(ByVal PosicionAnterior As Integer)
        Dim SaldoAnterior As Double = 0
        If (PosicionAnterior >= 0) Then
            SaldoAnterior = dgvAmortizacion.Rows(PosicionAnterior).Cells("Saldos").Value
        End If
        Return SaldoAnterior
    End Function






    Private Sub dgvAmortizacionCapital_KeyUp(sender As Object, e As KeyEventArgs)


    End Sub

    Private Sub dgvAmortizacion_KeyUp(sender As Object, e As KeyEventArgs) Handles dgvAmortizacion.KeyUp

    End Sub

    Private Sub dgvAmortizacionCapital_CellContentClick(sender As Object, e As DataGridViewCellEventArgs)

    End Sub

    Private Sub dgvAmortizacionCapital_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs)

    End Sub

    Private Sub dgvAmortizacion_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvAmortizacion.CellEndEdit

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles TbAmortizacion.Click, btnExcel.Click
        CargarExcel()
    End Sub

    Sub CargarExcel()
        Dim result As DialogResult = OpenFileDialog1.ShowDialog()
        ' Test result.
        If result = System.Windows.Forms.DialogResult.OK Then
            ' Get the file name.
            Dim path As String = OpenFileDialog1.FileName
            Cargar(dgvAmortizacion, path, "Hoja1")
        End If
    End Sub

    Sub Cargar(ByVal dgView As DataGridView,
        ByVal SLibro As String,
        ByVal sHoja As String)
        Dim cs As String = "Provider=Microsoft.Jet.OLEDB.4.0;" &
                       "Data Source=" & SLibro & ";" &
                       "Extended Properties=""Excel 8.0;HDR=YES"""
        Try
            ' cadena de conexión  
            Dim cn As New OleDbConnection(cs)
            If Not System.IO.File.Exists(SLibro) Then
                MsgBox("No se encontró el Libro: " &
                        SLibro, MsgBoxStyle.Critical,
                        "Ruta inválida")
                Exit Sub
            End If

            Dim Conexion As New OleDbConnection(cs)
            Conexion.Open()
            ' se conecta con la hoja sheet 1  
            Dim dAdapter As New OleDbCommand("Select * From [" & sHoja & "$]", Conexion)
            Dim reader As OleDbDataReader = dAdapter.ExecuteReader()
            Dim Cantidad As Integer = dgvAmortizacion.Rows.Count
            Dim Correlativo As Integer = Cantidad
            While (reader.Read())
                Correlativo += 1
                dgvAmortizacion.Rows.Add(Correlativo, reader(0))
            End While
            reader.Close()
            LLenarFechaAmort()
            CalculosAmort()



            Variables.dgvAmortizacion = dgvAmortizacion
        Catch oMsg As Exception
            MsgBox(oMsg.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub dgvAmortizacion_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvAmortizacion.CellContentClick

    End Sub


    Sub Formato()
        If String.IsNullOrEmpty(txtEmisionTotal.Text.ToString) Then
            txtEmisionTotal.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtTasaEmision.Text.ToString) Then
            txtTasaEmision.Text = "0.0%"
        End If
        If String.IsNullOrEmpty(txtPeriodicidadEmision.Text.ToString) Then
            txtPeriodicidadEmision.Text = "0.0"

        End If

        If String.IsNullOrEmpty(txtPeriodosEmision.Text.ToString) Then
            txtPeriodosEmision.Text = "0.0"
        End If

        If String.IsNullOrEmpty(txtMontoCompraEmision.Text.ToString) Then
            txtMontoCompraEmision.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtMontoCompraPrimario.Text.ToString) Then
            txtMontoCompraPrimario.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtCesionFlujo1.Text.ToString) Then
            txtCesionFlujo1.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtCesionFlujo2.Text.ToString) Then
            txtCesionFlujo2.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtCesionFlujo3.Text.ToString) Then
            txtCesionFlujo3.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtCesionFlujo4.Text.ToString) Then
            txtCesionFlujo4.Text = "0.0"
        End If
        If String.IsNullOrEmpty(txtCesionFlujo5.Text.ToString) Then
            txtCesionFlujo5.Text = "0.0"
        End If

        If txtTasaEmision.Text.ToString.IndexOf("%") = -1 Then
            txtTasaEmision.Text = txtTasaEmision.Text.ToString + "%"
        End If


    End Sub

    Private Sub txtEmisionTotal_TextChanged(sender As Object, e As EventArgs) Handles txtEmisionTotal.TextChanged

    End Sub

    Private Sub txtTasaEmision_TextChanged(sender As Object, e As EventArgs) Handles txtTasaEmision.TextChanged

    End Sub

    Private Sub txtPeriodicidadEmision_TextChanged(sender As Object, e As EventArgs) Handles txtPeriodicidadEmision.TextChanged

    End Sub

    Private Sub txtPeriodosEmision_TextChanged(sender As Object, e As EventArgs) Handles txtPeriodosEmision.TextChanged

    End Sub

    Private Sub txtMontoCompraEmision_TextChanged(sender As Object, e As EventArgs) Handles txtMontoCompraEmision.TextChanged

    End Sub

    Private Sub txtMontoCompraPrimario_TextChanged(sender As Object, e As EventArgs) Handles txtMontoCompraPrimario.TextChanged

    End Sub

    Private Sub txtCesionFlujo1_TextChanged(sender As Object, e As EventArgs) Handles txtCesionFlujo1.TextChanged

    End Sub

    Private Sub txtCesionFlujo2_TextChanged(sender As Object, e As EventArgs) Handles txtCesionFlujo2.TextChanged

    End Sub

    Private Sub esionFlujo3_TextChanged(sender As Object, e As EventArgs) Handles txtCesionFlujo3.TextChanged

    End Sub

    Private Sub txtCesionFlujo4_TextChanged(sender As Object, e As EventArgs) Handles txtCesionFlujo4.TextChanged

    End Sub

    Private Sub txtCesionFlujo5_TextChanged(sender As Object, e As EventArgs) Handles txtCesionFlujo5.TextChanged

    End Sub

    Private Sub txtEmisionTotal_Leave(sender As Object, e As EventArgs) Handles txtEmisionTotal.Leave
        Formato()
    End Sub

    Private Sub dtpFechaEmision_ValueChanged(sender As Object, e As EventArgs) Handles dtpFechaEmision.ValueChanged
        Formato()

    End Sub

    Private Sub txtTasaEmision_Leave(sender As Object, e As EventArgs) Handles txtTasaEmision.Leave
        Formato()
    End Sub

    Private Sub txtPeriodicidadEmision_Leave(sender As Object, e As EventArgs) Handles txtPeriodicidadEmision.Leave
        Formato()
    End Sub

    Private Sub txtPeriodosEmision_Leave(sender As Object, e As EventArgs) Handles txtPeriodosEmision.Leave
        Formato()
    End Sub

    Private Sub txtMontoCompraEmision_Leave(sender As Object, e As EventArgs) Handles txtMontoCompraEmision.Leave
        Formato()
    End Sub

    Private Sub txtMontoCompraPrimario_Leave(sender As Object, e As EventArgs) Handles txtMontoCompraPrimario.Leave
        Formato()
    End Sub

    Private Sub txtCesionFlujo1_Leave(sender As Object, e As EventArgs) Handles txtCesionFlujo1.Leave
        Formato()
    End Sub

    Private Sub txtCesionFlujo2_Leave(sender As Object, e As EventArgs) Handles txtCesionFlujo2.Leave
        Formato()
    End Sub

    Private Sub txtCesionFlujo3_Leave(sender As Object, e As EventArgs) Handles txtCesionFlujo3.Leave
        Formato()
    End Sub

    Private Sub txtCesionFlujo4_Leave(sender As Object, e As EventArgs) Handles txtCesionFlujo4.Leave
        Formato()
    End Sub

    Private Sub txtCesionFlujo5_Leave(sender As Object, e As EventArgs) Handles txtCesionFlujo5.Leave
        Formato()
    End Sub

    Private Sub txtEmisionTotal_KeyUp(sender As Object, e As KeyEventArgs) Handles txtEmisionTotal.KeyUp
        If txtEmisionTotal.Text = "." Then
            txtEmisionTotal.Text = ".0"
        End If
    End Sub

    Private Sub txtTasaEmision_KeyUp(sender As Object, e As KeyEventArgs) Handles txtTasaEmision.KeyUp
        If txtTasaEmision.Text = "." Then
            txtTasaEmision.Text = ".0%"
        End If
    End Sub

    Private Sub txtPeriodicidadEmision_KeyUp(sender As Object, e As KeyEventArgs) Handles txtPeriodicidadEmision.KeyUp
        If txtPeriodicidadEmision.Text = "." Then
            txtPeriodicidadEmision.Text = ".0"
        End If
    End Sub

    Private Sub txtPeriodosEmision_KeyUp(sender As Object, e As KeyEventArgs) Handles txtPeriodosEmision.KeyUp
        If txtPeriodosEmision.Text = "." Then
            txtPeriodosEmision.Text = ".0"
        End If
    End Sub

    Private Sub txtMontoCompraEmision_KeyUp(sender As Object, e As KeyEventArgs) Handles txtMontoCompraEmision.KeyUp
        If txtMontoCompraEmision.Text = "." Then
            txtMontoCompraEmision.Text = ".0"
        End If
    End Sub

    Private Sub txtMontoCompraPrimario_KeyUp(sender As Object, e As KeyEventArgs) Handles txtMontoCompraPrimario.KeyUp
        If txtMontoCompraPrimario.Text = "." Then
            txtMontoCompraPrimario.Text = ".0"
        End If
    End Sub

    Private Sub txtCesionFlujo1_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCesionFlujo1.KeyUp
        If txtCesionFlujo1.Text = "." Then
            txtCesionFlujo1.Text = ".0"
        End If
    End Sub

    Private Sub txtCesionFlujo2_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCesionFlujo2.KeyUp
        If txtCesionFlujo2.Text = "." Then
            txtCesionFlujo2.Text = ".0"
        End If
    End Sub

    Private Sub txtCesionFlujo3_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCesionFlujo3.KeyUp
        If txtCesionFlujo3.Text = "." Then
            txtCesionFlujo3.Text = ".0"
        End If
    End Sub

    Private Sub txtCesionFlujo4_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCesionFlujo4.KeyUp
        If txtCesionFlujo4.Text = "." Then
            txtCesionFlujo4.Text = ".0"
        End If
    End Sub

    Private Sub txtCesionFlujo5_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCesionFlujo5.KeyUp
        If txtCesionFlujo5.Text = "." Then
            txtCesionFlujo5.Text = ".0"
        End If
    End Sub

    Private Sub txtEmisionTotal_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEmisionTotal.KeyPress
        If String.IsNullOrEmpty(txtEmisionTotal.Text) Then
            If e.KeyChar = "." Then
                txtEmisionTotal.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtEmisionTotal.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtTasaEmision_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtTasaEmision.KeyPress
        If String.IsNullOrEmpty(txtTasaEmision.Text) Then
            If e.KeyChar = "." Then
                txtTasaEmision.Text = "0%"
                Exit Sub
            End If
        End If

        If (Not txtTasaEmision.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtPeriodicidadEmision_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPeriodicidadEmision.KeyPress
        If String.IsNullOrEmpty(txtPeriodicidadEmision.Text) Then
            If e.KeyChar = "." Then
                txtPeriodicidadEmision.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtPeriodicidadEmision.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtPeriodosEmision_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPeriodosEmision.KeyPress
        If String.IsNullOrEmpty(txtPeriodosEmision.Text) Then
            If e.KeyChar = "." Then
                txtPeriodosEmision.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtPeriodosEmision.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtMontoCompraEmision_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtMontoCompraEmision.KeyPress
        If String.IsNullOrEmpty(txtMontoCompraEmision.Text) Then
            If e.KeyChar = "." Then
                txtMontoCompraEmision.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtMontoCompraEmision.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtMontoCompraPrimario_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtMontoCompraPrimario.KeyPress
        If String.IsNullOrEmpty(txtMontoCompraPrimario.Text) Then
            If e.KeyChar = "." Then
                txtMontoCompraPrimario.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtMontoCompraPrimario.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtCesionFlujo1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCesionFlujo1.KeyPress
        If String.IsNullOrEmpty(txtCesionFlujo1.Text) Then
            If e.KeyChar = "." Then
                txtCesionFlujo1.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtCesionFlujo1.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtCesionFlujo2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCesionFlujo2.KeyPress
        If String.IsNullOrEmpty(txtCesionFlujo2.Text) Then
            If e.KeyChar = "." Then
                txtCesionFlujo2.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtCesionFlujo2.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtCesionFlujo3_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCesionFlujo3.KeyPress
        If String.IsNullOrEmpty(txtCesionFlujo3.Text) Then
            If e.KeyChar = "." Then
                txtCesionFlujo3.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtCesionFlujo3.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtCesionFlujo4_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCesionFlujo4.KeyPress
        If String.IsNullOrEmpty(txtCesionFlujo4.Text) Then
            If e.KeyChar = "." Then
                txtCesionFlujo4.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtCesionFlujo4.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub txtCesionFlujo5_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCesionFlujo5.KeyPress
        If String.IsNullOrEmpty(txtCesionFlujo5.Text) Then
            If e.KeyChar = "." Then
                txtCesionFlujo5.Text = "0"
                Exit Sub
            End If
        End If

        If (Not txtCesionFlujo5.Text.ToString.IndexOf(".") = -1 And e.KeyChar = ".") Then
            Operaciones.ValidarEntrada(sender, e, True)

        Else

            Operaciones.ValidarEntrada(sender, e, False)

        End If
    End Sub

    Private Sub TbGenerales_Click(sender As Object, e As EventArgs) Handles TbGenerales.Click

    End Sub



    Private Sub txtCantidadPeriodo_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub cboPeriodoGracia_SelectedIndexChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub BindingNavigator1_RefreshItems(sender As Object, e As EventArgs) Handles BindingNavigator1.RefreshItems

    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs)
        CargarIndexBase()
    End Sub

    Private Sub Panel2_Paint(sender As Object, e As PaintEventArgs) Handles Panel2.Paint

    End Sub

    Function BuscarPosicion()
        Dim FechaRedencionBuscar As Date = FechaRedencion
        Dim Posicion As Integer = -1
        Dim Cantidad As Integer = dgvAmortizacion.Rows.Count - 1
        Dim Index As Integer = 0
        Dim CantidadDiasFinal As Integer = 0
        Dim ExisteFecha As Boolean = False
        Dim Diccionario As New Dictionary(Of String, String)
        While Index <= Cantidad
            Dim Fecha As Date = dgvAmortizacion.Rows(Index).Cells("Fecha").Value
            Dim Correlativo = dgvAmortizacion.Rows(Index).Cells("Correlativo").Value
            Dim CantidadDias = dgvAmortizacion.Rows(Index).Cells("Dias").Value

            Dim InicioBucle As Integer = 0


            If IsNumeric(Correlativo) And IsNumeric(CantidadDias) Then

                Dim FechaBucle As Date = Fecha
                While InicioBucle < CantidadDias

                    Dim FechaRedencionBuscar_Limpia As String = Format(FechaRedencionBuscar, "yyyy/MM/dd")
                    Dim FechaBucle_Limpia As String = Format(FechaBucle, "yyyy/MM/dd")

                    If FechaRedencionBuscar_Limpia = FechaBucle_Limpia Then
                        Posicion = Correlativo - 1
                        ExisteFecha = True
                        CantidadDiasFinal = InicioBucle
                        Exit While
                    Else
                        FechaBucle = FechaBucle.AddDays(-1)
                    End If




                    InicioBucle += 1
                End While




            End If

            Index += 1
        End While

        Diccionario.Add("Existencia", ExisteFecha)
        Diccionario.Add("Posicion", Posicion)
        Diccionario.Add("DiasAtras", CantidadDiasFinal)

        Return Diccionario
    End Function

    Sub CorteRedencion()
        Dim ListaValidacion As New Dictionary(Of String, String)
        ListaValidacion = BuscarPosicion()

        Dim Existencia As Boolean = False
        Dim Posicion As Integer = -1
        Dim DiasAtras As Integer = 0

        For Each Valores In ListaValidacion
            If Valores.Key = "Existencia" Then
                Existencia = Valores.Value
            ElseIf Valores.Key = "Posicion" Then

                Posicion = Valores.Value

            ElseIf Valores.Key = "DiasAtras" Then
                DiasAtras = Valores.Value
            End If
        Next


        If Existencia Then
            Dim PosicionActual As Integer = Posicion + 1
            Dim PrimeraMitad As String = PosicionActual.ToString + ".1"
            Dim SegundaMitad As String = PosicionActual.ToString + ".2"
            Dim PosicionPrimera As Integer = Posicion
            Dim PosicionSegunda = Posicion + 1
            Dim FechaPosicionAnterior As Date = dgvAmortizacion.Rows(Posicion).Cells("Fecha").Value
            Dim DiasPosicionAnterior As Integer = dgvAmortizacion.Rows(Posicion).Cells("Dias").Value
            Dim Porcentaje As Double = dgvAmortizacion.Rows(Posicion).Cells("Porcentaje").Value

            Dim PrimeraFecha As Date = FechaPosicionAnterior.AddDays((DiasAtras) * -1)
            Dim SegundaFecha As Date = FechaPosicionAnterior


            dgvAmortizacion.Rows.Insert(PosicionSegunda, New DataGridViewRow)
            dgvAmortizacion.Rows(PosicionPrimera).Cells("Correlativo").Value = PrimeraMitad
            dgvAmortizacion.Rows(PosicionSegunda).Cells("Correlativo").Value = SegundaMitad

            dgvAmortizacion.Rows(PosicionPrimera).Cells("Porcentaje").Value = Porcentaje
            dgvAmortizacion.Rows(PosicionSegunda).Cells("Porcentaje").Value = Porcentaje



            dgvAmortizacion.Rows(PosicionPrimera).Cells("Dias").Value = DiasPosicionAnterior - DiasAtras
            dgvAmortizacion.Rows(PosicionSegunda).Cells("Dias").Value = DiasAtras


            dgvAmortizacion.Rows(PosicionPrimera).Cells("Fecha").Value = Format(PrimeraFecha, "dd/MM/yyyy")
            dgvAmortizacion.Rows(PosicionSegunda).Cells("Fecha").Value = Format(SegundaFecha, "dd/MM/yyyy")

            CalculosAmortRedencion(PosicionPrimera, FechaPosicionAnterior, DiasPosicionAnterior, DiasAtras, "iniciales")
            CalculosAmortRedencion(PosicionSegunda, FechaPosicionAnterior, DiasPosicionAnterior, DiasAtras, "finales")

            CambiarFilas(PosicionSegunda)
        End If

    End Sub
    Sub CambiarFilas(ByVal IndexAnterior As Double)
        Dim Index As Integer = Math.Truncate(IndexAnterior)
        Dim Cantidad As Integer = dgvAmortizacion.Rows.Count - 1

        While Index <= Cantidad
            dgvAmortizacion.Rows(Index).DefaultCellStyle.BackColor = Color.LightGray
            dgvAmortizacion.Rows(Index).DefaultCellStyle.ForeColor = Color.Maroon

            Index += 1
        End While
        DefinirVigencia()
    End Sub

    Sub DefinirVigencia()
        Dim Index As Integer = 0
        Dim Cantidad As Integer = dgvAmortizacion.Rows.Count - 1

        While Index <= Cantidad
            Dim Vigente As String = dgvAmortizacion.Rows(Index).Cells("Vigente").Value

            If Vigente = "False" Then
                dgvAmortizacion.Rows(Index).DefaultCellStyle.BackColor = Color.LightGray
                dgvAmortizacion.Rows(Index).DefaultCellStyle.ForeColor = Color.Maroon
            End If


            Index += 1
        End While
    End Sub

    Sub CalculosAmortRedencion(ByVal Index As Integer, ByVal Fecha As Date, ByVal DiasTotales As Integer, ByVal DiasCortos As Integer, ByVal TipoDias As String)
        Dim Cantidad = 0, Dias = 0, FechaEmis = Date.Now.Date, Cuota = 0.0, Amort = 0.0, Interes = 0.0, Saldo = 0.0, AmortPriTabla = 0.0, SaldoAnterior = 0.0, Posicion, PosicionAnterior, PosicionSiguiente
        Posicion = dgvAmortizacion.Rows.Count - 1
        Dim FechaCalculo As Date = Date.Today.Date
        Dim PrimerosDias As Integer = DiasTotales - DiasCortos
        Dim SegundosDias As Integer = DiasCortos
        Dim DiasTotalesNegativos As Integer = DiasTotales * -1
        Dim FechaFin As Date = Date.Today.Date
        
        If TipoDias = "iniciales" Then
            FechaCalculo = Fecha.AddDays(DiasTotalesNegativos)
            Fecha = FechaCalculo
            FechaCalculo = FechaCalculo.AddDays(PrimerosDias)

            FechaEmis = Fecha
            FechaFin = FechaCalculo



            Dias = DiasTotales - DiasCortos
            PosicionAnterior = Index - 1
            PosicionSiguiente = Index + 1
            Fecha = FechaCalculo
            SaldoAnterior = CalculosSaldoAnterior(PosicionAnterior)

            If IsNumeric(dgvAmortizacion.Rows(PosicionAnterior).Cells("Saldos").Value) Then
                Amort = dgvAmortizacion.Rows(PosicionAnterior).Cells("Saldos").Value
            End If



            Interes = CalculosInteres2(Index, SaldoAnterior, Dias, FechaEmis, FechaFin, IndexBase)
                Saldo = CalcularSaldos2(Index, SaldoAnterior, Amort)

                Cuota = Amort + Interes


                dgvAmortizacion.Rows(Index).Cells("Cuotas").Value = Cuota
                dgvAmortizacion.Rows(Index).Cells("Amortizacion de Capital").Value = Amort
                dgvAmortizacion.Rows(Index).Cells("Interés").Value = Interes
                dgvAmortizacion.Rows(Index).Cells("Saldos").Value = Saldo
            Else
                FechaCalculo = Fecha.AddDays((SegundosDias * -1))


            FechaEmis = FechaCalculo
            FechaFin = Fecha

            Dias = DiasCortos















            PosicionAnterior = Index - 2

            Fecha = FechaCalculo
            SaldoAnterior = CalculosSaldoAnterior(PosicionAnterior)


            Amort = CalculosAmort2(Index, Posicion, AmortPriTabla)




            Interes = CalculosInteres2(Index, SaldoAnterior, Dias, FechaEmis, FechaFin, IndexBase)
            Saldo = CalcularSaldos2(Index, SaldoAnterior, Amort)

            Cuota = Amort + Interes


                dgvAmortizacion.Rows(Index).Cells("Cuotas").Value = Cuota
                dgvAmortizacion.Rows(Index).Cells("Amortizacion de Capital").Value = Amort
                dgvAmortizacion.Rows(Index).Cells("Interés").Value = Interes
                dgvAmortizacion.Rows(Index).Cells("Saldos").Value = Saldo
            End If








    End Sub

    Sub Redencion()

        Dim FormularioRedencion As New Form
        Dim FechaRedencion As New DateTimePicker
        Dim TextoFecha As New Label
        Dim BotonFecha As New Button



        FormularioRedencion.Name = "frmFechaRedencion"
        FormularioRedencion.Text = "Buscar Fecha de Redencion"
        FormularioRedencion.Width = 250
        FormularioRedencion.Height = 250
        FormularioRedencion.StartPosition = FormStartPosition.CenterParent



        TextoFecha.Name = "lblfecha"
        TextoFecha.Text = "Ingresar una fecha"
        TextoFecha.Location = New Point(80, 25)




        FechaRedencion.Name = "dtpFechaRedencion"
        FechaRedencion.Width = FormularioRedencion.Width - 100
        FechaRedencion.Location = New Point(50, 50)
        FechaRedencion.Format = DateTimePickerFormat.Short
        AddHandler FechaRedencion.ValueChanged, AddressOf EventOperarFecha



        BotonFecha.Name = "btnfecha"
        BotonFecha.Text = "Aceptar"
        BotonFecha.Location = New Point(90, 100)
        AddHandler BotonFecha.Click, AddressOf EventAceptar



        FormularioRedencion.Controls.Add(TextoFecha)
        FormularioRedencion.Controls.Add(FechaRedencion)
        FormularioRedencion.Controls.Add(BotonFecha)
        FormularioRedencion.Show()
    End Sub




    Sub EventOperarFecha(sender As Object, e As EventArgs)
        FechaRedencion = sender.value
    End Sub


    Sub EventAceptar(sender As Object, e As EventArgs)
        Dim Nombre As Form = sender.parent
 
        Nombre.close()
        CorteRedencion()
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Redencion()
    End Sub

    Private Sub btnLimpiar_Click(sender As Object, e As EventArgs) Handles btnLimpiar.Click
        dgvAmortizacion.Rows.Clear()
    End Sub
End Class



