Imports DevExpress.Web

Public Class ucListadoPlazas
    Inherits ucBase

    Public ReadOnly Property idIns() As String
        Get
            Return Session("idIns")
        End Get
    End Property


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        RegisterCustomMessage(cbpConcursos)
        gridHistorialPuestos.SettingsPopup.HeaderFilter.Width = 300
        gridHistorialPuestos.SettingsPopup.HeaderFilter.Height = 320
        If Not IsPostBack Then
            Dim oIns As New InstitucionBusinessObject(Me.idIns)
            lblInstitucion.Text = String.Format("Institución: <b>{0}</b>", oIns.Entity.nombreInstitucion)
            'gridHistorialPuestos.DataBind()

        End If

    End Sub

    Protected Sub gridHistorialPuestos_CustomButtonInitialize(sender As Object, e As DevExpress.Web.ASPxGridViewCustomButtonEventArgs) Handles gridHistorialPuestos.CustomButtonInitialize
        If (e.VisibleIndex = -1) Then Return
        If e.ButtonID = "btnEdit" Or e.ButtonID = "btnEliminar" Then
            If CriterioVisible(CType(sender, ASPxGridView), e.VisibleIndex) = False Then e.Visible = DevExpress.Utils.DefaultBoolean.False
        End If
        If e.ButtonID = "btnCerrar" Then
            If CriterioVisibleCerrar(CType(sender, ASPxGridView), e.VisibleIndex) = False Then e.Visible = DevExpress.Utils.DefaultBoolean.False
        End If
    End Sub

    Private Function CriterioVisible(g As ASPxGridView, i As Integer) As Boolean
        'If Not String.IsNullOrEmpty(g.GetRowValues(i, "idEstadoPlaza")) Then
        'AndAlso (STP.BL.RolBusinessObject.IsInRole(CInt(Page.User.Identity.Name), 2))
        If g.GetRowValues(i, "idEstadoPlaza").ToString.Equals("1") AndAlso g.GetRowValues(i, "idInstitucion").ToString.Equals(Me.idIns) Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Function CriterioVisibleCerrar(g As ASPxGridView, i As Integer) As Boolean

        If g.GetRowValues(i, "idEstadoPlaza").ToString.Equals("6") AndAlso g.GetRowValues(i, "idInstitucion").ToString.Equals(Me.idIns) Then
            Dim oIns As New InstitucionBusinessObject(Me.idIns)
            If oIns.Entity.permisoFinalizarTodos = False Then
                If CInt(Page.User.Identity.Name) = CInt(g.GetRowValues(i, "usuarioCreacion")) Then
                    Return True
                Else
                    Return False
                End If
            Else

                Return True
            End If

        Else
            Return False
        End If

    End Function

    Protected Sub gridHistorialPuestos_HtmlDataCellPrepared(sender As Object, e As ASPxGridViewTableDataCellEventArgs) Handles gridHistorialPuestos.HtmlDataCellPrepared
        Select Case e.DataColumn.FieldName
            Case "idEstadoPlaza"
                ColoresEstado(e)
            Case "cod_inspto"
                If e.CellValue.ToString.Trim.Equals("Pendiente") Then
                    e.Cell.BackColor = ColorEstadoBorrador()
                End If
            Case "nombrePuesto"
                If e.CellValue.ToString.Trim.Equals("Pendiente") Then
                    e.Cell.BackColor = ColorEstadoBorrador()
                End If
            Case "dias"

                If CInt(e.CellValue) > 30 And CInt(e.CellValue) <= 60 Then
                    e.Cell.BackColor = Drawing.Color.Yellow
                ElseIf CInt(e.CellValue) > 60 Then
                    e.Cell.BackColor = Drawing.Color.Red
                End If
            Case Else
                Exit Select
        End Select
    End Sub

    Protected Sub cbpConcursos_Callback(sender As Object, e As CallbackEventArgsBase) Handles cbpConcursos.Callback
        'CustomMessage(txtID.Value, "veamos", cbpConcursos)

        Dim hasError As Boolean = False
        Dim codigoError As Boolean = False

        For Each column As GridViewColumn In gridPostulantes.Columns
            Dim dataColumn As GridViewDataColumn = TryCast(column, GridViewDataColumn)
            If dataColumn Is Nothing Then
                Continue For
            End If
            If dataColumn.FieldName = "idPostulante" Then
                If Not gridPostulantes.GetRowValues(0, dataColumn.FieldName) Is Nothing Then
                    If Not (String.IsNullOrEmpty(gridPostulantes.GetRowValues(0, dataColumn.FieldName))) Then
                        If ConcursoPostulanteBusinessObject.ExisteCodigo(gridPostulantes.GetRowValues(0, dataColumn.FieldName), CInt(txtID.Value)) = False Then
                            codigoError = True
                            Exit For
                        End If
                    End If

                End If

            Else
                Dim value As Object = gridPostulantes.GetRowValues(0, dataColumn.FieldName)
                If value Is Nothing Then
                    hasError = True
                    Exit For
                End If
            End If
        Next


        If Not hasError Then

            If Not codigoError Then

                Dim oPlaza As New PlazaBusinessObject(CInt(txtID.Value))
                Dim msg As New MSG

                If rbDesierto.Value = True Then
                    oPlaza.Entity.idEstadoPlaza = 7
                Else
                    oPlaza.Entity.idEstadoPlaza = 4
                End If

                oPlaza.Entity.cierreComentario = txtComentario.Text
                msg = oPlaza.SaveChanges

                If msg.EventType = Entity.MSG.MsgType.Errors Then
                    CustomMessage("Ha surgido un error.", "Actualización de Concurso", cbpConcursos)
                ElseIf msg.EventType = Entity.MSG.MsgType.Success Then
                    CustomMessage("El concurso ha finalizado.", "Actualización de Concurso", cbpConcursos)
                End If
                gridHistorialPuestos.DataBind()
                popupCerrar.ShowOnPageLoad = False
            Else
                CustomMessage("El código de la persona contratada no se encuentra en el sistema", "Error: Código inválido", cbpConcursos)
            End If

        Else
            CustomMessage("Debe escribir todas personas contratadas para CERRAR el concurso", "Error: Falta información", cbpConcursos)
        End If

    End Sub

    Protected Sub cbpComentario_Callback(sender As Object, e As CallbackEventArgsBase) Handles cbpComentario.Callback
        Dim oPlaza As New PlazaBusinessObject(CInt(e.Parameter))
        txtID.Value = e.Parameter
        ObjectContratos.SelectParameters("idPlaza").DefaultValue = e.Parameter
        lblConcurso.Text = String.Format("{0} - {1}", oPlaza.Entity.Identificador, oPlaza.Entity.nombrePuesto)
    End Sub

    Protected Sub gridPostulantes_HtmlRowPrepared(sender As Object, e As ASPxGridViewTableRowEventArgs) Handles gridPostulantes.HtmlRowPrepared

        If e.RowType = GridViewRowType.Data Then
            Dim hasError As Boolean = False
            If e.GetValue("nombre") Is Nothing Then
                hasError = True
            ElseIf String.IsNullOrEmpty(e.GetValue("nombre")) Then
                hasError = True
            End If

            If e.GetValue("apellido") Is Nothing Then
                hasError = True
            ElseIf String.IsNullOrEmpty(e.GetValue("apellido")) Then
            End If

            If hasError Then
                e.Row.ForeColor = System.Drawing.Color.Red
            End If
        End If

    End Sub

    'Protected Sub gridPostulantes_StartRowEditing(sender As Object, e As Data.ASPxStartRowEditingEventArgs) Handles gridPostulantes.StartRowEditing
    '    If (Not gridPostulantes.IsNewRowEditing) Then
    '        gridPostulantes.DoRowValidation()
    '    End If
    'End Sub

    Protected Sub gridPostulantes_RowUpdating(sender As Object, e As Data.ASPxDataUpdatingEventArgs) Handles gridPostulantes.RowUpdating
        ObjectContratos.SelectParameters("idPlaza").DefaultValue = txtID.Value
        If e.NewValues("idPostulante") Is Nothing Then
            e.NewValues("idPostulante") = ""
        End If

    End Sub

    Protected Sub gridHistorialPuestos_CustomColumnDisplayText(sender As Object, e As ASPxGridViewColumnDisplayTextEventArgs) Handles gridHistorialPuestos.CustomColumnDisplayText
        If e.Column.FieldName = "dias" Then
            If Convert.ToInt32(e.Value) = 0 Then
                e.DisplayText = "-"
            End If
        End If
    End Sub

    Protected Sub callPanelElemento_Callback(sender As Object, e As CallbackEventArgsBase) Handles callPanelElemento.Callback
        Dim oPlaza As New PlazaBusinessObject(e.Parameter)
        Dim oCreador As New UsuariosBusinessObject(oPlaza.Entity.usuarioCreacion)
        Dim oModificador As New UsuariosBusinessObject(oPlaza.Entity.usuarioModificacion)

        lblCreado.Text = String.Format("{0} {1}", oCreador.Entity.nombres, oCreador.Entity.apellidos)
        lblFechaCreado.Text = oPlaza.Entity.fechaCreacion

        lblModificado.Text = String.Format("{0} {1}", oModificador.Entity.nombres, oModificador.Entity.apellidos)
        lblFechaModificado.Text = oPlaza.Entity.fechaModificacion
    End Sub

    Protected Function GetEstadoConcursos() As Object
        Return PlazaBusinessObject.ExecuteEstadoConcursos(idIns)
    End Function
End Class