Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE


Friend Class frmCadastroTarifas
    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 vDescricaoOld As String
    Dim vLimitOld As String
    Dim vValorOld As String
    Dim vReferenciaOld As String
    Dim vNumOld As String
    Dim vCodTar As String

#Region "Propriedades"

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

        Try

            PreencheCombobox()
            cmbGrupoTarifario.SelectedIndex = 0

            lAtualizaList()
            cmbData.Text = Date.Now.ToShortDateString()

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

    End Sub

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

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

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

    End Sub

    Private Sub lvwTarifas_DoubleClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lvwTarifas.DoubleClick

        Try

            If lvwTarifas.Items.Count > 0 Then

                vNew = False
                lEdit(lvwTarifas.FocusedItem.Name.Trim())

                lblNomeTarifa.Text = vDescricaoOld & ":"

                With Me.txtValor
                    .Focus()
                    .SelectionStart = 0
                    .SelectionLength = Len(.Text)
                End With

            End If

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

    End Sub

    Private Sub cmbGrupoTarifario_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbGrupoTarifario.SelectedIndexChanged

        Dim objTarifa As New entidadeTarifa()
        Dim vGrupoTarifario As String
        Try

            vGrupoTarifario = Convert.ToString(DirectCast(cmbGrupoTarifario.SelectedItem, entidadeTarifa).DESCRI)

            If Trim(vGrupoTarifario.ToUpper()) <> "SELECIONE" Then
                lAtualizaList()
                objTarifa.NUM = Mid(vGrupoTarifario, 1, 4)
                PreencherTarifa(cmbData, objTarifa)
            End If

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


    End Sub

    Private Sub cmbData_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbData.SelectedIndexChanged

        Try

            lAtualizaList()

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

    End Sub

    Private Sub cmbData_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbData.Leave

        Try

            If Len(Trim(cmbData.Text)) = 0 Then
                Exit Sub
            Else
                If IsDate(cmbData.Text) Then
                    Me.cmbData.Text = Format(Convert.ToDateTime(cmbData.Text), "dd/MM/yyyy")
                Else
                    Me.cmbData.Text = String.Empty
                End If
            End If

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

    End Sub

    Private Sub cmdBuscar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBuscar.Click

        Try

            lAtualizaList()

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

    End Sub

    Private Sub cmdBuscar_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBuscar.Enter

        Try

            lAtualizaList()

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

    End Sub

    Private Sub cmdOK_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdOk.Click


        vCodigo = lvwTarifas.FocusedItem.Name.Trim()

        Dim Item As ListViewItem

        Try

            If lvwTarifas.Items.Count > 0 Then

                For Each Item In lvwTarifas.Items

                    If Item.Name = vCodigo Then

                        Item.SubItems(2).Text = Format(Convert.ToDouble(Me.txtValor.Text), "#,##0.00")
                        vValorOld = Item.SubItems(2).Text

                    End If


                Next

                Item = Nothing

            End If

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

    End Sub

    Private Sub cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click

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

    End Sub

    Private Sub cmdSalvar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSalvar.Click


        Try

            If CShort(Len(Trim(Me.cmbData.Text))) = 0 Then
                MessageBox.Show("É necessário informar a data de cadastramento!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                cmbData.Text = Date.Now.ToShortDateString()
                Call cmbData.Focus()
            Else

                If vNew = True Then

                    If lInsert() Then
                        MessageBox.Show("Tarifa criada com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                        lblNomeTarifa.Text = "Salvamento concluído!"
                        txtValor.Text = "0,00"
                    Else
                        MessageBox.Show("Tarifa não pode ser criada!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Exit Sub
                    End If

                Else

                    If lUpdate() Then
                        MessageBox.Show("Tarifa atualizada com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                        lblNomeTarifa.Text = "Salvamento concluído!"
                        txtValor.Text = "0,00"
                    Else
                        MessageBox.Show("Tarifa não pode ser atualizada!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Exit Sub
                    End If

                End If

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


    End Sub

    Private Sub frmCadastroTarifas_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)
            ElseIf KeyAscii = System.Windows.Forms.Keys.Escape Then
                cmdFechar_Click(cmdFechar, New System.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: frmCadastroTarifas_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

#End Region

#Region "Métodos"

    Private Sub lAtualizaList()

        Dim objTarifa As New entidadeTarifa

        Try

            If Trim(cmbData.Text.ToUpper()) = String.Empty Then
                vReferenciaOld = String.Empty
            Else
                vReferenciaOld = Trim(cmbData.Text.ToUpper())
            End If

            If Trim(cmbGrupoTarifario.Text.ToUpper()) = "SELECIONE" Or Trim(cmbGrupoTarifario.Text.ToUpper()) = String.Empty Then
                vNumOld = String.Empty
            Else
                vNumOld = cmbGrupoTarifario.Text
            End If


            If Len(Trim(vReferenciaOld)) > 0 Then
                If Mid(vNumOld, 1, 3) = "01A" Then
                    vCodTar = "4"
                    If Mid(vNumOld, 1, 4) = "01AP" Then
                        vCodTar = "6"
                    End If
                Else
                    vCodTar = "6"
                End If
                vNumOld = Mid(vNumOld, 1, vCodTar)
            Else
                vReferenciaOld = String.Empty
                vNumOld = String.Empty
            End If


            If vReferenciaOld = "FATD_FATURAMENTO.ENTIDADE.ENTIDADETARIFA" Then
                vReferenciaOld = String.Empty
            End If

            If vReferenciaOld = String.Empty Then
                objTarifa.REFERENCIA = Convert.ToDateTime("01/01/0001")
            Else
                objTarifa.REFERENCIA = Convert.ToDateTime(vReferenciaOld)
            End If

            If vNumOld = String.Empty Then
                objTarifa.NUM = String.Empty
                objTarifa.NUM_OITO = String.Empty
            Else
                objTarifa.NUM = vNumOld & Microsoft.VisualBasic.Left("000000", IIf(vCodTar = 4, 6, 4))
                objTarifa.NUM_OITO = vCodTar
                objTarifa.LIMITKWH = vNumOld
            End If

            CarregarGrid(objTarifa)

            If lvwTarifas.Items.Count <> 0 Then

                lvwTarifas.Focus()
                lvwTarifas.Items.Item(0).Selected = True
                lvwTarifas.FocusedItem = lvwTarifas.Items.Item(0)
                lvwTarifas.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

            lvwTarifas.Items.Clear()
            lvwTarifas.Columns.Clear()
            lvwTarifas.Columns.Add(String.Empty, "Código", 100)
            lvwTarifas.Columns.Add(String.Empty, "Descrição", 100)
            lvwTarifas.Columns.Add(String.Empty, "Valor", 100)
            lvwTarifas.Columns.Add(String.Empty, "Limite kWh", 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 objTarifa As entidadeTarifa)

        Try
            PrepararListView()
            For Each objTarifaFor As entidadeTarifa In New repositorioTarifa().Select_2(objTarifa)
                AddListItem(mItem, objTarifaFor)
            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 objTarifa As entidadeTarifa)

        Try

            xItem = lvwTarifas.Items.Add(objTarifa.NUM.ToString(), objTarifa.NUM.ToString(), String.Empty)


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

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

            If (String.IsNullOrEmpty(objTarifa.LIMITKWH)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objTarifa.LIMITKWH)
            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 lvwTarifas.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
                    vDescricaoOld = IIf(String.IsNullOrEmpty((Item.SubItems(1).Text)), " ", (Item.SubItems(1).Text))
                    txtValor.Text = IIf(String.IsNullOrEmpty((Item.SubItems(2).Text)), "0", (Item.SubItems(2).Text))
                    vValorOld = IIf(String.IsNullOrEmpty((Item.SubItems(2).Text)), "0", (Item.SubItems(2).Text))
                    vLimitOld = IIf(String.IsNullOrEmpty((Item.SubItems(3).Text)), " ", (Item.SubItems(3).Text))

                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 PreencheCombobox()

        Try

            PreencherTarifa(cmbGrupoTarifario)

        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 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 Function lInsert() As Boolean

        Dim objTarifa As New entidadeTarifa
        Dim repositorioTarifa As New repositorioTarifa

        Try

            objTarifa.NUM = Trim(IIf(String.IsNullOrEmpty((vCodOld)), " ", vCodOld))
            objTarifa.DESCRI = Trim(IIf(String.IsNullOrEmpty((vDescricaoOld)), " ", vDescricaoOld))
            objTarifa.LIMITKWH = Trim(IIf(Trim(String.IsNullOrEmpty((vLimitOld))) = String.Empty, "NULL", vLimitOld))
            objTarifa.DATANOVA = Trim(IIf(String.IsNullOrEmpty((cmbData.Text)), Date.Now.ToShortDateString(), Format(Convert.ToDateTime(cmbData.Text), "dd/MM/yyyy")))
            objTarifa.REFERENCIA = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty((cmbData.Text)), Date.Now, cmbData.Text)))
            objTarifa.VALOR = Convert.ToDouble(Trim(IIf(String.IsNullOrEmpty(vValorOld), "0", vValorOld)))

            repositorioTarifa.Insert(objTarifa)

            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 objTarifa As New entidadeTarifa
        Dim repositorioTarifa As New repositorioTarifa


        Try


            objTarifa.NUM = Trim(IIf(String.IsNullOrEmpty((vCodOld)), " ", vCodOld))
            objTarifa.DESCRI = Trim(IIf(String.IsNullOrEmpty((vDescricaoOld)), " ", vDescricaoOld))
            objTarifa.LIMITKWH = Trim(IIf(Trim(String.IsNullOrEmpty((vLimitOld))) = String.Empty, "NULL", vLimitOld))
            objTarifa.DATANOVA = Trim(IIf(String.IsNullOrEmpty((cmbData.Text)), Date.Now.ToShortDateString(), Format(Convert.ToDateTime(cmbData.Text), "dd/MM/yyyy")))
            objTarifa.REFERENCIA = Convert.ToDateTime(Trim(IIf(String.IsNullOrEmpty((cmbData.Text)), Date.Now, cmbData.Text)))
            objTarifa.VALOR = Convert.ToDouble(Trim(IIf(String.IsNullOrEmpty(vValorOld), "0", vValorOld)))
            objTarifa.NUM_OITO = objTarifa.NUM
            objTarifa.UN = objTarifa.DATANOVA

            repositorioTarifa.Update(objTarifa)

            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


#End Region


End Class