Imports DevComponents.DotNetBar.Controls

Public Class FrmUsuariosListar
    Private Sub BtnNuevo_Click(sender As Object, e As EventArgs) Handles BtnNuevo.Click
        Dim frm0 As New FrmUsuariosCrear(Me)
        For Each frm1 As Form In Application.OpenForms
            If frm1.Name = frm0.Name Then
                frm1.Show()
                frm1.Activate()
                Dim screenSize As Size = Screen.PrimaryScreen.WorkingArea.Size
                frm1.Location = New Point(screenSize.Width / 2 - frm1.Width / 2, screenSize.Height / 2 - frm1.Height / 2)
                Exit Sub
            End If
        Next

        frm0.Show()
        frm0.Activate()
    End Sub

    Dim filtrarOcupado As Boolean = False
    Public Sub Filtrar()
        If filtrarOcupado = True Then Exit Sub
        Try
            filtrarOcupado = True
            Dim conexion As New Conexion(conexionLocal)
            Dim manejador As New ClsUsuariosListar(conexion)
            Dim miTabla As New DataTable
            Dim argumentos As New UsuariosListar2Argumentos With {.FiltroUniversal = TxtBuscar.Text}

            miTabla = manejador.Listar(argumentos, CmbEmpresa.SelectedValue)

            DgvFichas.DataSource = miTabla

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        Finally
            filtrarOcupado = False
        End Try
    End Sub

    Private Sub FrmUsuariosListar_Load(sender As Object, e As EventArgs) Handles Me.Load
        DgvFichas.AutoGenerateColumns = False
        If idContrato = 0 Then
            Me.Close()
        End If

        RemoveHandler CmbEmpresa.SelectedIndexChanged, AddressOf CmbEmpresa_SelectedIndexChanged
        CargarEmpresas()
        CargarRutEmpresa()
        AddHandler CmbEmpresa.SelectedIndexChanged, AddressOf CmbEmpresa_SelectedIndexChanged
        Filtrar()
    End Sub

    Private Sub CargarRutEmpresa()
        Dim conn As New Conexion(conexionLocal)
        rutEmpresa = conn.ObtenerValor($"SELECT numeroLegal FROM Empresas WHERE idContrato = {idContrato} AND id = {CmbEmpresa.SelectedValue}")
    End Sub

    Private Sub CargarEmpresas()
        Dim conexion As New Conexion(conexionLocal)

        Dim sql As String = $"SELECT id AS cod, nombreLegal AS nombre FROM Empresas WHERE idContrato = {idContrato}"
        Dim dt = conexion.ObtenerDataTable(sql, New List(Of SqlClient.SqlParameter))

        With CmbEmpresa
            .DataSource = dt
            .DisplayMember = "nombre"
            .ValueMember = "cod"
        End With

        CmbEmpresa.SelectedIndex = 0
    End Sub

    Private Sub _KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBuscar.KeyPress
        If e.KeyChar = Chr(13) Then
            Filtrar()
            e.Handled = True
            Exit Sub
        End If
    End Sub

    Private Sub TxtBuscar_MouseLeave(sender As Object, e As EventArgs) Handles TxtBuscar.MouseLeave
        Filtrar()
    End Sub

    Private Sub DgvFichas_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DgvFichas.CellContentClick
        ' Validaciones
        If IsNothing(sender) Then Return
        If e.RowIndex = -1 Then Return
        Dim dgv As DataGridViewX = TryCast(sender, DataGridViewX)

        ' Validacion
        Dim idUsuario As String = dgv(DgvFichasIdentificador.Name, e.RowIndex).Value.ToString()
        Dim UsuarioNombre As String = dgv(DgvFichasNombre.Name, e.RowIndex).Value.ToString()
        Dim UsuarioApellido As String = dgv(DgvFichasApellidos.Name, e.RowIndex).Value.ToString()
        Dim UsuarioNumeroLegal As String = dgv(DgvFichasNumeroLegal.Name, e.RowIndex).Value.ToString()

        If Not IsNothing(dgv.Columns(DgvFichasBtnEnrolar.Name)) AndAlso e.ColumnIndex = dgv.Columns(DgvFichasBtnEnrolar.Name).Index Then
            ' ENROLAR
            UpdateEnrollUsersData()
            Dim data = GetUserDeviceData(idUsuario)
            Enrolar(data, $"{UsuarioNombre} {UsuarioApellido}", UsuarioNumeroLegal)
        ElseIf Not IsNothing(dgv.Columns(DgvFichasBtnEditar.Name)) AndAlso e.ColumnIndex = dgv.Columns(DgvFichasBtnEditar.Name).Index Then
            ' EDITAR
            Editar(idUsuario)
        ElseIf Not IsNothing(dgv.Columns(DgvFichasBtnEliminar.Name)) AndAlso e.ColumnIndex = dgv.Columns(DgvFichasBtnEliminar.Name).Index Then
            ' ELIMINAR
            Eliminar(idUsuario, UsuarioNombre)
        ElseIf Not IsNothing(dgv.Columns(DgvFichasDesenrolar.Name)) AndAlso e.ColumnIndex = dgv.Columns(DgvFichasDesenrolar.Name).Index Then
            Desenrolar(idUsuario, UsuarioNombre)
        End If
    End Sub

    Private Sub Desenrolar(idUsuario As String, nombreUsuario As String)
        Dim sino As String = ""
        Dim conexion As New Conexion(conexionLocal)
        Dim manejador As New ClsUsuariosDesenrolar(conexion)
        Dim mensajeError As String = ""
        Dim ok As Boolean = False

        Try
            Dim argumentoEntrada As New UsuariosDesenrolarArgumentos() With {
                       .IdUsuario = CInt(idUsuario)}

            sino = PreguntaSimple_Msgbox($"¿Está seguro que desea desenrolar al usuario '{nombreUsuario}'?")

            If sino = MsgBoxResult.Yes Then
                ok = manejador.Desenrolar(argumentoEntrada, mensajeError)
            Else
                Exit Sub
            End If
        Catch ex As Exception
            mensajeError += vbNewLine + ex.Message
        Finally
            conexion.Dispose()
        End Try


        If ok Then
            MessageBox.Show("Usuario desenrolado correctamente.")
            Filtrar()
        Else
            MsgBox(mensajeError)
        End If
    End Sub

    Private Sub Eliminar(idUsuario As String, nombreUsuario As String)

        Dim sino As String = ""
        Dim conexion As New Conexion(conexionLocal)
        Dim manejador As New ClsUsuariosEliminar(conexion)
        Dim mensajeError As String = ""
        Dim ok As Boolean = False

        Try
            Dim argumentoEntrada As New UsuariosEliminarArgumentos() With {
                       .Id = CInt(idUsuario)}

            sino = PreguntaSimple_Msgbox($"¿Está seguro que desea eliminar el usuario '{nombreUsuario}'?")

            If sino = MsgBoxResult.Yes Then
                ok = manejador.Eliminar(argumentoEntrada, mensajeError)
            Else
                Exit Sub
            End If
        Catch ex As Exception
            mensajeError += vbNewLine + ex.Message
        Finally
            conexion.Dispose()
        End Try


        If ok Then
            MessageBox.Show("Usuario eliminado correctamente.")
            Filtrar()
        Else
            MsgBox(mensajeError)
        End If


    End Sub

    Private Sub Editar(idUsuario As String)
        Dim frm0 As New FrmUsuariosModificar(Me, idUsuario)
        For Each frm1 As Form In Application.OpenForms
            If frm1.Name = frm0.Name Then
                frm1.Show()
                frm1.Activate()
                Exit Sub
            End If
        Next

        frm0.Show()
        frm0.Activate()
    End Sub

    Private Sub Enrolar(ByVal data As DeviceUserData, usuarioFullNombre As String, usuarioNumeroLegal As String)
        Dim frm0 As New FrmUsuariosEnrolar(data, usuarioFullNombre, usuarioNumeroLegal, Me)
        For Each frm1 As Form In Application.OpenForms
            If frm1.Name = frm0.Name Then
                frm1.Show()
                frm1.Activate()
                Exit Sub
            End If
        Next

        frm0.Show()
        frm0.Activate()
    End Sub

    Dim rutEmpresa As String
    Private Sub BtnImportar_Click(sender As Object, e As EventArgs) Handles BtnImportar.Click
        Dim frm As New FrmPeriodoMes(rutEmpresa)
        frm.ShowDialog()

        If mes <> 0 And periodo <> 0 Then
            MessageBox.Show("Los usuarios importados quedaran con la contraseña por defecto 1234", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information)
            ImportarUsuarios()
        Else
            MsgBox("Debe seleccionar periodo y mes para importar usuarios")
        End If
    End Sub

    Private Function ImportarUsuarios() As Boolean
        Try
            Dim result As Boolean = False
            Dim conn As New Conexion(conexionLocal)

            Dim MaestraDataSource = My.Settings.ConexionMaestraDataSource
            Dim MaestraInitialCatalog As String = $"PRIXUS_{rutEmpresa}"
            Dim MaestraUser = My.Settings.ConexionMaestraUsuario
            Dim MaestraPass = My.Settings.ConexionMaestraPassword

            conn.CerrarBD()

            Dim conexionEmp = CrearCadenaConexion(MaestraDataSource, MaestraInitialCatalog, MaestraUser, MaestraPass)

            Dim conexion As New Conexion(conexionEmp)


            Dim sql As String = $"SELECT 
                                    rut,
                                    nombres, 
                                    apePaterno + ' ' + apeMaterno AS apellidos,
                                    fechaIngreso,
                                    fechaTermino,
                                    correoPart,
                                    correoEmp,
                                    celularPart,
                                    celularEmp,
                                    ficha
                                FROM remTrabajadores 
                                WHERE   activo = 1
                                        AND mes = {mes}
                                        AND periodo = {periodo}"

            Dim dtEmp = conexion.ObtenerDataTable(sql, New List(Of SqlClient.SqlParameter))

            If dtEmp.Rows.Count > 0 Then
                Dim connLocal As New Conexion(conexionLocal)
                Dim mensajeError As String = ""

                For Each usr As DataRow In dtEmp.Rows
                    Dim usuarioCrear As New ClsUsuariosCrear(connLocal)

                    Dim ok As Boolean = False

                    If ValidarUsuarioExiste(usr.Item("rut")) Then
                        Try
                            Dim argumentosEmpresa As New UsuariosCrearArgumentos() With {
                                .NumeroLegal = usr.Item("rut"),
                                .Password = "1234",
                                .Rol = 2,
                                .Nombre = usr.Item("nombres"),
                                .Apellidos = usr.Item("apellidos"),
                                .IdEmpresa = CmbEmpresa.SelectedValue,
                                .InicioContrato = usr.Item("fechaIngreso"),
                                .FinContrato = usr.Item("fechaTermino"),
                                .MailPersonal = usr.Item("correoPart"),
                                .MailCorporativo = usr.Item("correoEmp"),
                                .MovilPersonal = usr.Item("celularPart"),
                                .MovilCorporativo = usr.Item("celularEmp"),
                                .IdAlternativo = usr.Item("ficha")}
                            If usuarioCrear.Crear(argumentosEmpresa, mensajeError) Then
                                result = True
                            Else
                                result = False
                                Exit For
                            End If
                        Catch ex As Exception
                            mensajeError += vbNewLine + ex.Message
                        End Try
                    Else
                        MsgBox($"Error al ingresar usuario {usr.Item("nombres") & " " & usr.Item("apellidos")}")
                        Exit Function
                    End If
                Next

                If result Then
                    MessageBox.Show("Usuarios importados correctamente.")
                    conn.Dispose()
                    Filtrar()
                Else
                    MsgBox(mensajeError)
                    conn.Dispose()
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Function

    Private Function ValidarUsuarioExiste(numeroLegal As String) As Boolean
        Try
            Dim result As Boolean = False
            Dim mensajeError As String = ""

            Dim conn As New Conexion(conexionLocal)
            Dim manejador As New ClsUsuariosEliminar(conn)
            Dim desenrolador As New ClsUsuariosDesenrolar(conn)

            Dim userExist = conn.ObtenerValor($"SELECT id FROM Usuarios WHERE numeroLegal = '{numeroLegal}' AND idEmpresa = {CmbEmpresa.SelectedValue}")

            If userExist <> "" Then
                'Eliminar Enrolamiento
                Dim argumentoEntradaDes As New UsuariosDesenrolarArgumentos() With {
                       .IdUsuario = CInt(userExist)}

                Dim ok = desenrolador.Desenrolar(argumentoEntradaDes, mensajeError)

                If ok Then
                    Dim argumentoEntrada As New UsuariosEliminarArgumentos() With {
                       .Id = CInt(userExist)}

                    result = manejador.Eliminar(argumentoEntrada, mensajeError)
                Else
                    result = False
                End If
            Else
                result = True
            End If

            Return result
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Function

    Private Sub CmbEmpresa_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbEmpresa.SelectedIndexChanged
        CargarRutEmpresa()
        Filtrar()
    End Sub
End Class