#Region "Comisiones"
    Public ReadOnly Property PorcentajeComisionRecargoExterno As Double
        Get
            Return If(Me.RecargoExterno.HasValue = False OrElse Me.RecargoExterno = 0 OrElse Me.AsegasaRecargoExterno.HasValue = False OrElse Me.AsegasaRecargoExterno.Value = 0, 0, Math.Round(Me.AsegasaRecargoExterno.Value * 100 / Me.RecargoExterno.Value, 2, MidpointRounding.AwayFromZero))
        End Get
    End Property
    Public ReadOnly Property PorcentajeComisionConsorcio As Double
        Get
            Return If(Me.Consorcio.HasValue = False OrElse Me.Consorcio = 0 OrElse Me.AsegasaComisionConsorcio.HasValue = False OrElse Me.AsegasaComisionConsorcio.Value = 0, 0, Math.Round(Me.AsegasaComisionConsorcio.Value * 100 / Me.Consorcio.Value, 2, MidpointRounding.AwayFromZero))
        End Get
    End Property
    Public ReadOnly Property PorcentajeComisionAsegasa As Double
        Get
            Return If(Me.TotalComision.HasValue = False OrElse Me.TotalComision = 0 OrElse Me.AsegasaComisionTotal.HasValue = False, 0, Math.Round(Me.AsegasaComisionTotal.Value * 100 / Me.TotalComision.Value, 2, MidpointRounding.AwayFromZero))
        End Get
    End Property


    Public Function ObtieneDatosComisiones() As List(Of DatoComision)
        Try
            Dim ldcs As New List(Of DatoComision)
            Dim dc As New DatoComision
            With dc
                .Concepto = "Prima Neta"
                .Base = Math.Round(PrimaNeta.Value + BonificacionORecargo.Value, 2, MidpointRounding.AwayFromZero)
                .Porcentaje = Math.Round(PorcentajeReciboPrimaNeta.Value, 2, MidpointRounding.AwayFromZero)
                .ComisionBruta = Math.Round(ComisionReciboPrimaNeta.Value, 2, MidpointRounding.AwayFromZero)
                .Sobrecomision = Math.Round(Sobrecomision.NothingA0, 2, MidpointRounding.AwayFromZero)
                .TotalComision = Math.Round(TotalComision.Value, 2, MidpointRounding.AwayFromZero)
                .PorcentajeComisionPrevista = Math.Round(PorcentajeComisionPrevista.Value, 2, MidpointRounding.AwayFromZero)
                .ComisionPrevista = Math.Round(ComisionPrevista.Value, 2, MidpointRounding.AwayFromZero)
                .Diferencia = Math.Round(.ComisionBruta - ComisionPrevista.Value, 2, MidpointRounding.AwayFromZero)
            End With
            ldcs.Add(dc)

            Dim dcre As New DatoComision
            With dcre
                .Concepto = "Recargos Externos"
                .Base = Math.Round(RecargoExterno.Value, 2, MidpointRounding.AwayFromZero)
                .Porcentaje = Math.Round(PorcentajeComisionRecargoExterno, 2, MidpointRounding.AwayFromZero)
                .Sobrecomision = 0
                .TotalComision = Math.Round(AsegasaRecargoExterno.Value, 2, MidpointRounding.AwayFromZero)
                ' .ComisionBruta = Math.Round(.TotalComision - .Sobrecomision, 2, MidpointRounding.AwayFromZero)
                .ComisionBruta = Math.Round(.TotalComision, 2, MidpointRounding.AwayFromZero)
                .PorcentajeComisionPrevista = .Porcentaje
                .ComisionPrevista = .TotalComision
                .Diferencia = Math.Round(.TotalComision - .ComisionPrevista, 2, MidpointRounding.AwayFromZero)
            End With
            ldcs.Add(dcre)
            Dim dcco As New DatoComision
            With dcco
                .Concepto = "Consorcio"
                .Base = Math.Round(Consorcio.Value, 2, MidpointRounding.AwayFromZero)
                .Porcentaje = Math.Round(PorcentajeComisionConsorcio, 2, MidpointRounding.AwayFromZero)
                .Sobrecomision = 0
                .TotalComision = Math.Round(AsegasaComisionConsorcio.Value, 2, MidpointRounding.AwayFromZero)
                ' .ComisionBruta = Math.Round(.TotalComision - .Sobrecomision, 2, MidpointRounding.AwayFromZero)
                .ComisionBruta = Math.Round(.TotalComision, 2, MidpointRounding.AwayFromZero)
                .PorcentajeComisionPrevista = .Porcentaje
                .ComisionPrevista = .TotalComision
                .Diferencia = Math.Round(.TotalComision - .ComisionPrevista, 2, MidpointRounding.AwayFromZero)
            End With
            ldcs.Add(dcco)
            Dim dcag As New DatoComision
            With dcag
                .Concepto = "AGENTE"
                .Base = Math.Round(BaseComisionAgente.Value, 2, MidpointRounding.AwayFromZero)
                .Porcentaje = Math.Round(PorcentajeComisionAgente.Value, 2, MidpointRounding.AwayFromZero)
                .Sobrecomision = 0
                .TotalComision = Math.Round(ComisionAgente.Value, 2, MidpointRounding.AwayFromZero)
                '  .ComisionBruta = Math.Round(.TotalComision - .Sobrecomision, 2, MidpointRounding.AwayFromZero)
                .ComisionBruta = Math.Round(.TotalComision, 2, MidpointRounding.AwayFromZero)
                .PorcentajeComisionPrevista = .Porcentaje
                .ComisionPrevista = .TotalComision
                .Diferencia = Math.Round(.TotalComision - .ComisionPrevista, 2, MidpointRounding.AwayFromZero)
            End With
            ldcs.Add(dcag)
            Dim dcAS As New DatoComision
            With dcAS
                .Concepto = "ASEGASA"
                .Base = Math.Round(TotalComision.Value, 2, MidpointRounding.AwayFromZero)
                .Porcentaje = Math.Round(PorcentajeComisionAsegasa, 2, MidpointRounding.AwayFromZero)
                .ComisionBruta = Math.Round(AsegasaComisionTotal.Value, 2, MidpointRounding.AwayFromZero)
                .Sobrecomision = Math.Round(Sobrecomision.NothingA0, 2, MidpointRounding.AwayFromZero)
                .TotalComision = Math.Round(AsegasaComisionTotal.Value + Sobrecomision.NothingA0, 2, MidpointRounding.AwayFromZero)
                .PorcentajeComisionPrevista = .Porcentaje
                .ComisionPrevista = .TotalComision
                .Diferencia = Math.Round(.ComisionBruta - .ComisionPrevista, 2, MidpointRounding.AwayFromZero)
            End With
            ldcs.Add(dcAS)
            Return ldcs
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Function

    Public Shared Sub ImportaRecibosPatriaHispana(bd As bdGestionAsegasa.gestionasegasaEntities, Lrai As List(Of ReciboAIncorporar), ByRef iNumfic As Integer, NumTotFics As Integer, Ficheros As List(Of ficheroscompanias), Busqueda As String, MostrarProgreso As Boolean, GuardarCambios As Boolean, MarcarFicheros As Boolean, Optional ByRef ListadoRecibosDuplicados As List(Of String) = Nothing)
        Try
            If MostrarProgreso Then
                '  DXSplashScreen.Show(Of SplashScreenTecnosis)()
                DXSplashScreen.SetState("Incorporando recibos de PATRIA HISPANA ...")
            End If
            '        Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContextoCN()
            Dim cia = bd.companias.First(Function(x) x.Codigo = "0037")
            '    Dim TipoRecibo As Integer = bdGestionAsegasa.ficheroscompanias.TipoFicheroCompania.RECIBOS_EIAC
            '  Dim lrai As New List(Of bdGestionAsegasa.ReciboAIncorporar)
            '        Dim FICS = bd.ficheroscompanias.Where(Function(x) x.FechaProcesado Is Nothing And x.FechaError Is Nothing And x.idCompania = cia.idCompania And x.Tipo = TipoRecibo).OrderBy(Function(x) x.FechaCreacion).ToList
            If Ficheros.Count > 0 Then
                Dim ldur = bd.enumeraciones.Where(Function(x) x.gruposenumeraciones.Grupo = "DUR").ToList
                '     Dim idTipoPagoCIA = bd.enumeraciones.First(Function(X) X.Codigo = "TIPP.CIA").idEnumeracion
                Dim TiposRecibos = bd.enumeraciones.Where(Function(x) x.gruposenumeraciones.Grupo = "TRC").ToList
                Dim pols = bd.polizassg.Include("entidadespolizas.entidades").Where(Function(x) x.idCompania = cia.idCompania).ToList
                Dim recs = bd.recibos.Where(Function(x) x.polizassg.idCompania = cia.idCompania).Select(Function(x) New With {.idRecibo = x.idRecibo, .Codigorecibo = x.CodigoRecibo, .NumeroRecibo = x.NumeroRecibo, .idPoliza = x.idPoliza, .NumeroPoliza = x.polizassg.NumeroPoliza, .NumeroSuplemento = x.polizassg.NumeroSuplemento, .FechaEfecto = x.FechaEfecto, .FechaVencimiento = x.FechaVencimiento, .FechaBaja = x.FechaBaja, .FechaFacturacion = x.FechaFacturacion}).ToList
                Dim agentes = bd.agentes.ToList
                Dim subagentes = bd.subagentes.ToList
                Dim ramos = bd.ramos.ToList
                Dim comsCia = bd.comisionescompanias.Where(Function(x) x.idCompania = cia.idCompania).ToList
                Dim comsAge = bd.comisionesagentes.ToList
                '   Dim iNumfic = 0
                '   Dim iNumfics = Ficheros.Count
                '   Dim recsai As New List(Of recibos)

                For Each f In Ficheros
                    If MostrarProgreso Then
                        DXSplashScreen.SetState("Comprobando " & f.NombreFichero)
                    End If
                    iNumfic += 1
                    Try

                        'Catch ex As Exception

                        'End Try
                        '   Dim DatosEIAC As ProcesosEIAC_V5.ProcesosEIAC = tsl5.Utilidades.Deserializa(f.Fichero, GetType(ProcesosEIAC_V5.ProcesosEIAC))
                        Dim iNumrec As Integer = 0
                        '  If DatosEIAC.Objetos IsNot Nothing AndAlso DatosEIAC.Objetos.Items IsNot Nothing Then

                        '  Dim lrecibos = DatosEIAC.Objetos.Items.Where(Function(x) x.GetType Is GetType(bdGestionAsegasa.tipo_recibo)).Cast(Of bdGestionAsegasa.tipo_recibo)
                        ' Dim iNumRecs = lrecibos.Count

                        Dim clsReader As System.IO.TextReader = New StreamReader(New MemoryStream(f.Fichero))
                        Dim sLine As String = clsReader.ReadLine
                        Do Until sLine Is Nothing


                            Dim npo = sLine.Substring(7, 7)
                            Dim nre = sLine.Substring(14, 9)
                            Dim Pne = CDbl(sLine.Substring(29, 11)) / 100
                            Dim Pnerc = Pne
                            Dim Bon = 0
                            Dim Con = CDbl(sLine.Substring(40, 9)) / 100
                            Dim Conrc = Con
                            Dim Ipu = CDbl(sLine.Substring(49, 9)) / 100
                            Dim Ipurc = Ipu
                            '  Dim Fecoc As Date
                            Dim Tipp As String = ""
                            Dim Pneom As Double = 0
                            Dim Conom As Double = 0
                            Dim Ipuom As Double = 0
                            Dim Pneoc As Double = 0
                            Dim Conoc As Double = 0
                            Dim Ipuoc As Double = 0
                            Dim Fef As Date
                            Dim Fve As Date
                            Dim Imp = Pne + Con + Ipu


                            If sLine.Trim.Length <= 200 Then
                                Fef = New Date(CInt(sLine.Substring(82, 4)), CInt(sLine.Substring(80, 2)), CInt(sLine.Substring(78, 2))) ' Recibo.DatosRecibo.Fechas.FechaEfectoActual
                                Fve = New Date(CInt(sLine.Substring(90, 4)), CInt(sLine.Substring(88, 2)), CInt(sLine.Substring(86, 2))) ' Recibo.DatosRecibo.Fechas.FechaVencimi
                                '   Fecoc = Fef
                                Tipp = sLine.Substring(94, 1)
                            Else
                                Fef = New Date(CInt(sLine.Substring(93, 4)), CInt(sLine.Substring(91, 2)), CInt(sLine.Substring(89, 2))) ' Recibo.DatosRecibo.Fechas.FechaEfectoActual
                                Fve = New Date(CInt(sLine.Substring(101, 4)), CInt(sLine.Substring(99, 2)), CInt(sLine.Substring(97, 2))) ' Recibo.DatosRecibo.Fechas.FechaVencimiento
                                '    Fecoc = New Date(CInt(sLine.Substring(234, 4)), CInt(sLine.Substring(230, 2)), CInt(sLine.Substring(228, 2)))
                                Pneom = CDbl(sLine.Substring(105, 11)) / 100
                                Conom = CDbl(sLine.Substring(116, 9)) / 100
                                Ipuom = CDbl(sLine.Substring(125, 9)) / 100
                                Pneoc = CDbl(sLine.Substring(181, 11)) / 100
                                Conoc = CDbl(sLine.Substring(192, 9)) / 100
                                Ipuoc = CDbl(sLine.Substring(201, 9)) / 100
                                Pne = Pnerc + Pneom + Pneoc
                                Con = Conrc + Conom + Conoc
                                Ipu = Ipurc + Ipuom + Ipuoc
                                Imp = Pne + Con + Ipu
                                Tipp = sLine.Substring(248, 1)
                            End If








                            '  For Each Recibo In lrecibos
                            Dim bIncluir As Boolean = False
                            If f.idFichero = 2584 Then Debug.WriteLine("aqui")
                            If Busqueda <> "" Then
                                If npo.Contains(Busqueda) Or nre.Contains(Busqueda) Then
                                    bIncluir = True
                                End If
                            Else
                                bIncluir = True
                            End If
                            If bIncluir Then
                                Try
                                    iNumrec += 1
                                    Dim cre = cia.Codigo & "/" & nre
                                    Dim ir As bdGestionAsegasa.ReciboAIncorporar
                                    ir = Lrai.FirstOrDefault(Function(x) x.Código_Recibo = cre And x.Correcto)
                                    If ir Is Nothing Then
                                        ir = New bdGestionAsegasa.ReciboAIncorporar
                                        Lrai.Add(ir)
                                    End If
                                    ir.Correcto = False
                                    ir.Fecha_Efecto = Fef
                                    ir.Fecha_Vencimiento = Fve
                                    ir.Número_Fichero = f.idFichero
                                    ir.Fecha_Fichero = f.FechaCreacion
                                    ir.Fecha_Procesado = f.FechaProcesado
                                    ir.Usuario_Procesado = If(f.usuarios IsNot Nothing, f.usuarios.Nombre, "")
                                    ir.Código_Cia = f.companias.Codigo
                                    ir.idCompañia = f.idCompania
                                    ir.Código_Recibo = cre
                                    If MostrarProgreso Then DXSplashScreen.SetState("Incorporando Recibos. Fichero (" & iNumfic.ToString & "/" & NumTotFics.ToString & "). " & "Recibo (" & iNumrec.ToString & "): " & ir.Código_Recibo)
                                    Dim pol As polizassg

                                    pol = pols.Where(Function(x) x.NumeroPoliza = npo And x.FechaBaja.HasValue = False And x.companias.Codigo = cia.Codigo And x.RechazoSuplemento = False).OrderByDescending(Function(x) x.NumeroSuplemento).FirstOrDefault
                                    If pol Is Nothing Then
                                        If npo.Substring(0, 1) = "0" Then
                                            npo = npo.Substring(1)
                                            pol = pols.Where(Function(x) x.NumeroPoliza = npo And x.FechaBaja.HasValue = False And x.companias.Codigo = cia.Codigo And x.RechazoSuplemento = False).OrderByDescending(Function(x) x.NumeroSuplemento).FirstOrDefault
                                        End If
                                    End If
                                    If pol Is Nothing Then pol = pols.Where(Function(x) x.NumeroPoliza = npo And x.companias.Codigo = cia.Codigo And x.RechazoSuplemento = False).OrderByDescending(Function(x) x.NumeroSuplemento).FirstOrDefault
                                    ir.Número_Póliza = npo

                                    Dim idTipoRecibo As Integer


                                    If Imp < 0 Then
                                        idTipoRecibo = TiposRecibos.First(Function(x) x.Codigo = "TRC.CX").idEnumeracion
                                    Else
                                        idTipoRecibo = TiposRecibos.First(Function(x) x.Codigo = "TRC.C").idEnumeracion
                                    End If
                                    ir.Tipo = TiposRecibos.First(Function(X) X.idEnumeracion = idTipoRecibo).Descripcion

                                    If pol IsNot Nothing Then
                                        ir.Observaciones = pol.Observaciones
                                        ir.Tipo_Pago = pol.TipoPago
                                        ir.Forma_Pago_Recibida = "DESCONOCIDA"
                                        ir.Situacion_Recibo = "DESCONOCIDA"
                                        If Not Lrai.Any(Function(x) x.Código_Recibo = ir.Código_Recibo And x.Correcto) Then
                                            Dim Rec = recs.Where(Function(x) x.Codigorecibo = ir.Código_Recibo).FirstOrDefault
                                            If Rec Is Nothing Then
                                                If ir.Fecha_Efecto.AddMonths(1) > Today Then
                                                    Dim recant = recs.FirstOrDefault(Function(X) X.idPoliza = pol.idPoliza And X.FechaEfecto = ir.Fecha_Efecto And X.FechaVencimiento = ir.Fecha_Vencimiento And X.Codigorecibo <> ir.Código_Recibo)
                                                    Dim recantFichs = Lrai.Where(Function(x) x.Poliza IsNot Nothing).FirstOrDefault(Function(x) x.Poliza.idPoliza = pol.idPoliza And x.Fecha_Efecto = ir.Fecha_Efecto And x.Fecha_Vencimiento = ir.Fecha_Vencimiento And x.Código_Recibo <> ir.Código_Recibo)
                                                    If (recant Is Nothing AndAlso recantFichs Is Nothing) OrElse (recant IsNot Nothing AndAlso (recant.FechaEfecto.AddMonths(1) > Date.Today And nre.Contains(recant.NumeroRecibo) = False)) Then
                                                        If Imp <> 0 Then
                                                            ir.Mensaje = "Recibo Correcto"
                                                        Else
                                                            ir.Mensaje = "Recibo con Prima Neta = 0"
                                                        End If
                                                        ir.Correcto = True
                                                        ir.Corregible = True
                                                        RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                                        If recant IsNot Nothing Then
                                                            If recant.FechaFacturacion.HasValue Then
                                                                ir.Mensaje = "Existe otro recibo facturado de la misma póliza con el mismo efecto y vencimiento (" & recant.Codigorecibo & ")"
                                                            Else
                                                                ir.Mensaje = "Existe otro recibo de la misma póliza con el mismo efecto y vencimiento (" & recant.Codigorecibo & ")"
                                                                If ListadoRecibosDuplicados IsNot Nothing Then ListadoRecibosDuplicados.Add(recant.Codigorecibo)
                                                            End If
                                                        End If
                                                    Else
                                                        ir.Correcto = False
                                                        ir.Corregible = True
                                                        RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                                        If recant Is Nothing Then
                                                            ir.Mensaje = "Existe otro recibo de la misma póliza con el mismo efecto y vencimiento en otro fichero (F.Efecto Anterior a un Mes) (" & recantFichs.Código_Recibo & ")"
                                                        Else
                                                            ir.Mensaje = "Existe otro recibo de la misma póliza con el mismo efecto y vencimiento (F.Efecto Anterior a un Mes) (" & recant.Codigorecibo & ")"
                                                        End If
                                                    End If
                                                Else
                                                    ir.Correcto = False
                                                    ir.Corregible = True
                                                    RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                                    ir.Mensaje = "Recibo Con fecha de efecto anterior a la permitida."
                                                End If
                                            Else
                                                If Now.Subtract(Rec.FechaEfecto).TotalDays > 365 Then
                                                    ir.Mensaje = "Recibo ya existente (Anterior a un año)"
                                                Else
                                                    ir.Mensaje = "Recibo ya existente"
                                                End If
                                                ir.Correcto = False
                                                ir.Corregible = False
                                                RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                            End If
                                        Else
                                            '  ir.Correcto = False
                                            '  ir.Corregible = False
                                            RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False, True)
                                            '   ir.Mensaje = "Recibo Duplicado en el fichero"
                                        End If
                                        ir.Tomador = pol.Tomador.RazonSocial
                                        ir.Matrícula = pol.Matricula
                                        ir.Bienes_Asegurados = pol.BienesAsegurados
                                        ir.Agente = agentes.First(Function(x) x.idAgente = pol.idAgente).Nombre
                                        ir.Subagente = If(pol.idSubAgente.HasValue = False, "", subagentes.First(Function(x) x.idSubagente = pol.idSubAgente.Value).Nombre)
                                        ir.Ramo = ramos.First(Function(x) x.idRamo = pol.idRamo).Descripcion
                                        ir.IBAN = pol.IBAN

                                        ir.Comisión = ir.Comisión_Prevista_ASEGASA
                                        ir.Sobrecomisión = 0
                                    Else
                                        ir.Correcto = False
                                        ir.Corregible = False
                                        ir.Mensaje = "Póliza no encontrada"
                                    End If
                                Catch ex As Exception
                                    Throw New Exception("Error Incorporando Recibo: " & nre & " Póliza: " & npo, ex)
                                End Try
                            End If
                            sLine = clsReader.ReadLine
                        Loop
                        '    End If
                    Catch ex As Exception
                        Throw New Exception("Error Incorporando " & f.NombreFichero & " Compañia: " & "0037", ex)
                    End Try
                Next
                If GuardarCambios Then
                    Dim rcc = Lrai.Where(Function(x) x.Correcto).ToList
                    Dim rnp = Lrai.Where(Function(x) x.Correcto = False).ToList
                    ' Dim raa = lrai.Where(Function(x) x.Actualizado).ToList
                    If MarcarFicheros Then
                        GuardaRecibosEIAC(bd, Lrai, Nothing, Nothing, Nothing, MostrarProgreso, Ficheros, comsCia, comsAge, ldur)
                    Else
                        GuardaRecibosEIAC(bd, Lrai, Nothing, Nothing, Nothing, MostrarProgreso, Nothing, comsCia, comsAge, ldur)
                    End If
                    GeneraEmailRecibosIncorporados(Lrai, Nothing, rnp, Nothing, Nothing)
                End If
            End If
            'If MostrarProgreso Then
            '    DXSplashScreen.Close()
            'End If
            '     Return lrai
        Catch EX As Exception
            If MostrarProgreso AndAlso DXSplashScreen.IsActive Then DXSplashScreen.Close()
            Throw New Exception(EX.Message, EX) '  bdGestionAsegasa.Utilidades.AñadeLog(TipoLog.Fallo, "En ImportaRecibosEIAC " & Compañia, EX.Message, EX)
        End Try
    End Sub
    Public Shared Sub ImportaRecibosPrevisionMallorquina(bd As bdGestionAsegasa.gestionasegasaEntities, Lrai As List(Of ReciboAIncorporar), ByRef iNumfic As Integer, NumTotFics As Integer, Ficheros As List(Of ficheroscompanias), Busqueda As String, MostrarProgreso As Boolean, GuardarCambios As Boolean, MarcarFicheros As Boolean, Optional ByRef ListadoRecibosDuplicados As List(Of String) = Nothing)
        Try
            If MostrarProgreso Then
                ' DXSplashScreen.Show(Of SplashScreenTecnosis)()
                DXSplashScreen.SetState("Incorporando recibos de PREVISION MALLORQUINA ...")
            End If
            Dim cia = bd.companias.First(Function(x) x.Codigo = "0024")
            If Ficheros.Count > 0 Then
                Dim ldur = bd.enumeraciones.Where(Function(x) x.gruposenumeraciones.Grupo = "DUR").ToList
                Dim idTipoPagoCIA = bd.enumeraciones.First(Function(X) X.Codigo = "TIPP.CIA").idEnumeracion
                Dim TiposRecibos = bd.enumeraciones.Where(Function(x) x.gruposenumeraciones.Grupo = "TRC").ToList
                Dim pols = bd.polizassg.Include("entidadespolizas.entidades").Where(Function(x) x.idCompania = cia.idCompania).ToList
                Dim recs = bd.recibos.Where(Function(x) x.polizassg.idCompania = cia.idCompania).Select(Function(x) New With {.idRecibo = x.idRecibo, .Codigorecibo = x.CodigoRecibo, .NumeroRecibo = x.NumeroRecibo, .idPoliza = x.idPoliza, .NumeroPoliza = x.polizassg.NumeroPoliza, .NumeroSuplemento = x.polizassg.NumeroSuplemento, .FechaEfecto = x.FechaEfecto, .FechaVencimiento = x.FechaVencimiento, .FechaBaja = x.FechaBaja, .FechaFacturacion = x.FechaFacturacion}).ToList
                Dim agentes = bd.agentes.ToList
                Dim subagentes = bd.subagentes.ToList
                Dim ramos = bd.ramos.ToList
                Dim comsCia = bd.comisionescompanias.Where(Function(x) x.idCompania = cia.idCompania).ToList
                Dim comsAge = bd.comisionesagentes.ToList

                For Each f In Ficheros
                    If MostrarProgreso Then
                        DXSplashScreen.SetState("Comprobando " & f.NombreFichero)
                    End If
                    iNumfic += 1
                    Try
                        Dim iNumrec As Integer = 0
                        Dim wb As New Workbook
                        wb.LoadDocument(f.Fichero, DevExpress.Spreadsheet.DocumentFormat.Xlsx)
                        Dim i As Integer = 2
                        If wb.Worksheets(0).Cells("A3").Value.ToString = "Mediador" Then i = 4
                        Do Until wb.Worksheets(0).Cells("A" & i.ToString).Value.ToString = ""
                            Dim npo = wb.Worksheets(0).Cells("D" & i.ToString).Value.ToString.Replace("'", "").Trim
                            Dim nre = wb.Worksheets(0).Cells("N" & i.ToString).Value.ToString.Replace("'", "").Trim
                            Dim Pne = wb.Worksheets(0).Cells("J" & i.ToString).Value.NumericValue
                            Dim Pnerc = Pne
                            Dim Bon = 0
                            Dim Con = wb.Worksheets(0).Cells("K" & i.ToString).Value.NumericValue
                            ' Dim Conrc = Con
                            Dim Ipu = 0
                            Dim Ipurc = Ipu
                            Dim Pneom As Double = 0
                            Dim Conom As Double = 0
                            Dim Ipuom As Double = 0
                            Dim Pneoc As Double = 0
                            Dim Conoc As Double = 0
                            Dim Ipuoc As Double = 0
                            Dim Fef As Date
                            Dim Fve As Date
                            Dim Imp = Pne + Con + Ipu
                            Fef = tsl5.Extensiones.StringExtensions.FechaStringADate(wb.Worksheets(0).Cells("F" & i.ToString).Value.ToString, False)
                            Fve = Fef.AddYears(1)
                            Dim bIncluir As Boolean = False
                            If f.idFichero = 2584 Then Debug.WriteLine("aqui")
                            If Busqueda <> "" Then
                                If npo.Contains(Busqueda) Or nre.Contains(Busqueda) Then
                                    bIncluir = True
                                End If
                            Else
                                bIncluir = True
                            End If
                            If bIncluir Then
                                Try
                                    iNumrec += 1
                                    Dim ir As New bdGestionAsegasa.ReciboAIncorporar
                                    Lrai.Add(ir)
                                    ir.Correcto = False
                                    ir.Fecha_Efecto = Fef
                                    ir.Fecha_Vencimiento = Fve
                                    ir.Número_Fichero = f.idFichero
                                    ir.Fecha_Fichero = f.FechaCreacion
                                    ir.Fecha_Procesado = f.FechaProcesado
                                    ir.Usuario_Procesado = If(f.usuarios IsNot Nothing, f.usuarios.Nombre, "")
                                    ir.Código_Cia = f.companias.Codigo
                                    ir.idCompañia = f.idCompania
                                    ir.Código_Recibo = cia.Codigo & "/" & nre
                                    If MostrarProgreso Then DXSplashScreen.SetState("Incorporando Recibos. Fichero (" & iNumfic.ToString & "/" & NumTotFics.ToString & "). " & "Recibo (" & iNumrec.ToString & "): " & ir.Código_Recibo)
                                    Dim pol As polizassg
                                    pol = pols.Where(Function(x) x.NumeroPoliza = npo And x.FechaBaja.HasValue = False And x.companias.Codigo = cia.Codigo And x.RechazoSuplemento = False).OrderByDescending(Function(x) x.NumeroSuplemento).FirstOrDefault
                                    If pol Is Nothing Then
                                        If npo.Substring(0, 1) = "0" Then
                                            npo = npo.Substring(1)
                                            pol = pols.Where(Function(x) x.NumeroPoliza = npo And x.FechaBaja.HasValue = False And x.companias.Codigo = cia.Codigo And x.RechazoSuplemento = False).OrderByDescending(Function(x) x.NumeroSuplemento).FirstOrDefault
                                        End If
                                    End If
                                    If pol Is Nothing Then pol = pols.Where(Function(x) x.NumeroPoliza = npo And x.companias.Codigo = cia.Codigo And x.RechazoSuplemento = False).OrderByDescending(Function(x) x.NumeroSuplemento).FirstOrDefault
                                    ir.Número_Póliza = npo

                                    Dim idTipoRecibo As Integer


                                    If Imp < 0 Then
                                        idTipoRecibo = TiposRecibos.First(Function(x) x.Codigo = "TRC.CX").idEnumeracion
                                    Else
                                        idTipoRecibo = TiposRecibos.First(Function(x) x.Codigo = "TRC.C").idEnumeracion
                                    End If
                                    ir.Tipo = TiposRecibos.First(Function(X) X.idEnumeracion = idTipoRecibo).Descripcion

                                    If pol IsNot Nothing Then
                                        ir.Observaciones = pol.Observaciones
                                        ' columna n fecha de pago y tipo de pago siempre cia
                                        '   If r.Situacion_Recibo = "COBRADO" AndAlso r.Forma_Pago_Recibida = "CUENTA BANCARIA" AndAlso r.Fecha_Situacion.HasValue Then
                                        ir.Tipo_Pago = idTipoPagoCIA
                                        pol.idTipoPago = idTipoPagoCIA
                                        ir.Forma_Pago_Recibida = "CUENTA BANCARIA"
                                        ir.Situacion_Recibo = "COBRADO"
                                        ir.Fecha_Situacion = Now
                                        If Not Lrai.Any(Function(x) x.Código_Recibo = ir.Código_Recibo And x.Correcto) Then
                                            Dim Rec = recs.Where(Function(x) x.Codigorecibo = ir.Código_Recibo).FirstOrDefault
                                            If Rec Is Nothing Then
                                                If ir.Fecha_Efecto.AddMonths(1) > Today Then
                                                    Dim recant = recs.FirstOrDefault(Function(X) X.idPoliza = pol.idPoliza And X.FechaEfecto = ir.Fecha_Efecto And X.FechaVencimiento = ir.Fecha_Vencimiento And X.Codigorecibo <> ir.Código_Recibo)
                                                    Dim recantFichs = Lrai.Where(Function(x) x.Poliza IsNot Nothing).FirstOrDefault(Function(x) x.Poliza.idPoliza = pol.idPoliza And x.Fecha_Efecto = ir.Fecha_Efecto And x.Fecha_Vencimiento = ir.Fecha_Vencimiento And x.Código_Recibo <> ir.Código_Recibo)
                                                    If (recant Is Nothing AndAlso recantFichs Is Nothing) OrElse (recant IsNot Nothing AndAlso (recant.FechaEfecto.AddMonths(1) > Date.Today And nre.Contains(recant.NumeroRecibo) = False)) Then
                                                        If Imp <> 0 Then
                                                            ir.Mensaje = "Recibo Correcto"
                                                        Else
                                                            ir.Mensaje = "Recibo con Prima Neta = 0"
                                                        End If
                                                        ir.Correcto = True
                                                        ir.Corregible = True
                                                        RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                                        If recant IsNot Nothing Then
                                                            If recant.FechaFacturacion.HasValue Then
                                                                ir.Mensaje = "Existe otro recibo facturado de la misma póliza con el mismo efecto y vencimiento (" & recant.Codigorecibo & ")"
                                                            Else
                                                                ir.Mensaje = "Existe otro recibo de la misma póliza con el mismo efecto y vencimiento (" & recant.Codigorecibo & ")"
                                                                If ListadoRecibosDuplicados IsNot Nothing Then ListadoRecibosDuplicados.Add(recant.Codigorecibo)
                                                            End If
                                                        End If
                                                    Else
                                                        ir.Correcto = False
                                                        ir.Corregible = True
                                                        RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                                        If recant Is Nothing Then
                                                            ir.Mensaje = "Existe otro recibo de la misma póliza con el mismo efecto y vencimiento en otro fichero (F.Efecto Anterior a un Mes) (" & recantFichs.Código_Recibo & ")"
                                                        Else
                                                            ir.Mensaje = "Existe otro recibo de la misma póliza con el mismo efecto y vencimiento (F.Efecto Anterior a un Mes) (" & recant.Codigorecibo & ")"
                                                        End If
                                                    End If
                                                Else
                                                    ir.Correcto = False
                                                    ir.Corregible = True
                                                    RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                                    ir.Mensaje = "Recibo Con fecha de efecto anterior a la permitida."
                                                End If
                                            Else
                                                If Now.Subtract(Rec.FechaEfecto).TotalDays > 365 Then
                                                    ir.Mensaje = "Recibo ya existente (Anterior a un año)"
                                                Else
                                                    ir.Mensaje = "Recibo ya existente"
                                                End If
                                                ir.Correcto = False
                                                ir.Corregible = False
                                                RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                            End If
                                        Else
                                            ir.Correcto = False
                                            ir.Corregible = False
                                            RellenaDatosRecibo(cia.Codigo, ir, f, pol, 0, comsCia, comsAge, TiposRecibos, idTipoRecibo, Pne, 0, Imp, False, False)
                                            ir.Mensaje = "Recibo Duplicado en el fichero"
                                        End If
                                        ir.Tomador = pol.Tomador.RazonSocial
                                        ir.Matrícula = pol.Matricula
                                        ir.Bienes_Asegurados = pol.BienesAsegurados
                                        ir.Agente = agentes.First(Function(x) x.idAgente = pol.idAgente).Nombre
                                        ir.Subagente = If(pol.idSubAgente.HasValue = False, "", subagentes.First(Function(x) x.idSubagente = pol.idSubAgente.Value).Nombre)
                                        ir.Ramo = ramos.First(Function(x) x.idRamo = pol.idRamo).Descripcion
                                        ir.IBAN = pol.IBAN

                                        ir.Comisión = ir.Comisión_Prevista_ASEGASA
                                        ir.Sobrecomisión = 0
                                    Else
                                        ir.Correcto = False
                                        ir.Corregible = False
                                        ir.Mensaje = "Póliza no encontrada"
                                    End If
                                Catch ex As Exception
                                    Throw New Exception("Error Incorporando Recibo: " & nre & " Póliza: " & npo, ex)
                                End Try
                            End If
                            i += 1
                        Loop
                    Catch ex As Exception
                        Throw New Exception("Error Incorporando " & f.NombreFichero & " Compañia: " & "0024", ex)
                    End Try
                Next
                If GuardarCambios Then
                    Dim rcc = Lrai.Where(Function(x) x.Correcto).ToList
                    Dim rnp = Lrai.Where(Function(x) x.Correcto = False).ToList
                    If MarcarFicheros Then
                        GuardaRecibosEIAC(bd, Lrai, Nothing, Nothing, Nothing, MostrarProgreso, Ficheros, comsCia, comsAge, ldur)
                    Else
                        GuardaRecibosEIAC(bd, Lrai, Nothing, Nothing, Nothing, MostrarProgreso, Nothing, comsCia, comsAge, ldur)
                    End If
                    GeneraEmailRecibosIncorporados(Lrai, Nothing, rnp, Nothing, Nothing)
                End If
            End If
            'If MostrarProgreso Then
            '    DXSplashScreen.Close()
            'End If
        Catch EX As Exception
            If MostrarProgreso AndAlso DXSplashScreen.IsActive Then DXSplashScreen.Close()
            Throw New Exception(EX.Message, EX)
        End Try
    End Sub
