Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE

Friend Class frmCadastroTributos
    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
    Dim vCount As Integer


#Region "Propriedades"

    Private Sub frmCadTributos_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: frmCadTributos_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

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

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

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

    End Sub

    Private Sub lvwTributos_DoubleClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lvwTributos.DoubleClick

        Try

            If lvwTributos.Items.Count > 0 Then

                vNew = False

                lEdit(lvwTributos.FocusedItem.Name.Trim())

                habDesabTudo(False)

            End If

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

    End Sub

    Private Sub txtNome_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtNome.Enter

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

    End Sub

    Private Sub txtUnidade_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtUnidade.Enter

        Try
            txtUnidade.SelectionStart = 0
            txtUnidade.SelectionLength = Len(txtUnidade.Text)
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtUnidade_Enter" & "", "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: txtValor_Enter" & "", "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: btNovo_Click" & "", "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: btEditar_Click" & "", "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 objCodigo As New entidadeCodigo


        Try

            If Len(Trim(vCodOld)) < 1 Then
                MessageBox.Show("É necessário selecionar um tributo!", "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

                objCodigo.NUM = vCodOld
                objCodigo.DATANOVA = Convert.ToDateTime(vDataOld)

                If Not lDelete(objCodigo) Then
                    MessageBox.Show("Tributo não pode ser excluído!", "Confirmação de Exclusão", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                Else
                    MessageBox.Show("Tributo 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: btExcluir_Click" & "", "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("Tributo criado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    lClear()
                    habDesabTudo(False)
                    lAtualizaList()
                Else
                    MessageBox.Show("Tributo não pode ser criado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If

            Else

                If lUpdate() Then
                    MessageBox.Show("Tributo atualizado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    lClear()
                    habDesabTudo(False)
                    lAtualizaList()
                Else
                    MessageBox.Show("Tributo 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: btSalvar_Click" & "", "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: btFechar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub frmCadTributos_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: frmCadTributos_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

#End Region

#Region "Métodos"


    Private Sub lAtualizaList()

        Dim objCodigo As entidadeCodigo

        Try
            CarregarGrid(objCodigo)

            If lvwTributos.Items.Count <> 0 Then

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

            End If

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

    End Sub

    Public Sub PrepararListView()

        Try

            lvwTributos.Items.Clear()
            lvwTributos.Columns.Clear()
            lvwTributos.Columns.Add(String.Empty, "Código", 50)
            lvwTributos.Columns.Add(String.Empty, "Descrição", 100)
            lvwTributos.Columns.Add(String.Empty, "Un", 100)
            lvwTributos.Columns.Add(String.Empty, "Valor", 100)
            lvwTributos.Columns.Add(String.Empty, "Data", 100)


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

    End Sub

    Public Sub CarregarGrid(ByRef objCodigo As entidadeCodigo)

        Try
            PrepararListView()
            vCount = 0
            For Each objCodigoFor As entidadeCodigo In New repositorioCodigo().Select_2(objCodigo)
                AddListItem(mItem, objCodigoFor)
            Next
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregarGrid" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub AddListItem(ByRef xItem As System.Windows.Forms.ListViewItem, ByRef objCodigo As entidadeCodigo)

        Try

            vCount = vCount + 1

            xItem = lvwTributos.Items.Add(vCount.ToString(), objCodigo.NUM.ToString(), String.Empty)

            If (String.IsNullOrEmpty(objCodigo.DESCRI)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objCodigo.DESCRI)
            End If

            If (String.IsNullOrEmpty(objCodigo.UN)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objCodigo.UN)
            End If

            If (String.IsNullOrEmpty(objCodigo.VALOR)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objCodigo.VALOR)
            End If

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

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: AddListItem" & "", "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 lvwTributos.Items

                If Item.Name = vCodigo Then

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

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

                    vDataOld = Convert.ToString(txtData.Value)

                    If Mid(vCodOld, 3, 3) = "PIS" Then
                        cmbTipo.SelectedIndex = 0
                    ElseIf Mid(vCodOld, 3, 3) = "COF" Then
                        cmbTipo.SelectedIndex = 1
                    End If

                End If


            Next

            Item = Nothing


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencherValoresList" & "", "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: lEdit" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub habDesabTudo(ByRef forma As Boolean)

        Try

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

            txtNome.Enabled = forma
            txtUnidade.Enabled = forma
            txtValor.Enabled = forma
            txtData.Enabled = forma

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

    End Sub

    Private Sub PreencheCombobox()

        Try

            cmbTipo.Items.Clear()
            cmbTipo.Items.Add(("PIS/PASEP"))
            cmbTipo.Items.Add(("COFINS"))

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

    End Sub

    Private Sub lClear()

        Try

            txtNome.Text = String.Empty
            txtUnidade.Text = String.Empty
            txtValor.Text = "0,00"
            txtData.Value = Date.Now

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lClear" & "", "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: lEdit" & "", "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: lClose" & "", "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 objCodigo As New entidadeCodigo
        Dim repositorioCodigo As New repositorioCodigo

        Try

            objCodigo.NUM = "40" & Convert.ToString(Mid(cmbTipo.Text, 1, 3)) & "00001"
            objCodigo.DESCRI = Trim(IIf(String.IsNullOrEmpty((txtNome.Text)), " ", txtNome.Text))
            objCodigo.UN = Trim(IIf(String.IsNullOrEmpty((txtUnidade.Text)), " ", txtUnidade.Text))
            objCodigo.VALOR = Trim(IIf(String.IsNullOrEmpty((txtValor.Text)), " ", Replace(txtValor.Text, ",", ".")))
            objCodigo.DATANOVA = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty(txtData.Value), Date.Now, txtData.Value)))

            repositorioCodigo.Insert_2(objCodigo)

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

    End Function

    Private Function lUpdate() As Boolean

        Dim objCodigo As New entidadeCodigo
        Dim repositorioCodigo As New repositorioCodigo


        Try

            objCodigo.NUM = Trim(IIf(String.IsNullOrEmpty((vCodOld)), " ", vCodOld))
            objCodigo.DESCRI = Trim(IIf(String.IsNullOrEmpty((txtNome.Text)), " ", txtNome.Text))
            objCodigo.UN = Trim(IIf(String.IsNullOrEmpty((txtUnidade.Text)), " ", txtUnidade.Text))
            objCodigo.VALOR = Trim(IIf(String.IsNullOrEmpty((txtValor.Text)), " ", Replace(txtValor.Text, ",", ".")))
            objCodigo.DATANOVA = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty(txtData.Value), Date.Now, txtData.Value)))
            objCodigo.SITUACAO = Trim(IIf(String.IsNullOrEmpty(vDataOld), Date.Now.ToShortDateString, vDataOld))


            repositorioCodigo.Update_2(objCodigo)

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

    End Function

    Private Function lDelete(ByRef objCodigo As entidadeCodigo) As Boolean
        Dim repositorioCodigo As New repositorioCodigo
        Try

            repositorioCodigo.Delete_1(objCodigo)

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

#End Region


End Class