Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Imports CrystalDecisions.CrystalReports.Engine

Friend Class frmPalm
    Inherits System.Windows.Forms.Form
    Dim vResp As Short

#Region "Propriedades"

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

        Try


            PreencheCombobox()
            PreencherRotas()

            cboLeituras.SelectedIndex = 0

            Me.txtMesAno.Text = VB6.Format(Date.Now.ToShortDateString(), "mm/yyyy")

            lblDiaVcto.Visible = True

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cboLeituras_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cboLeituras.SelectedIndexChanged

        Try


            If cboLeituras.Text = "Receber" Then
                Me.dtpLeitura.Enabled = True
                Me.dtpLeitura.Value = CDate("01/" & Me.txtMesAno.Text)
                lsvRotas.Enabled = False
            Else
                lsvRotas.Enabled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lsvRotas_Click(sender As Object, e As EventArgs) Handles lsvRotas.Click

        Try

            If lsvRotas.Items.Count > 0 Then

                If lsvRotas.FocusedItem.[Text].ToString() = "Todas as rotas" Then

                    If lsvRotas.FocusedItem.Checked = True Then
                        CheckAllListView(lsvRotas, False)
                    ElseIf lsvRotas.FocusedItem.Checked = False Then
                        CheckAllListView(lsvRotas, True)
                    End If

                Else
                    If lsvRotas.FocusedItem.Checked = False Then
                        lsvRotas.Items.Item(0).Checked = False
                        lsvRotas.FocusedItem.Checked = True
                    Else
                        lsvRotas.Items.Item(0).Checked = False
                        lsvRotas.FocusedItem.Checked = False
                    End If
                End If

            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub txtMesAno_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMesAno.Enter

        Try


            Me.txtMesAno.SelectionStart = 0
            Me.txtMesAno.SelectionLength = Len(Me.txtMesAno.Text)

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub txtMesAno_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMesAno.Leave

        Try


            Me.txtMesAno.Text = FormataData(txtMesAno, 1)

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdProcessar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdProcessar.Click

        Try

            If Trim(cboLeituras.Text) = "Enviar" Then
                EnviaLeituras()
            Else
                RecebeLeituras()
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - 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 um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub


#End Region