#End Region
    Public Property BloquearFacturacion As Boolean
        Get
            If Utilidades.idSitr1.HasValue = False Then
                Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
                Utilidades.idSitr1 = bd.enumeraciones.First(Function(x) x.Codigo = "SITR.1").idEnumeracion
            End If
            Return If(Me.idSituacion.HasValue = False, False, (Me.idSituacion.Value = Utilidades.idSitr1))
        End Get
        Set(value As Boolean)
            If Utilidades.idSitr1.HasValue = False Then
                Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
                Utilidades.idSitr1 = bd.enumeraciones.First(Function(x) x.Codigo = "SITR.1").idEnumeracion
            End If
            If value Then
                Me.idSituacion = Utilidades.idSitr1
            Else
                Me.idSituacion = Nothing
            End If
        End Set
    End Property

    Public Property idAgente_Nulable As Integer?
        Get
            If Me.idAgente = 0 Then
                Return Nothing
            Else
                Return Me.idAgente
            End If
        End Get
        Set(value As Integer?)
            If value.HasValue Then Me.idAgente = value.Value
            OnPropertyChanged("idCliente_Nulable")
        End Set
    End Property

    Friend Shared Sub GuardandoCambios(bd As bdGestionAsegasa.gestionasegasaEntities, Aplicacion As String)
        Dim recs As IEnumerable(Of ObjectStateEntry) = Nothing
        Dim pols As IEnumerable(Of ObjectStateEntry) = Nothing
        Dim ents As IEnumerable(Of ObjectStateEntry) = Nothing
        Dim eps As IEnumerable(Of ObjectStateEntry) = Nothing
        Dim dirs As IEnumerable(Of ObjectStateEntry) = Nothing
        Dim docsp As IEnumerable(Of ObjectStateEntry) = Nothing
        Dim gests As IEnumerable(Of ObjectStateEntry) = Nothing
        recs = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "recibos")
        pols = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "polizassg")
        eps = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "entidadespolizas")
        ents = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "entidades")
        dirs = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "direcciones")
        docsp = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "documentospolizassg")
        gests = bd.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Where(Function(x) x.EntitySet.Name.ToLower = "gestionespolizassg")

        Try

            Dim bdtmp = bdGestionAsegasa.gestionasegasaEntities.NuevoContextoCN
            Dim su = If(bd.Aplicacion IsNot Nothing, bd.Aplicacion.ModoSuperUsuario, False)
            For Each m In recs
                Dim ra = DirectCast(m.Entity, recibos)
                Dim reant = bdtmp.recibos.First(Function(x) x.idRecibo = ra.idRecibo)
                Dim lrec = bdGestionAsegasa.logs.GeneraLog(bdtmp, "RECIBOS", reant.idRecibo, Nothing, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(reant), su, Aplicacion)
                Dim polant = bdtmp.polizassg.First(Function(x) x.idPoliza = reant.idPoliza)
                If reant.idRemesa.HasValue Then bdGestionAsegasa.logs.GeneraLog(bdtmp, "REMESAS", reant.idRemesa, lrec, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(reant.remesas), su, Aplicacion)
                If reant.asientos IsNot Nothing Then bdGestionAsegasa.logs.GeneraLog(bdtmp, "ASIENTODEVUELTOBANCO", reant.idRecibo, lrec, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(reant.asientos), su, Aplicacion)
                If reant.asientos1 IsNot Nothing Then bdGestionAsegasa.logs.GeneraLog(bdtmp, "ASIENTOFACTURACION", reant.idRecibo, lrec, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(reant.asientos1), su, Aplicacion)
                Dim lr = bdGestionAsegasa.logs.GeneraLog(bdtmp, "POLIZASSG", reant.idPoliza, lrec, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(polant), su, Aplicacion)

                Dim lep = polant.entidadespolizas.ToList
                bdGestionAsegasa.logs.GeneraLog(bdtmp, "ENTIDADESPOLIZAS", reant.idPoliza, lrec, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(lep), su, Aplicacion)
                For Each ent In lep
                    Dim lrent = bdGestionAsegasa.logs.GeneraLog(bdtmp, "ENTIDADES", ent.idEntidad, lr, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(ent.entidades), su, Aplicacion)
                    If ent.entidades.direcciones1 IsNot Nothing Then bdGestionAsegasa.logs.GeneraLog(bdtmp, "DIRECCIONES", ent.entidades.direcciones1.idDireccion, lrent, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(ent.entidades.direcciones1), su, Aplicacion)
                Next
                Dim ges = reant.gestionesrecibos.ToList
                bdGestionAsegasa.logs.GeneraLog(bdtmp, "GESTIONESRECIBOS", reant.idRecibo, lrec, "REGISTRO_COMPLETO", tsl5.Utilidades.Serializar(ges), su, Aplicacion)
            Next
        Catch ex As Exception
            Dim sListaCambios As String = ""
            If pols IsNot Nothing Then
                For Each m In pols
                    Dim ra = DirectCast(m.Entity, polizassg)
                    sListaCambios &= "polizassg idPoliza:" & ra.idPoliza & "; "
                Next
            End If
            sListaCambios = sListaCambios.Trim.TrimEnd(";") & vbCrLf
            If ents IsNot Nothing Then
                For Each m In ents
                    Dim ra = DirectCast(m.Entity, entidades)
                    sListaCambios &= "entidades idEntidad:" & ra.idEntidad & "; "
                Next
            End If
            sListaCambios = sListaCambios.Trim.TrimEnd(";") & vbCrLf
            If eps IsNot Nothing Then
                For Each m In eps
                    Dim ra = DirectCast(m.Entity, entidadespolizas)
                    sListaCambios &= "entidadespoliza idEntidadPoliza:" & ra.idEntidadPoliza & "; "
                Next
            End If
            sListaCambios = sListaCambios.Trim.TrimEnd(";") & vbCrLf
            If dirs IsNot Nothing Then
                For Each m In dirs
                    Dim ra = DirectCast(m.Entity, direcciones)
                    sListaCambios &= "direcciones idDireccion:" & ra.idDireccion & "; "
                Next
            End If
            If docsp IsNot Nothing Then
                For Each m In docsp
                    Dim ra = DirectCast(m.Entity, documentospolizassg)
                    sListaCambios &= "documentos idDocumento:" & ra.idDocumento & "; "
                Next
            End If
            If gests IsNot Nothing Then
                For Each m In dirs
                    Dim ra = DirectCast(m.Entity, gestionespolizassg)
                    sListaCambios &= "direcciones idGestionPoliza:" & ra.idGestionPoliza & "; "
                Next
            End If
            Call Utilidades.AñadeLog(tsl5.Enumeraciones.TipoLog.Fallo, "En GuardandoCambios", ex.Message & vbCrLf & sListaCambios, ex)
        End Try
    End Sub

    Public ReadOnly Property NombreSubAgente As String
        Get
            If Me.idSubagente.HasValue Then
                Return subagentes.ListaSubAgentes.First(Function(x) x.idSubagente = Me.idSubagente).Nombre
            Else
                Return ""
            End If
        End Get
    End Property
    Public Sub RefrescaNombreSubAgente()
        Me.OnPropertyChanged("NombreSubAgente")
    End Sub

    Private Shared _idCabaSUPL As Integer?
    Public Shared Function idCabaSUPL() As Integer
        If _idCabaSUPL.HasValue = False Then
            Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
            _idCabaSUPL = bd.enumeraciones.First(Function(x) x.Codigo = "CABA.SUPL").idEnumeracion
        End If
        Return _idCabaSUPL
    End Function

    Private Shared _idCabaFP As Integer?
    Public Shared Function idCabaFP() As Integer
        If _idCabaFP.HasValue = False Then
            Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
            _idCabaFP = bd.enumeraciones.First(Function(x) x.Codigo = "CABA.FP").idEnumeracion
        End If
        Return _idCabaFP
    End Function
    Private Shared _idCabaCIE As Integer?
    Public Shared Function idCabaCIE() As Integer
        If _idCabaCIE.HasValue = False Then
            Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
            _idCabaCIE = bd.enumeraciones.First(Function(x) x.Codigo = "CABA.CIE").idEnumeracion
        End If
        Return _idCabaCIE
    End Function

    Private Shared ListadoBancos As List(Of bancos)
    Private Shared _idTippba As Integer?
    Private Shared _idTippCIA As Integer?
    Private Shared _idTippFAE As Integer?
    Private Sub RellenaListadoBancos()
        Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
        ListadoBancos = bd.bancos.ToList
    End Sub
    Public Shared Function idTippBA() As Integer
        If _idTippba.HasValue = False Then
            Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
            _idTippba = bd.enumeraciones.First(Function(x) x.Codigo = "TIPP.BA").idEnumeracion
        End If
        Return _idTippba
    End Function

    Public Shared Function idtippCIA() As Integer
        If _idTippCIA.HasValue = False Then
            Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
            _idTippCIA = bd.enumeraciones.First(Function(x) x.Codigo = "TIPP.CIA").idEnumeracion
        End If
        Return _idTippCIA
    End Function
    Public Shared Function idtippFAE() As Integer
        If _idTippFAE.HasValue = False Then
            Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto
            _idTippFAE = bd.enumeraciones.First(Function(x) x.Codigo = "TIPP.FAE").idEnumeracion
        End If
        Return _idTippFAE
    End Function

    Public ReadOnly Property DiferenciaComision As Double
        Get
            Dim cp As Double = If(Me.ComisionPrevistaAsegasa.HasValue, Me.ComisionPrevistaAsegasa.Value, 0)
            If cp = 0 Then cp = If(Me.ComisionPrevista.HasValue, Me.ComisionPrevista.Value, 0)
            Dim c As Double = If(Me.ComisionReciboPrimaNeta.HasValue, Me.ComisionReciboPrimaNeta.Value, 0)
            Return c - cp
        End Get
    End Property
    Public ReadOnly Property DiferenciaComisionAgente As Double
        Get
            Dim cp As Double = If(Me.ComisionPrevista.HasValue, Me.ComisionPrevista.Value, 0)
            Dim c As Double = If(Me.ComisionReciboPrimaNeta.HasValue, Me.ComisionReciboPrimaNeta.Value, 0)
            Return c - cp
        End Get
    End Property
    Public ReadOnly Property idSubAgente_Especial As Integer?
        Get
            If Me.idSubagente.HasValue AndAlso Me.agentes.Codigo = "000047002186" Then
                Dim bd As gestionasegasaEntities = Me.ObtieneContexto
                Dim Codigo = Me.subagentes.Codigo.Substring(0, 2) & "00"
                Dim subage = bd.subagentes.FirstOrDefault(Function(x) x.idAgente = Me.idAgente And x.Codigo = Codigo)
                If subage IsNot Nothing Then
                    Return subage.idSubagente
                Else
                    Return Nothing
                End If
            Else
                Return idSubagente
            End If
        End Get
    End Property
    Public ReadOnly Property Banco As String
        Get
            If ListadoBancos Is Nothing Then RellenaListadoBancos()
            If Me.IBAN.NothingAVacio <> "" Then
                If Me.IBAN.Length <> 24 Then
                    Return "** IBAN ERRONEO **"
                Else
                    Dim codban = Me.IBAN.Substring(4, 4)
                    Dim b = ListadoBancos.FirstOrDefault(Function(x) x.Codigo = codban)
                    If b IsNot Nothing Then
                        Return b.Nombre
                    Else
                        Return ""
                    End If
                End If
            Else
                Return ""
            End If
        End Get
    End Property
    Public ReadOnly Property IBAN_Parcial As String
        Get
            If Me.IBAN.NothingAVacio.Length <> 24 Then
                Return "** IBAN ERRONEO **"
            Else
                Return Me.IBAN.Substring(0, 10) & "XXXXXXXX" & Me.IBAN.Substring(18)
            End If
        End Get
    End Property

    Public ReadOnly Property IBANCorrecto As Boolean
        Get
            If Me.idTipoPago = idTippBA() Then
                Return tsl5.Bancos.Genericas.IBANCorrecto(Me.IBAN)
            Else
                Return True
            End If
        End Get
    End Property



    Public ReadOnly Property OficinaAgente As String
        Get
            If Me.agentes IsNot Nothing Then
                Return Me.agentes.OficinaAgente
            Else
                Return ""
            End If
        End Get
    End Property
    Public ReadOnly Property DescripcionSuplemento As String
        Get
            If Me.polizassg.recibos.Any Then
                If Me.polizassg.recibos.OrderBy(Function(x) x.FechaEfecto).First.idRecibo = Me.idRecibo Then
                    Return Me.polizassg.DescripcionSuplemento
                Else
                    Return ""
                End If
            Else
                Return Me.polizassg.DescripcionSuplemento
            End If
        End Get
    End Property

    Public Property FormaComunicacionTMP As FormaComunicacionEnum
    Public ReadOnly Property DescripcionFormaComunicacion As String
        Get
            Return FormaComunicacionTMP.ToString.Replace("_", " ")
        End Get
    End Property

    Public ReadOnly Property DescripcionFormaPago As String
        Get
            If Me.idTipoPago.HasValue Then
                Return Me.enumeraciones2.Descripcion
            Else
                Return ""
            End If
        End Get
    End Property


    Public ReadOnly Property Estado As EstadoRecibo
        Get
            Dim est As EstadoRecibo = EstadoRecibo.PENDIENTE
            If Me.idRemesa.HasValue Then est = EstadoRecibo.REMESADO
            If Me.idTipoPago = gestionasegasaEntities.TipoPagoCia OrElse Me.idTipoPago = gestionasegasaEntities.TipoPagoFAE Then est = EstadoRecibo.GESTION_COBRO_CIA
            If Me.FechaLiquidacionAgente.HasValue Then est = EstadoRecibo.LIQUIDADO
            If Me.FechaBaja.HasValue Then est = EstadoRecibo.BAJA
            If Me.FechaDevolucionBanco.HasValue Then est = EstadoRecibo.DEVUELTO_BANCO
            '     If Me.FechaDevolucionCompania.HasValue Then est = EstadoRecibo.DEVUELTO_CIA
            Return est
        End Get
    End Property



    Public ReadOnly Property NombreBanco As String
        Get
            If Me.IBAN.NothingAVacio <> "" Then
                If IBAN.Length = 24 Then 'IBAN.Length <> 24 Then
                    Dim bd = bdGestionAsegasa.gestionasegasaEntities.NuevoContexto()
                    Dim banco = bd.bancos.Where(Function(x) x.Codigo = IBAN.Substring(4, 4))
                    If banco.Any Then
                        Return banco.First.Nombre
                    Else
                        Return "** DESCONOCIDO **"
                    End If
                Else
                    Return "** IBAN ERRONEO **"
                End If
            Else
                Return ""
            End If
        End Get
    End Property

    Public ReadOnly Property idLiquidacionAgente As Integer
        Get
            If Me.liquidacionesagenterecibos.Any(Function(x) x.liquidacionesagentes.enumeraciones.Codigo = "TIPLIQAG.LIQUIDACION") Then
                Return Me.liquidacionesagenterecibos.Where(Function(x) x.liquidacionesagentes.enumeraciones.Codigo = "TIPLIQAG.LIQUIDACION").OrderByDescending(Function(x) x.liquidacionesagentes.Fecha).First.liquidacionesagentes.idLiquidacionAgente
            Else
                Return Nothing
            End If
        End Get
    End Property
    Public ReadOnly Property FechaLiquidacionAgente As Date?
        Get
            If Me.liquidacionesagenterecibos.Any(Function(x) x.liquidacionesagentes.enumeraciones.Codigo = "TIPLIQAG.LIQUIDACION") Then
                Return Me.liquidacionesagenterecibos.Where(Function(x) x.liquidacionesagentes.enumeraciones.Codigo = "TIPLIQAG.LIQUIDACION").OrderByDescending(Function(x) x.liquidacionesagentes.Fecha).First.liquidacionesagentes.Fecha
            Else
                Return Nothing
            End If
        End Get
    End Property
    Public ReadOnly Property CausaDevolucion As String
        Get
            If Me.enumeraciones4 IsNot Nothing Then
                Return Me.enumeraciones4.Descripcion
            Else
                Return ""
            End If
        End Get
    End Property

    Public ReadOnly Property TipoRecibo As String
        Get
            If Me.enumeraciones1 IsNot Nothing Then
                Return Me.enumeraciones1.Descripcion
            Else
                Return ""
            End If
        End Get
    End Property
    Public ReadOnly Property CausaBaja As String
        Get
            If Me.enumeraciones3 IsNot Nothing Then
                Return Me.enumeraciones3.Descripcion
            Else
                Return ""
            End If
        End Get
    End Property

    Public ReadOnly Property TipoPago As String
        Get
            If Me.enumeraciones2 IsNot Nothing Then
                Return Me.enumeraciones2.Descripcion
            Else
                Return ""
            End If
        End Get
    End Property
    Public ReadOnly Property CamposAComprobar As String
        Get
            Dim sFechaBaja As String = If(Me.FechaBaja.HasValue, Me.FechaBaja.Value.ToString("yyyyMMdd"), "0")
            Dim sFechaPago As String = If(Me.FechaPago.HasValue, Me.FechaPago.Value.ToString("yyyyMMdd"), "0")
            Dim sFechaRemesa As String = If(Me.idRemesa.HasValue, Me.remesas.Fecha.Value.ToString("yyyyMMdd"), "0")
            Dim sNumeroRemesa As String = If(Me.idRemesa.HasValue, Me.remesas.idRemesa.ToString, "")
            Return (Me.CodigoRecibo & "|" & sFechaBaja & "|" & sFechaPago & "|" & sFechaRemesa & "|" & sNumeroRemesa)
        End Get
    End Property
    Public ReadOnly Property LimiteEfectoSobrePasadoFechaBaja As Boolean
        Get
            Dim DiasLimite As Integer
            If Me.TipoRecibo.Contains("CARTERA") Then
                DiasLimite = Me.polizassg.companias.NumeroDiasLimiteFBCartera
            Else
                DiasLimite = Me.polizassg.companias.NumeroDiasLimiteFBEmision
            End If
            Return Me.FechaEfecto < Today.AddDays(DiasLimite)
        End Get
    End Property
    Public Enum TipoOrigenRecibo
        OTROS = 0
        IMPORTACION_EIAC = 1
    End Enum
    Public Enum EstadoRecibo
        PENDIENTE = 0 'NEGRO
        REMESADO = 1 ' AZUL
        GESTION_COBRO_CIA = 2 'VERDE
        DEVUELTO_BANCO = 3 'NARANJA
        BAJA = 4 'MARRON
        '    DEVUELTO_CIA = 5 'ROJO
        LIQUIDADO = 6 ' VIOLETA
    End Enum


