Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE

Friend Class frmCadastroIndiceCM
    Inherits System.Windows.Forms.Form

    Private mItem As System.Windows.Forms.ListViewItem ' Objeto que controla a linha do listview
    Dim vCodigo As String
    Dim vResp As Short
    Dim vNew As Boolean
    Dim vCodOld As String
    Dim vDataOld As String


#Region "Propriedades"

    Private Sub frmCadIndiceCM_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load

        Try
            lAtualizaList()
            PreencheCombobox()
            habDesabTudo(False)
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lvwCorrecaoMonetaria_ColumnClick(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ColumnClickEventArgs) Handles lvwCorrecaoMonetaria.ColumnClick

        Dim ColumnHeader As System.Windows.Forms.ColumnHeader = lvwCorrecaoMonetaria.Columns(eventArgs.Column)

        Try
            lvwCorrecaoMonetaria.ListViewItemSorter = New ListViewItemComparer(eventArgs.Column)
            lvwCorrecaoMonetaria.Sort()
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lvwCorrecaoMonetaria_DoubleClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lvwCorrecaoMonetaria.DoubleClick

        Try

            If lvwCorrecaoMonetaria.Items.Count > 0 Then

                vNew = False

                lEdit(lvwCorrecaoMonetaria.FocusedItem.Name.Trim())

                habDesabTudo(False)

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub txtValor_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtValor.Enter

        Try
            txtValor.SelectionStart = 0
            txtValor.SelectionLength = Len(txtValor.Text)
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub txtValor_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtValor.Leave

        Try
            txtValor.Text = FormatNumber(txtValor.Text, 6)
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub btNovo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btNovo.Click

        Try
            lNew()
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub btEditar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btEditar.Click

        Try
            lEdit()
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub btSalvar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btSalvar.Click

        Try

            If vNew = True Then

                If lInsert() Then
                    MessageBox.Show("Indice Correção Monetária criado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    lClear()
                    habDesabTudo(False)
                    lAtualizaList()
                Else
                    MessageBox.Show("Indice Correção Monetária não pode ser criado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If

            Else

                If lUpdate() Then
                    MessageBox.Show("Indice Correção Monetária atualizado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    lClear()
                    habDesabTudo(False)
                    lAtualizaList()
                Else
                    MessageBox.Show("Indice Correção Monetária não pode ser atualizado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If

            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try


    End Sub

    Private Sub btExcluir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btExcluir.Click


        Dim objIndiceCM As New entidadeIndiceCM


        Try

            If Len(Trim(vCodOld)) < 1 Then
                MessageBox.Show("É necessário selecionar um Indice Correção Monetária!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Exit Sub
            End If

            vResp = MessageBox.Show("Esta operação não possui retorno!" & vbCrLf & vbCrLf & "Tem certeza de que deseja excluir este registro?", "Confirmação de Exclusão", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

            If vResp = DialogResult.Yes Then

                objIndiceCM.CODIGO = Convert.ToInt32(vCodOld)
                objIndiceCM.MESANO = Convert.ToDateTime(vDataOld)

                If Not lDelete(objIndiceCM) Then
                    MessageBox.Show("Indice Correção Monetária não pode ser excluído!", "Confirmação de Exclusão", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                Else
                    MessageBox.Show("Indice Correção Monetária excluído com sucesso!", "Confirmação de Exclusão", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    lClear()
                    lAtualizaList()
                End If


            ElseIf vResp = DialogResult.Cancel Then
                Exit Sub
            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub btFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles btFechar.Click

        Try

            lClose()
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub frmCadIndiceCM_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try


            If KeyAscii = System.Windows.Forms.Keys.Return Then
                TabEnter(KeyAscii, eventArgs)
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try


    End Sub

#End Region

#Region "Métodos"


    Private Sub lAtualizaList()

        Dim objIndiceCM As entidadeIndiceCM

        Try
            CarregarGrid(objIndiceCM)

            If lvwCorrecaoMonetaria.Items.Count <> 0 Then

                lvwCorrecaoMonetaria.Focus()
                lvwCorrecaoMonetaria.Items.Item(0).Selected = True
                lvwCorrecaoMonetaria.FocusedItem = lvwCorrecaoMonetaria.Items.Item(0)
                lvwCorrecaoMonetaria.Items.Item(0).EnsureVisible()

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub PrepararListView()

        Try

            lvwCorrecaoMonetaria.Items.Clear()
            lvwCorrecaoMonetaria.Columns.Clear()
            lvwCorrecaoMonetaria.Columns.Add(String.Empty, "Código", 50)
            lvwCorrecaoMonetaria.Columns.Add(String.Empty, "Tipo", 100)
            lvwCorrecaoMonetaria.Columns.Add(String.Empty, "Valor", 100)
            lvwCorrecaoMonetaria.Columns.Add(String.Empty, "Data", 100)


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub CarregarGrid(ByRef objIndiceCM As entidadeIndiceCM)

        Try
            PrepararListView()
            For Each objIndiceCMFor As entidadeIndiceCM In New repositorioIndiceCM().Select(objIndiceCM)
                AddListItem(mItem, objIndiceCMFor)
            Next
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub AddListItem(ByRef xItem As System.Windows.Forms.ListViewItem, ByRef objIndiceCM As entidadeIndiceCM)

        Try


            xItem = lvwCorrecaoMonetaria.Items.Add(objIndiceCM.CODIGO.ToString(), objIndiceCM.CODIGO.ToString(), String.Empty)

            If (String.IsNullOrEmpty(objIndiceCM.INDICE)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objIndiceCM.INDICE)
            End If

            If (String.IsNullOrEmpty(Convert.ToString(objIndiceCM.VLRINDICE))) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objIndiceCM.VLRINDICE)
            End If

            If (String.IsNullOrEmpty(Convert.ToString(objIndiceCM.MESANO))) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objIndiceCM.MESANO)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub PreencherValoresList(ByRef Items As String)

        vCodigo = Items

        Dim Item As ListViewItem



        Try

            For Each Item In lvwCorrecaoMonetaria.Items

                If Item.Name = vCodigo Then

                    'Pega a Coluna 0
                    vCodOld = IIf(String.IsNullOrEmpty((Item.Text)), "0", (Item.Text))

                    'Para pegar os SubItems e so fazer o seguinte
                    txtCodigo.Text = vCodOld
                    txtValor.Text = FormatNumber(Convert.ToDouble(IIf(String.IsNullOrEmpty((Item.SubItems(2).Text)), "0", (Item.SubItems(2).Text))))
                    txtData.Value = IIf(String.IsNullOrEmpty((Item.SubItems(3).Text)), Date.Now, Format(Convert.ToDateTime((Item.SubItems(3).Text)), "dd/MM/yyyy"))

                    vDataOld = Convert.ToString(txtData.Value)


                    If IIf(String.IsNullOrEmpty((Item.SubItems(1).Text)), " ", (Item.SubItems(1).Text)) = "IGP-M" Then
                        cmbTipo.SelectedIndex = 1
                    Else
                        cmbTipo.SelectedIndex = 0
                    End If


                End If


            Next

            Item = Nothing


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lEdit(ByRef Item As String)

        vCodigo = Item

        Try

            PreencherValoresList(vCodigo)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub habDesabTudo(ByRef abForma As Boolean)

        Try

            If vNew <> False Then
                cmbTipo.Enabled = abForma
            End If

            txtValor.Enabled = abForma
            txtData.Enabled = abForma

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub PreencheCombobox()

        Try
            cmbTipo.Items.Clear()
            cmbTipo.Items.Add(("IPCA"))
            cmbTipo.Items.Add(("INPC"))
            cmbTipo.Items.Add(("IGP-M"))

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lClear()

        Try

            txtValor.Text = FormatNumber(0, 6)
            txtData.Value = Date.Now

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lEdit()

        Try

            vNew = False
            habDesabTudo(True)
            txtData.Focus()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lClose()

        Try

            Close()
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lNew()

        Try

            vNew = True

            lClear()
            habDesabTudo(True)

            cmbTipo.Enabled = True
            cmbTipo.Focus()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Function lInsert() As Boolean

        Dim objIndiceCM As New entidadeIndiceCM
        Dim repositorioIndiceCM As New repositorioIndiceCM

        Try


            objIndiceCM.INDICE = cmbTipo.Text
            objIndiceCM.VLRINDICE = Convert.ToDouble(Trim(IIf(String.IsNullOrEmpty((txtValor.Text)), "0", txtValor.Text))) 'Convert.ToDouble(Trim(IIf(String.IsNullOrEmpty((txtValor.Text)), "0", ReplacetxtValor.Text, ",", "."))))
            objIndiceCM.MESANO = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty(txtData.Value), Date.Now, txtData.Value)))

            repositorioIndiceCM.Insert(objIndiceCM)

            Return True
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        End Try

    End Function

    Private Function lUpdate() As Boolean

        Dim objIndiceCM As New entidadeIndiceCM
        Dim repositorioIndiceCM As New repositorioIndiceCM


        Try


            objIndiceCM.INDICE = cmbTipo.Text
            objIndiceCM.VLRINDICE = Convert.ToDouble(Trim(IIf(String.IsNullOrEmpty((txtValor.Text)), "0", txtValor.Text)))
            objIndiceCM.MESANO = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty(txtData.Value), Date.Now, txtData.Value)))
            objIndiceCM.CODIGO = Convert.ToInt32(Trim(IIf(String.IsNullOrEmpty((vCodOld)), "0", vCodOld)))
            objIndiceCM.MESANO_OLD = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty(vDataOld), Date.Now, vDataOld)))


            repositorioIndiceCM.Update(objIndiceCM)

            Return True
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        End Try

    End Function

    Private Function lDelete(ByRef objIndiceCM As entidadeIndiceCM) As Boolean
        Dim repositorioIndiceCM As New repositorioIndiceCM
        Try

            repositorioIndiceCM.Delete(objIndiceCM)

            Return True
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        End Try
    End Function

#End Region


End Class