#Region "Métodos"

    Private Sub lClose()

        Try

            Me.Close()

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub PreencheCombobox()

        Try

            '--- Vencimentos
            Me.cbxDiaVencU.Items.Clear()
            PreencherDatasVencimento(cbxDiaVencU)

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub PreencherRotas()

        Dim lstrRot As String

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try

            Me.lsvRotas.Items.Clear()

            objUCFaturamento.SITUACAO = "'L','C','D','I'"

            vlist = repositorioUCFaturamento.SelectOthersTables_12(objUCFaturamento)

            If vlist.Count > 0 Then

                Me.lsvRotas.Items.Add("Todas as rotas")

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    lstrRot = VB6.Format(IIf(IsDBNull(objUCFaturamentoFor.ROTA), "0", objUCFaturamentoFor.ROTA), "0000")
                    Me.lsvRotas.Items.Add(lstrRot)

                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function MontaFiltroRotas() As String

        Dim lstrAux As String
        Dim lintIdx As Short

        Try

            lstrAux = ""

            With Me.lsvRotas
                If .Items.Item(0).Checked = True Then
                    For lintIdx = 1 To .Items.Count - 1
                        If .Items.Item(lintIdx).Checked = True Then
                            lstrAux = lstrAux & """" & .Items.Item(lintIdx).Text & ""","
                        End If
                    Next lintIdx
                    If Len(Trim(lstrAux)) > 0 Then
                        lstrAux = " (" & Microsoft.VisualBasic.Left(lstrAux, Len(lstrAux) - 1) & ") "
                    End If
                    If Len(Trim(lstrAux)) > 0 Then
                        lstrAux = " AND LEFT(rota,4) IN " & lstrAux & " "
                    End If
                End If
            End With
            MontaFiltroRotas = lstrAux


        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Function isMedia(ByVal astrOcorrencia As String) As Short

        Dim lintRet As Short

        Dim vlist

        Dim objOcorrencia As New entidadeOcorrencia
        Dim repositorioOcorrencia As New repositorioOcorrencia

        Try

            objOcorrencia.COD = Trim(astrOcorrencia)

            vlist = repositorioOcorrencia.Select_2(objOcorrencia)

            If vlist.Count > 0 Then

                For Each objOcorrenciaFor As entidadeOcorrencia In vlist
                    lintRet = IIf(IsDBNull(objOcorrenciaFor.MEDIA), 0, objOcorrenciaFor.MEDIA)
                Next

                isMedia = lintRet
            Else
                lintRet = 0
            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function MontaMedias(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String) As Double

        Dim lintAux As Short
        Dim ldblCon_1(11) As Double
        Dim ldblCon(11) As Double
        Dim llngDivisor As Integer
        Dim ldblConsMed As Double

        Dim vlist

        Dim objConsumos As New entidadeConsumos
        Dim repositorioConsumos As New repositorioConsumos

        Try

            objConsumos.ZONA = Trim(astrZona)
            objConsumos.LIVRO = Trim(astrLivro)
            objConsumos.CONTA = Trim(astrConta)

            vlist = repositorioConsumos.Select_1(objConsumos)

            If vlist.Count > 0 Then

                For Each objConsumosFor As entidadeConsumos In vlist

                    ldblCon_1(0) = IIf(IsDBNull(objConsumosFor.CONSUMO0), -1, objConsumosFor.CONSUMO0)
                    ldblCon_1(1) = IIf(IsDBNull(objConsumosFor.CONSUMO1), -1, objConsumosFor.CONSUMO1)
                    ldblCon_1(2) = IIf(IsDBNull(objConsumosFor.CONSUMO2), -1, objConsumosFor.CONSUMO2)
                    ldblCon_1(3) = IIf(IsDBNull(objConsumosFor.CONSUMO3), -1, objConsumosFor.CONSUMO3)
                    ldblCon_1(4) = IIf(IsDBNull(objConsumosFor.CONSUMO4), -1, objConsumosFor.CONSUMO4)
                    ldblCon_1(5) = IIf(IsDBNull(objConsumosFor.CONSUMO5), -1, objConsumosFor.CONSUMO5)
                    ldblCon_1(6) = IIf(IsDBNull(objConsumosFor.CONSUMO6), -1, objConsumosFor.CONSUMO6)
                    ldblCon_1(7) = IIf(IsDBNull(objConsumosFor.CONSUMO7), -1, objConsumosFor.CONSUMO7)
                    ldblCon_1(8) = IIf(IsDBNull(objConsumosFor.CONSUMO8), -1, objConsumosFor.CONSUMO8)
                    ldblCon_1(9) = IIf(IsDBNull(objConsumosFor.CONSUMO9), -1, objConsumosFor.CONSUMO9)
                    ldblCon_1(10) = IIf(IsDBNull(objConsumosFor.CONSUMO10), -1, objConsumosFor.CONSUMO10)
                    ldblCon_1(11) = IIf(IsDBNull(objConsumosFor.CONSUMO11), -1, objConsumosFor.CONSUMO11)

                Next

                llngDivisor = 0
                ldblConsMed = 0

                For lintAux = 11 To 0 Step -1

                    ldblCon(lintAux) = ldblCon_1(lintAux)

                    If ldblCon(lintAux) >= 0 Then
                        ldblConsMed = ldblConsMed + ldblCon(lintAux)
                        llngDivisor = llngDivisor + 1
                    End If

                Next lintAux

                If llngDivisor > 0 Then
                    ldblConsMed = ldblConsMed / llngDivisor
                Else
                    ldblConsMed = 0
                End If

            End If

            MontaMedias = Arredondar(ldblConsMed, 0)

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub BuscaConsIdUnidId(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByRef alngConsId As Integer, ByRef alngUnidId As Integer, ByRef astrNome As String, ByRef astrEndereco As String, ByRef astrCidade As String)
        Dim lstrNom As String
        Dim lstrEnd As String
        Dim lstrNum As String
        Dim lstrCom As String
        Dim lstrCid As String

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try

            objUCFaturamento.ZONA = Trim(astrZona)
            objUCFaturamento.LIVRO = Trim(astrLivro)
            objUCFaturamento.CONTA = Trim(astrConta)

            vlist = repositorioUCFaturamento.Select_4(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    alngConsId = IIf(IsDBNull(objUCFaturamentoFor.CONS_ID), 0, objUCFaturamentoFor.CONS_ID)
                    alngUnidId = IIf(IsDBNull(objUCFaturamentoFor.UNID_ID), 0, objUCFaturamentoFor.UNID_ID)
                    lstrNom = IIf(IsDBNull(objUCFaturamentoFor.NOME), "", objUCFaturamentoFor.NOME)
                    lstrEnd = Trim(IIf(IsDBNull(objUCFaturamentoFor.END), "", objUCFaturamentoFor.END))
                    lstrNum = Trim(IIf(IsDBNull(objUCFaturamentoFor.NUMERO), "", objUCFaturamentoFor.NUMERO))
                    lstrCom = Trim(IIf(IsDBNull(objUCFaturamentoFor.COMPLEMENT), "", objUCFaturamentoFor.COMPLEMENT))
                    lstrCid = Trim(IIf(IsDBNull(objUCFaturamentoFor.CIDADE), "", objUCFaturamentoFor.CIDADE))
                    astrNome = Microsoft.VisualBasic.Left(lstrNom, 50)
                    astrEndereco = Microsoft.VisualBasic.Left(lstrEnd & " " & lstrNum & " " & lstrCom, 100)
                    astrCidade = Microsoft.VisualBasic.Left(lstrCid, 20)

                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CheckAllListView(ByRef vlist As System.Windows.Forms.ListView, ByVal vCheck As Boolean)

        Dim i As Integer

        Try
            For i = 0 To vlist.Items.Count - 1
                vlist.Items.Item(i).Checked = vCheck
            Next i
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub EnviaLeituras()

        Dim lstrErr As String
        Dim ldblCMd As Double
        Dim lstrFil As String
        Dim lstrKVa As String
        Dim lstrMed As String
        Dim lstrSit As String
        Dim lstrZon As String
        Dim lstrLiv As String
        Dim lstrCon As String
        Dim lstrRot As String
        Dim ldblAnt As Double
        Dim lstrEnd As String
        Dim lstrNum As String
        Dim lstrCom As String
        Dim lstrCid As String
        Dim lstrNom As String
        Dim ldblKva As Double

        Dim vlist

        Dim objConsumiPalm As New entidadeConsumiPalm
        Dim repositorioConsumiPalm As New repositorioConsumiPalm

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try

            Me.lblInfo.Text = " Preparando banco de dados..."

            ' ----- Apaga dados da ConsumiPalm
            lDelete(objConsumiPalm)


            ' ----- Filtra Por Rota
            lstrFil = MontaFiltroRotas()

            If Len(lstrFil) = 0 Then
                MessageBox.Show("Você precisa selecionar ao menos uma rota!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)

                Me.lblInfo.Text = ""
                Me.lblInfo.Refresh()

            Else

                ' ----- Popula ConsumiPalm

                If cbxDiaVencU.SelectedIndex > 0 Then
                    objUCFaturamento.DIAVENC = cbxDiaVencU.Text
                End If

                If Me.chkDesligados.CheckState = 0 Then
                    objUCFaturamento.SITUACAO = "'D'"
                End If

                If Me.chkCortados.CheckState = 0 Then
                    objUCFaturamento.SITUACAO = "'C'"
                End If

                If Me.chkInativos.CheckState = 0 Then
                    objUCFaturamento.SITUACAO = "'I'"
                End If

                If gstrEmpresa_Sigla = "EFLUL" Then
                    objUCFaturamento.ROTA = "ORDER BY RIGHT(ROTA, 6) ASC "
                Else
                    objUCFaturamento.ROTA = "ORDER BY ROTA ASC "
                End If

                vlist = repositorioUCFaturamento.Select_8(objUCFaturamento)

                If vlist.Count > 0 Then

                    BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)

                    For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                        lstrErr = "medidor"

                        lstrMed = Trim(IIf(IsDBNull(objUCFaturamentoFor.NUM), "", objUCFaturamentoFor.NUM))
                        lstrErr = "medidor reativo"

                        lstrKVa = Trim(IIf(IsDBNull(objUCFaturamentoFor.MEDKVARH), "", objUCFaturamentoFor.MEDKVARH))
                        lstrErr = "situação"

                        lstrSit = Trim(IIf(IsDBNull(objUCFaturamentoFor.SITUACAO), "L", objUCFaturamentoFor.SITUACAO))
                        lstrErr = "zona"

                        lstrZon = Trim(IIf(IsDBNull(objUCFaturamentoFor.ZONA), "", objUCFaturamentoFor.ZONA))
                        lstrErr = "livro"

                        lstrLiv = Trim(IIf(IsDBNull(objUCFaturamentoFor.LIVRO), "", objUCFaturamentoFor.LIVRO))
                        lstrErr = "conta"

                        lstrCon = Trim(IIf(IsDBNull(objUCFaturamentoFor.CONTA), "", objUCFaturamentoFor.CONTA))
                        lstrErr = "rota"

                        lstrRot = Trim(IIf(IsDBNull(objUCFaturamentoFor.ROTA), "", objUCFaturamentoFor.ROTA))
                        lstrErr = "ultima leitura"

                        ldblAnt = Val(IIf(IsDBNull(objUCFaturamentoFor.ULTLEIT), 0, objUCFaturamentoFor.ULTLEIT))
                        lstrErr = "endereço"

                        lstrEnd = Trim(IIf(IsDBNull(objUCFaturamentoFor.END), "", objUCFaturamentoFor.END))
                        lstrErr = "número"

                        lstrNum = Trim(IIf(IsDBNull(objUCFaturamentoFor.NUMERO), "", objUCFaturamentoFor.NUMERO))
                        lstrErr = "complemento"

                        lstrCom = Trim(IIf(IsDBNull(objUCFaturamentoFor.COMPLEMENT), "", objUCFaturamentoFor.COMPLEMENT))
                        lstrErr = "cidade"

                        lstrCid = Trim(IIf(IsDBNull(objUCFaturamentoFor.CIDADE), "", objUCFaturamentoFor.CIDADE))
                        lstrErr = "nome"

                        lstrNom = Trim(IIf(IsDBNull(objUCFaturamentoFor.NOME), "NOME INDEFINIDO", objUCFaturamentoFor.NOME))
                        lstrErr = "leitura reativo"

                        ldblKva = Val(IIf(IsDBNull(objUCFaturamentoFor.KVARH), 0, objUCFaturamentoFor.KVARH))
                        ldblCMd = MontaMedias(lstrZon, lstrLiv, lstrCon)

                        objConsumiPalm.UNIQUEID = 0
                        objConsumiPalm.CATEGORY = 0
                        objConsumiPalm.DIRTY = 0
                        objConsumiPalm.SECRET = 0
                        objConsumiPalm.STATUS = 0
                        objConsumiPalm.ROTA = Mid(lstrRot, 1, 8)
                        objConsumiPalm.SEQ = VB6.Format(Mid(lstrRot, 5, 4), "0000")
                        objConsumiPalm.ZONA = Microsoft.VisualBasic.Left(lstrZon, 3)
                        objConsumiPalm.LIVRO = Microsoft.VisualBasic.Left(lstrLiv, 2)
                        objConsumiPalm.CONTA = Microsoft.VisualBasic.Left(lstrCon, 6)
                        objConsumiPalm.SETOR = Mid(lstrRot, 1, 4)
                        objConsumiPalm.LEIT_ANT = Replace(Replace(CStr(ldblAnt), ",", ""), ".", "")

                        If lstrSit = "L" Then
                            If Microsoft.VisualBasic.Right(lstrMed, 4) = "F***" Then
                                objConsumiPalm.LEIT_ATUAL = Replace(Replace(CStr(ldblAnt), ",", ""), ".", "")
                            Else
                                objConsumiPalm.LEIT_ATUAL = "0"
                            End If
                        Else
                            objConsumiPalm.LEIT_ATUAL = " "
                        End If

                        If IsNumeric(lstrMed) Then
                            objConsumiPalm.MEDIDOR = CDbl(lstrMed)
                        Else
                            objConsumiPalm.MEDIDOR = Microsoft.VisualBasic.Left(lstrMed, 30)
                        End If

                        objConsumiPalm.ENDERECO = Replace(Microsoft.VisualBasic.Left(lstrEnd & " " & lstrNum & " " & lstrCom, 100), "'", "\'")
                        objConsumiPalm.MUNICIP = Replace(Microsoft.VisualBasic.Left(lstrCid, 20), "'", "\'")
                        objConsumiPalm.DATA = Convert.ToDateTime(VB6.Format(Me.txtMesAno.Text, "YYYY-MM") & "-01")
                        objConsumiPalm.NOME = Replace(Microsoft.VisualBasic.Left(lstrNom, 50), "'", "\'")
                        objConsumiPalm.MEDIA = Replace(Replace(CStr(ldblCMd), ",", ""), ".", "")
                        objConsumiPalm.OCORRENC = "00"
                        objConsumiPalm.MEDKVARH = Microsoft.VisualBasic.Left(lstrKVa, 11)
                        objConsumiPalm.KVARH = Microsoft.VisualBasic.Left(Replace(Replace(CStr(ldblKva), ",", ""), ".", ""), 10)
                        objConsumiPalm.KVARHATUAL = 0
                        objConsumiPalm.SITUACAO = Microsoft.VisualBasic.Left(lstrSit, 1)

                        lInsert(objConsumiPalm)

                        BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)

                    Next

                End If

                Me.lblInfo.Text = " Pronto! Utilize a opção ""Receber"" no Palm"
                Me.lblInfo.Refresh()

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub RecebeLeituras()

        Dim lstrAux As String
        Dim ldblAtu As Double
        Dim ldblAnt As Double
        Dim lstrZon As String
        Dim lstrLiv As String
        Dim lstrCon As String
        Dim llngCId As Integer
        Dim llngUid As Integer
        Dim lstrNom As String
        Dim lstrRot As String
        Dim lstrSeq As String
        Dim lstrMed As String
        Dim lstrEnd As String
        Dim lstrCid As String
        Dim lstrOco As String
        Dim lstrMKv As String
        Dim lstrKVa As String
        Dim ldblVan As Double
        Dim ldblVat As Double
        Dim lintMed As Short
        Dim lintQNL As Short
        Dim lblnRel As Boolean

        Dim vlist

        Dim objConsumiPalm As New entidadeConsumiPalm
        Dim repositorioConsumiPalm As New repositorioConsumiPalm

        Dim objLeitmensal As New entidadeLeitmensal

        Try

            Me.lblInfo.Text = " Atualizando tabela LeitMensal... "
            Me.lblInfo.Refresh()

            ' ----- Pega as rotas que tem na ConsumiPalm

            vlist = repositorioConsumiPalm.Select(objConsumiPalm)

            If vlist.Count > 0 Then

                lstrRot = ""

                For Each objConsumiPalmFor As entidadeConsumiPalm In vlist

                    If Trim(lstrRot) = "" Then
                        lstrRot = lstrRot & " " & IIf(IsDBNull(objConsumiPalmFor.ROTA), "", objConsumiPalmFor.ROTA)
                    Else
                        lstrRot = lstrRot & ", " & IIf(IsDBNull(objConsumiPalmFor.ROTA), "", objConsumiPalmFor.ROTA)
                    End If

                Next

            End If

            lblnRel = False
            lintQNL = 0

            vlist = repositorioConsumiPalm.Select_1(objConsumiPalm)

            If vlist.Count > 0 Then

                BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)

                ' DELETA AS LEITURAS DA TABELA LEITMENSAL
                ' ------------------------------------------------------------------------
                Me.lblInfo.Text = " Apagando leituras desta rota... "
                Me.lblInfo.Refresh()

                objLeitmensal.ROTA = lstrRot
                lDelete(objLeitmensal)

                For Each objConsumiPalmFor As entidadeConsumiPalm In vlist

                    ' Verifica se teve alguma leitura não efetuada

                    lstrZon = Trim(IIf(IsDBNull(objConsumiPalmFor.ZONA), "", objConsumiPalmFor.ZONA))

                    lstrLiv = Trim(IIf(IsDBNull(objConsumiPalmFor.LIVRO), "", objConsumiPalmFor.LIVRO))

                    lstrCon = Trim(IIf(IsDBNull(objConsumiPalmFor.CONTA), "", objConsumiPalmFor.CONTA))

                    lstrAux = Trim(IIf(IsDBNull(objConsumiPalmFor.LEIT_ATUAL), 0, objConsumiPalmFor.LEIT_ATUAL))
                    ldblAtu = IIf(IsNumeric(lstrAux), lstrAux, 0)

                    lstrAux = Trim(IIf(IsDBNull(objConsumiPalmFor.LEIT_ANT), 0, objConsumiPalmFor.LEIT_ANT))
                    ldblAnt = IIf(IsNumeric(lstrAux), lstrAux, 0)

                    lstrRot = Trim(IIf(IsDBNull(objConsumiPalmFor.ROTA), "", objConsumiPalmFor.ROTA))

                    lstrSeq = Trim(IIf(IsDBNull(objConsumiPalmFor.SEQ), "", objConsumiPalmFor.SEQ))

                    lstrMed = Trim(IIf(IsDBNull(objConsumiPalmFor.MEDIDOR), "", objConsumiPalmFor.MEDIDOR))

                    '          lstrNom = Strings.Trim(IIf(IsNull(objConsumiPalmFor.nome), "", objConsumiPalmFor.nome))
                    '          lstrEnd = Strings.Trim(IIf(IsNull(objConsumiPalmFor.endereco), "", objConsumiPalmFor.endereco))
                    '          lstrCid = Strings.Trim(IIf(IsNull(objConsumiPalmFor.municip), "", objConsumiPalmFor.municip))


                    lstrOco = Trim(IIf(IsDBNull(objConsumiPalmFor.OCORRENC), "", objConsumiPalmFor.OCORRENC))

                    lstrMKv = Trim(IIf(IsDBNull(objConsumiPalmFor.MEDKVARH), "", objConsumiPalmFor.MEDKVARH))

                    lstrAux = Trim(IIf(IsDBNull(objConsumiPalmFor.KVARH), 0, objConsumiPalmFor.KVARH))
                    ldblVan = IIf(IsNumeric(lstrAux), lstrAux, 0)

                    lstrAux = Trim(IIf(IsDBNull(objConsumiPalmFor.KVARHATUAL), 0, objConsumiPalmFor.KVARHATUAL))
                    ldblVat = IIf(IsNumeric(lstrAux), lstrAux, 0)

                    BuscaConsIdUnidId(lstrZon, lstrLiv, lstrCon, llngCId, llngUid, lstrNom, lstrEnd, lstrCid)

                    lintMed = isMedia(lstrOco)

                    If ldblAtu = 0 Then
                        lblnRel = True
                        lintQNL = lintQNL + 1
                    End If

                    If llngCId > 0 And llngUid > 0 Then

                        objLeitmensal.STATUS = "1"
                        objLeitmensal.ROTA = lstrRot
                        objLeitmensal.SEQ = lstrSeq
                        objLeitmensal.ZONA = lstrZon
                        objLeitmensal.LIVRO = lstrLiv
                        objLeitmensal.CONTA = lstrCon
                        objLeitmensal.LEIT_ANT = Replace(Replace(CStr(ldblAnt), ",", ""), ".", "")
                        objLeitmensal.LEIT_ATUAL = Replace(Replace(CStr(ldblAtu), ",", ""), ".", "")
                        objLeitmensal.MEDIDOR = lstrMed
                        objLeitmensal.ENDERECO = Replace(lstrEnd, "'", "\'")
                        objLeitmensal.NOME = Replace(lstrNom, "'", "\'")
                        objLeitmensal.MUNICIP = Replace(lstrCid, "'", "\'")
                        objLeitmensal.MEDIA = lintMed
                        objLeitmensal.OCORRENC = lstrOco
                        objLeitmensal.MEDKVARH = lstrMKv
                        objLeitmensal.KVARH = Replace(Replace(CStr(ldblVan), ",", ""), ".", "")
                        objLeitmensal.KVARHATUAL = Replace(Replace(CStr(ldblVat), ",", ""), ".", "")
                        objLeitmensal.DT_LEIT = Me.dtpLeitura.Value
                        objLeitmensal.CONS_ID = llngCId
                        objLeitmensal.UNID_ID = llngUid


                    End If


                    BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)

                Next

                Me.lblInfo.Text = " Fim do processamento!"
                Me.lblInfo.Refresh()
            Else
                MessageBox.Show("Não foi encontrado nenhuma leitura. Verifique!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            If lintQNL > 0 Then

                vResp = MessageBox.Show(lintQNL & " leituras não efetuadas. Emitir relatório?", "Informação", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

                If vResp = DialogResult.Yes Then
                    lPrint()
                End If

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub lPrint()

        Dim dt As DataTable
        Dim dc As DataColumn
        Dim ds As DataSet

        Dim bytBLOBData() As Byte

        Dim rpt As New ReportDocument()

        Dim vlist

        Dim objConsumiPalm As New entidadeConsumiPalm
        Dim repositorioConsumiPalm As New repositorioConsumiPalm

        Dim objEmpresa As New entidadeEmpresa
        Dim repositorioEmpresa As New repositorioEmpresa

        Try

            ds = New DataSet

            vlist = repositorioEmpresa.Select(objEmpresa)

            If vlist.Count <> 0 Then

                For Each objEmpresaFor As entidadeEmpresa In vlist

                    bytBLOBData = objEmpresaFor.LOGOTIPO

                Next

            End If

            dt = repositorioConsumiPalm.Select_2(objConsumiPalm)

            If dt.Rows.Count > 0 Then

                dc = New DataColumn("IMAGE", GetType(Byte()))
                dc.DefaultValue = bytBLOBData
                dt.Columns.Add(dc)

            End If

            ds.Tables.Add(dt)
            ds.Tables(0).TableName = "REL_LEITURA_NAO_EFETUADA"

            If ds.Tables(0).Rows.Count = 0 Then
                MessageBox.Show("Não há registros para o relatório escolhido! ", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            Else

                rpt = New rptLeiturasNaoEfetuadas

                rpt.SetDataSource(ds)

                frmViewRelatorios.rpt = rpt

                frmViewRelatorios.CRViewer.Zoom((100))
                frmViewRelatorios.Text = "Relatório de Leituras não Efetuadas"
                frmViewRelatorios.ShowDialog()

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function lInsert(ByRef objLeitmensal As entidadeLeitmensal) As Boolean
        Dim repositorioLeitmensal As New repositorioLeitmensal
        Try

            repositorioLeitmensal.Insert_1(objLeitmensal)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function lDelete(ByRef objLeitmensal As entidadeLeitmensal) As Boolean
        Dim repositorioLeitmensal As New repositorioLeitmensal
        Try

            repositorioLeitmensal.Delete_1(objLeitmensal)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function lDelete(ByRef objConsumiPalm As entidadeConsumiPalm) As Boolean
        Dim repositorioConsumiPalm As New repositorioConsumiPalm
        Try

            repositorioConsumiPalm.Delete(objConsumiPalm)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function lInsert(ByRef objConsumiPalm As entidadeConsumiPalm) As Boolean
        Dim repositorioConsumiPalm As New repositorioConsumiPalm
        Try

            repositorioConsumiPalm.Insert(objConsumiPalm)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

#End Region


End Class