Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE

Public Class frmFatGrupoAaaa

    Private ilngAnoMes_Fat As Long 'REN 863/2019 - mês civil
    Private ilngMatricula As Long
    Private idblConsId As Double
    Private idblUnidId As Double
    Private istrClasse As String
    Private istrQH As String
    Private istrNrBco As String
    Private istrNmBco As String
    Private istrAgencia As String
    Private istrContaCorrente As String
    Private istrCpfCnpj As String
    Private istrInsEst As String
    Private istrUF As String
    Private istrTensao As String
    Private istrFase As String
    Private istrRota As String
    Private istrcaderno As String
    Private idblCfop As Double
    Private iblnIcmsDemLida As Boolean
    Private iblnParCativo As Boolean
    Private iblnPeriodoTeste As Boolean
    Private idteIniPeriodoTeste As Date
    Private idteFimPeriodoTeste As Date
    Private iintLivreEspecial As Short
    Private iintLivreVerde As Integer
    Private iintLivreLeituraConsumo As Short
    Private iintMicroGeracao As Short
    Private iblnMicroGeracaoConvenioSefaz As Boolean
    Private iCep As String
    Private iIBGE As String
    Private iUF As String
    Private iCidade As String


    Private iintMesIniPerSeco As Short
    Private iintMesFimPerSeco As Short
    Private istrRes414_Art93 As String
    Private istrRes414_Art104 As String
    Private idteBase As Date

    Private iintBanderiaVigente As Short
    Private idteBandeira As Date
    Private idblNumNf As Double
    Private idblNsuNr As Double

    Private iintTipoTarifa As Short

    Private iblnExisteLeitura As Boolean 'Revisado em 15/05/2015

    'geral
    Private BaseICMS As Double
    Private BaseICMS2 As Double
    Private BasePis As Double
    Private BaseCofins As Double
    Private idblBasePisCofins As Double
    Private ICMS As Double
    Private ICMS2 As Double
    '-- Leituras Anteriores
    Private ant_consumo_p As Double
    Private ant_consumo_fp As Double
    Private ant_demanda_p As Double
    Private ant_demanda_fp As Double
    Private ant_demanda_ultra_p As Double
    Private ant_demanda_ultra_fp As Double
    Private ant_kvarh As Double
    Private ant_kvarh_fp As Double
    Private ant_kwh_cap_reat_fp As Double
    'Micro Geração
    Private ant_reverso_p As Double
    Private ant_reverso_fp As Double
    '-- Tarifas do Convencional
    Private tarConsumo As Double
    Private tarConsumoSemDesconto As Double
    Private tarConsumoBan As Double
    Private tarDemanda As Double
    Private tarDemUltra As Double
    Private tarExtra As Double

    '-- Tarifas do Horo-Sazonal (Verde e Azul)
    Private idblTarConsumo_p As Double
    Private idblTarConsumo_p_tusd As Double
    Private idblTarConsumo_p_te As Double
    Private idblTarConsumo_fp As Double
    Private idblTarConsumo_fp_tusd As Double
    Private idblTarConsumo_fp_te As Double
    Private idblTarConsumoBan_p As Double
    Private idblTarConsumoBan_fp As Double
    Private idblTarConsumoSemDesconto_p As Double
    Private idblTarConsumoSemDesconto_fp As Double
    'Compensado GD
    Private idblDescontoGD_p_tusd As Double
    Private idblDescontoGD_p_te As Double
    Private idblDescontoGD_fp_tusd As Double
    Private idblDescontoGD_fp_te As Double

    Private idblTarDemanda_p As Double
    Private idblTarDemanda_fp As Double
    Private idblTarDemUltra_p As Double
    Private idblTarDemUltra_fp As Double
    'Se for parcialmente cativo
    Private idblTarConsumoLiv_p As Double
    Private idblTarConsumoLiv_fp As Double

    'Tarifa TE residencial normal usado para calculo do consumo reativo
    Private idblTarTe_B1 As Double

    '-- Aliquotas
    Private idblAliqPIS As Double
    Private idblAliqCofins As Double
    Private idblAliqICMS As Double
    Private idblAliqICMS2 As Double

    Private istrFlgCalcPisCofNAss As String
    Private istrFlgCalcPisCof As String

    '-- Contém todos os codigos que não aparecerão no grid
    Private Item_Fatura As String
    Private FP As String
    '-- Pra ver o esquema da res. 49, paragr.2 - Ultimos 12 consumos demanda
    Private idteContratoDemanda As Date
    Private nAjuste_Demanda_P As Double
    Private nAjuste_Demanda_FP As Double
    Private nQtiMeses As Short
    '
    Private ccee_titul_anterior As String
    '
    'Controle dos itens tributados individualmente
    Private idbl_Ite_Pic(15) As Double 'itens que pertence a base de pis/cofis
    Private idbl_Ite_Icm(15) As Double 'itens que pertence a base de icms
    '
    Private idbl_Bas_Icm(15) As Double 'base do icms
    Private idbl_Bas_Pic(15) As Double 'base do pis e cofins
    '
    Private idbl_Vlr_Pis(15) As Double 'valor do pis de cada item
    Private idbl_Vlr_Cof(15) As Double 'valor do cofins de cada item
    Private idbl_Vlr_Icm(15) As Double 'valor do icms
    '
    Private idbl_Ret_Con(15) As Double 'base da rentação tributária para itens de consumo
    Private idbl_Ret_Dem(15) As Double 'base da rentação tributária para itens de demanda
    '
    Private istr_Bas_Icm(15) As String 'codigos da base de icms
    Private istr_Bas_Pis(15) As String 'codigos da base de pis
    Private istr_Bas_Cof(15) As String 'codigos da base de cofins
    Private istr_Vlr_Icm(15) As String 'codigos do valor do icms
    Private istr_Vlr_Pis(15) As String 'codigos do valor do pis
    Private istr_Vlr_Cof(15) As String 'codigos do valor do cofins
    Private istr_Ite_Icm(15) As String 'codigos do valor do item para o icms
    Private istr_Ite_Pis(15) As String 'codigos do valor do item para o pis
    Private istr_Ite_Cof(15) As String 'codigos do valor do item para o cofins

    Dim vResp As Short

    Public Sub New()

        ' Esta chamada é requerida pelo designer.
        InitializeComponent()

        ' Adicione qualquer inicialização após a chamada InitializeComponent().

    End Sub

#Region "Propriedades"

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

        Try
            idteBase = Date.Now

            gFormularioParaLog = Me.Text

            Me.txtMesAno.Text = GetConfig("mes.ano.faturamento")
            Me.txtMesAno.Text = FormataData(Me.txtMesAno, 1)

            If Me.txtMesAno.Text = "" Then
                Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Date.Now), Year(Date.Now)) & "/" & VB6.Format(Date.Now, "MM/YYYY")).ToOADate)
            Else
                Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Me.txtMesAno.Text), Year(Me.txtMesAno.Text)) & "/" & VB6.Format(Me.txtMesAno.Text, "MM/YYYY")).ToOADate)
            End If

            Monta_MesAno_Civil()
            PreencherGridUnidade()

            'Me.sstLeituras.SelectedIndex = 0

            Me.sstLeituras.TabPages.RemoveAt(0)
            'Me.sstLeituras.TabPages.RemoveAt(2)

            iintMesIniPerSeco = Val(GetConfig("mes.ini.periodo.seco"))
            iintMesFimPerSeco = iintMesIniPerSeco + 6

            istrRes414_Art93 = Trim(GetConfig("resolucao.414.art.93"))
            istrFlgCalcPisCof = Trim(GetConfig("CALCULA.PIS.COFINS"))
            istrFlgCalcPisCofNAss = Trim(GetConfig("calcula.pis.cofins.nao.socio"))

            If istrRes414_Art93 = "-1" Then
                istrRes414_Art93 = "N"
                SetConfig("resolucao.414.art.93", "String", istrRes414_Art93, istrRes414_Art93, "Aplicar a regra da resolução 414 artigo 93.")
            ElseIf Len(istrRes414_Art93) = 0 Then
                istrRes414_Art93 = "N"
                SetConfig("resolucao.414.art.93", "String", istrRes414_Art93, istrRes414_Art93, "Aplicar a regra da resolução 414 artigo 93.")
            End If

            istrRes414_Art104 = Trim(GetConfig("resolucao.414.art.104"))

            If istrRes414_Art104 = "-1" Then
                istrRes414_Art104 = "N"
                SetConfig("resolucao.414.art.104", "String", istrRes414_Art104, istrRes414_Art104, "Aplicar a regra da resolução 414 artigo 104.")
            ElseIf Len(istrRes414_Art104) = 0 Then
                istrRes414_Art104 = "N"
                SetConfig("resolucao.414.art.104", "String", istrRes414_Art104, istrRes414_Art104, "Aplicar a regra da resolução 414 artigo 104.")
            End If

            Me.dtpMesAnoConsumo.Value = CDate("01/" & 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 mhgDados_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mhgDados.DblClick

        Try


            Me.lblStatus.Text = ""

            With mhgDados
                If .Row > 0 Then
                    '000.00.000000
                    Me.txtZona.Text = Mid(.get_TextMatrix(.Row, 0), 1, 3)
                    Me.txtLivro.Text = Mid(.get_TextMatrix(.Row, 0), 5, 2)
                    Me.txtConta.Text = Mid(.get_TextMatrix(.Row, 0), 8)
                End If
            End With

            txtConta_Leave(txtConta, New System.EventArgs())

            CarregaGridFatura()

            Me.txtDt_Faturamento.Focus()

        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 mhgDados_ClickEvent(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mhgDados.ClickEvent


        Try

            If mhgDados.Rows > 1 Then
                mhgDados.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightAlways
            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 grid_fatura_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles grid_fatura.DblClick

        Dim vMessage As String

        Try

            With grid_fatura
                vMessage = "Informações do Item da Fatura" & vbCrLf & vbCrLf
                vMessage = vMessage & "Código: " & .get_TextMatrix(.Row, 0) & vbCrLf
                vMessage = vMessage & "Descrição: " & .get_TextMatrix(.Row, 1) & vbCrLf
                vMessage = vMessage & "Quantidade: " & .get_TextMatrix(.Row, 2) & vbCrLf
                vMessage = vMessage & "Valor: R$ " & .get_TextMatrix(.Row, 3) & vbCrLf
            End With


            MessageBox.Show(vMessage, "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)

        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 opbDesligados_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbDesligados.CheckedChanged


        Try


            If eventSender.Checked Then
                PreencherGridUnidade()
            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 opbLigados_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbLigados.CheckedChanged


        Try

            If eventSender.Checked Then
                PreencherGridUnidade()
            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 opbTodos_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbTodos.CheckedChanged

        Try

            If eventSender.Checked Then
                PreencherGridUnidade()
            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 optZLC_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optZLC.CheckedChanged

        Try


            If eventSender.Checked Then
                PreencherGridUnidade()
            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 optNome_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optNome.CheckedChanged

        Try


            If eventSender.Checked Then
                PreencherGridUnidade()
            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 optTarifa_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optTarifa.CheckedChanged

        Try


            If eventSender.Checked Then
                PreencherGridUnidade()
            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 cmdGravarFatura_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGravarFatura.Click
        Dim lstr_MesAno_Config As String = GetConfig("mes.ano.faturamento")

        Dim lblnContinua As Boolean

        Dim ldte_MesAnoConfig As Date = Convert.ToDateTime("01/" & lstr_MesAno_Config)
        Dim ldte_MesAnoFat As Date = Convert.ToDateTime("01/" & txtMesAno.Text)

        ldte_MesAnoFat = Convert.ToDateTime(UltimoDiaMes(ldte_MesAnoFat.Month, ldte_MesAnoFat.Year) & "/" & Strings.Format(ldte_MesAnoFat, "MM/yyy"))


        Try

            lblnContinua = True



            If ldte_MesAnoFat >= DateAndTime.DateAdd("d", -1, ldte_MesAnoConfig) Then
                If Mid(txtTA.Text, 1, 4) = "01AL" And CDbl(IIf(IsNumeric(Me.txtCCEEValorIcms.Text), Me.txtCCEEValorIcms.Text, 0)) = 0 Then
                    lblnContinua = MsgBox("Você não informou o valor da comercialização!" & vbCrLf & "Tem certeza que deseja continuar mesmo assim?", MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton1, gstrTituloMensagem) = MsgBoxResult.Yes
                End If
                If lblnContinua Then
                    LigDesBotoes(False)
                    Grava_Fatura()
                    LigDesBotoes(True)
                End If
            Else

                MessageBox.Show("Você não pode efetuar a gravação em faturas com o mês já encerrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            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 Txt_Auto_Consumo_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Consumo.Enter

        Try

            With Me.txt_Auto_Consumo
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txt_Auto_Consumo_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Consumo.Leave


        Try


            With Me.txt_Auto_Consumo
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With


        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 Txt_Auto_Deficit_Dem_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Deficit_Dem.Enter



        Try


            With Me.txt_Auto_Deficit_Dem
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 Txt_Auto_Deficit_Dem_HI_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Deficit_Dem_HI.Enter



        Try


            With Me.txt_Auto_Deficit_Dem_HI
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txt_Auto_Deficit_Dem_HI_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Deficit_Dem_HI.Leave



        Try


            With Me.txt_Auto_Deficit_Dem_HI
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With



        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 txt_Auto_Deficit_Dem_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Deficit_Dem.Leave




        Try


            With Me.txt_Auto_Deficit_Dem
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With



        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 Txt_Auto_Dem_Supl_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Dem_Supl.Enter




        Try


            With Me.txt_Auto_Dem_Supl
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txt_Auto_Dem_Supl_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txt_Auto_Dem_Supl.Leave




        Try



            With Me.txt_Auto_Dem_Supl
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With


        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 txtAjusteDemandaFP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaFP.Enter



        Try


            With Me.txtAjusteDemandaFP
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtajustedemandafp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaFP.Leave



        Try


            With Me.txtAjusteDemandaFP
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With



        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 txtAjusteDemandaP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaP.Enter



        Try


            With Me.txtAjusteDemandaP
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtajustedemandap_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaP.Leave



        Try


            With Me.txtAjusteDemandaP
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With



        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 txtCCEEAliquotaCofins_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEAliquotaCofins.Enter



        Try


            With Me.txtCCEEAliquotaCofins
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = CInt(Len(.Text))
            End With



        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 txtCCEEAliquotaCofins_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCCEEAliquotaCofins.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.Back And (KeyAscii <> 44 And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9)) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = 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 txtCCEEAliquotaCofins_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEAliquotaCofins.Leave



        Try



            With Me.txtCCEEAliquotaPis
                .Text = VB6.Format(.Text, "#,#####0.00000")
            End With


        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 txtCCEEAliquotaIcms_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEAliquotaIcms.Enter


        Try


            With Me.txtCCEEAliquotaIcms
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = CInt(Len(.Text))
            End With




        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 txtCCEEAliquotaIcms_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCCEEAliquotaIcms.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.Back And (KeyAscii <> 44 And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9)) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = 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 txtCCEEAliquotaIcms_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEAliquotaIcms.Leave



        Try


            With Me.txtCCEEAliquotaIcms
                .Text = VB6.Format(.Text, "#,#####0.00000")
            End With



        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 txtCCEEAliquotaPis_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEAliquotaPis.Enter



        Try



            With Me.txtCCEEAliquotaPis
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = CInt(Len(.Text))
            End With


        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 txtCCEEAliquotaPis_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCCEEAliquotaPis.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.Back And (KeyAscii <> 44 And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9)) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = 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 txtCCEEAliquotaPis_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEAliquotaPis.Leave



        Try


            With Me.txtCCEEAliquotaPis
                .Text = VB6.Format(.Text, "#,#####0.00000")
            End With



        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 txtCCEEConsumoTotal_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEConsumoTotal.Enter



        Try



            With Me.txtCCEEConsumoTotal
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = CInt(Len(.Text))
            End With


        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 txtCCEEConsumoTotal_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCCEEConsumoTotal.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.Back And (KeyAscii <> 44 And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9)) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = 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 txtCCEEConsumoTotal_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEConsumoTotal.Leave



        Try


            With Me.txtCCEEConsumoTotal
                .Text = VB6.Format(.Text, "#,##0.00")
            End With



        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 txtCCEEEnergiaComprada_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEEnergiaComprada.Enter



        Try


            With Me.txtCCEEEnergiaComprada
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = CInt(Len(.Text))
            End With



        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 txtCCEEEnergiaComprada_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCCEEEnergiaComprada.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.Back And (KeyAscii <> 44 And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9)) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = 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 txtCCEEEnergiaComprada_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEEnergiaComprada.Leave



        Try


            With Me.txtCCEEEnergiaComprada
                .Text = VB6.Format(.Text, "#,##0.00")
            End With



        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 txtCCEEPrecoMedio_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEPrecoMedio.Enter


        Try



            With Me.txtCCEEPrecoMedio
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = CInt(Len(.Text))
            End With



        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 txtCCEEPrecoMedio_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCCEEPrecoMedio.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.Back And (KeyAscii <> 44 And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9)) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = 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 txtCCEEPrecoMedio_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCCEEPrecoMedio.Leave



        Try



            With Me.txtCCEEPrecoMedio
                .Text = VB6.Format(.Text, "#,#####0.00000")
            End With


        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 txtConsumo_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_FP.Enter



        Try


            With Me.txtConsumo_FP
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtConsumo_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_FP.Leave



        Try



            With Me.txtConsumo_FP
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With


        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 txtConsumo_p_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_p.Enter



        Try


            With Me.txtConsumo_p
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtConsumo_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_p.Leave



        Try


            With Me.txtConsumo_p
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtConta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Enter

        Try


            txtConta.SelectionStart = 0
            txtConta.SelectionLength = Len(txtConta.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 txtConta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Leave

        Try

            If Len(txtConta.Text) >= 1 Then
                If IsNumeric(Me.txtConta.Text) Then
                    Me.txtConta.Text = VB6.Format(Me.txtConta.Text, "000000")
                Else
                    Me.txtConta.Text = ""
                End If
            End If

            Loca_Consumidor()

        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 txtDem_Exc_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_FP.Enter

        Try

            With Me.txtDem_Exc_FP
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With

        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 txtdem_exc_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_FP.Leave



        Try


            With Me.txtDem_Exc_FP
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtDem_Exc_Ponta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_Ponta.Enter



        Try



            With Me.txtDem_Exc_Ponta
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txtdem_exc_ponta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_Ponta.Leave



        Try


            With Me.txtDem_Exc_Ponta
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtDemanda_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_FP.Enter



        Try



            With Me.txtDemanda_FP
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txtDemanda_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_FP.Leave



        Try



            With Me.txtDemanda_FP
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With


        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 txtDemanda_p_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_p.Enter



        Try


            With Me.txtDemanda_p
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtDemanda_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_p.Leave



        Try


            With Me.txtDemanda_p
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtDt_Apresenta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Apresenta.Enter

        Try



            txtDt_Apresenta.SelectionStart = 0
            txtDt_Apresenta.SelectionLength = Len(txtDt_Apresenta.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 txtDt_Apresenta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Apresenta.Leave


        'Try


        '    txtDt_Apresenta.Text = FormataData(txtDt_Apresenta, 2)
        '    If Len(Trim(txtDt_Apresenta.Text)) > 0 Then
        '        txtDt_Vencto.Text = CStr(BuscaDtVcto(CDate(txtDt_Apresenta.Text)))
        '    Else
        '        txtDt_Vencto.Text = ""
        '    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 txtDt_Faturamento_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Faturamento.Enter



        Try


            txtDt_Faturamento.SelectionStart = 0
            txtDt_Faturamento.SelectionLength = Len(txtDt_Faturamento.Text)
            HabilitaGuias()



        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 txtDt_Faturamento_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Faturamento.Leave

        Try

            txtDt_Faturamento.Text = FormataData(txtDt_Faturamento, 2)


        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 txtDt_Leit_Anterior_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Anterior.Enter


        Try

            txtDt_Leit_Anterior.SelectionStart = 0
            txtDt_Leit_Anterior.SelectionLength = Len(txtDt_Leit_Anterior.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 txtDt_Leit_Anterior_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Anterior.Leave


        Try


            txtDt_Leit_Anterior.Text = FormataData(txtDt_Leit_Anterior, 2)

        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 txtDt_Leit_Atual_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Atual.Enter


        Try


            txtDt_Leit_Atual.SelectionStart = 0
            txtDt_Leit_Atual.SelectionLength = Len(txtDt_Leit_Atual.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 txtDt_Leit_Atual_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Atual.Leave


        Try

            txtDt_Leit_Atual.Text = FormataData(txtDt_Leit_Atual, 2)


        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 txtDt_Prox_Leit_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Prox_Leit.Enter


        Try


            txtDt_Prox_Leit.SelectionStart = 0
            txtDt_Prox_Leit.SelectionLength = Len(txtDt_Prox_Leit.Text)

            If Len(Trim(txtDt_Apresenta.Text)) = 0 Then
                MessageBox.Show("É necessário informar uma Data de Apresentação!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtDt_Apresenta.Focus()
                System.Windows.Forms.Application.DoEvents()
                Exit Sub
            End If
            If Len(Trim(txtDt_Vencto.Text)) = 0 Then
                MessageBox.Show("É necessário informar uma Data de Vencimento!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtDt_Vencto.Focus()
                System.Windows.Forms.Application.DoEvents()
                Exit Sub
            End If
            If Mid(istrClasse, 1, 2) = "62" Or Mid(istrClasse, 1, 2) = "63" Or Mid(istrClasse, 1, 2) = "64" Then
                If System.DateTime.FromOADate(CDate(txtDt_Vencto.Text).ToOADate - CDate(txtDt_Apresenta.Text).ToOADate) < System.DateTime.FromOADate(10) Then
                    MessageBox.Show("Atenção! Data de vencimento inferior a dez dias da apresentação!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
            Else
                If System.DateTime.FromOADate(CDate(txtDt_Vencto.Text).ToOADate - CDate(txtDt_Apresenta.Text).ToOADate) < System.DateTime.FromOADate(5) Then
                    MessageBox.Show("Atenção! Data de vencimento inferior a cinco dias da apresentação!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                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 txtDt_Prox_Leit_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Prox_Leit.Leave


        Try


            txtDt_Prox_Leit.Text = FormataData(txtDt_Prox_Leit, 2)

        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 txtDt_Vencto_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Vencto.Enter

        Try

            txtDt_Vencto.SelectionStart = 0
            txtDt_Vencto.SelectionLength = Len(txtDt_Vencto.Text)

            If Len(Trim(txtDt_Leit_Atual.Text)) = 0 Then
                MessageBox.Show("É necessário informar a Data de Leitura Atual!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtDt_Leit_Atual.Focus()
                System.Windows.Forms.Application.DoEvents()
                Exit Sub
            End If
            If Len(Trim(txtDt_Leit_Anterior.Text)) = 0 Then
                MessageBox.Show("É necessário informar a Data de Leitura Anterior!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtDt_Leit_Anterior.Focus()
                System.Windows.Forms.Application.DoEvents()
                Exit Sub
            End If
            If System.DateTime.FromOADate(CDate(txtDt_Leit_Atual.Text).ToOADate - CDate(txtDt_Leit_Anterior.Text).ToOADate) > System.DateTime.FromOADate(33) Then
                MessageBox.Show("Atenção! Período de leitura superior a 33 dias!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)

            ElseIf System.DateTime.FromOADate(CDate(txtDt_Leit_Atual.Text).ToOADate - CDate(txtDt_Leit_Anterior.Text).ToOADate) < System.DateTime.FromOADate(27) Then
                MessageBox.Show("Atenção! Período de leitura inferior a 27 dias!", "Inromação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            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 txtDt_Vencto_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Vencto.Leave


        Try

            txtDt_Vencto.Text = FormataData(txtDt_Vencto, 2)


        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 txtKvarh_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_FP.Enter


        Try

            With Me.txtKvarh_FP
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txtkvarh_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_FP.Leave

        Try


            With Me.txtKvarh_FP
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtKvarh_P_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_P.Enter

        Try


            With Me.txtKvarh_P
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtkvarh_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_P.Leave

        Try

            With Me.txtKvarh_P
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With




        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 txtLeit_Consumo_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Consumo.Enter

        Try


            With Me.txtLeit_Consumo
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtLeit_Consumo_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Consumo.Leave

        Try


            With Me.txtLeit_Consumo
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With



        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 txtLeit_Demanda_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Demanda.Enter

        Try


            With Me.txtLeit_Demanda
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtLeit_Demanda_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Demanda.Leave

        Try



            With Me.txtLeit_Demanda
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With


        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 txtLeit_Kvarh_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Kvarh.Enter

        Try


            With Me.txtLeit_Kvarh
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtLeit_Kvarh_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Kvarh.Leave

        Try


            With Me.txtLeit_Kvarh
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00")
                End If
            End With



        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 txtLivro_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Enter

        Try


            txtLivro.SelectionStart = 0
            txtLivro.SelectionLength = Len(txtLivro.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_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMesAno.Enter

        Try

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

            If Me.txtMesAno.Text = "" Then
                Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Date.Now), Year(Date.Now)) & "/" & VB6.Format(Date.Now, "MM/YYYY")).ToOADate)
            Else
                Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Me.txtMesAno.Text), Year(Me.txtMesAno.Text)) & "/" & VB6.Format(Me.txtMesAno.Text, "MM/YYYY")).ToOADate)
            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_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMesAno.Leave

        Dim ldteAux As Date

        Try


            If Trim(Me.txtMesAno.Text) <> "" Then
                Me.txtMesAno.Text = FormataData(txtMesAno, 1)
                ldteAux = System.DateTime.FromOADate(CDate("01/" & Me.txtMesAno.Text).ToOADate - 1)
                ldteAux = System.DateTime.FromOADate(CDate("01/" & VB6.Format(ldteAux, "MM/YYYY")).ToOADate - 1)
                Me.dtpMesAnoConsumo.Value = CDate("01/" & VB6.Format(ldteAux, "MM/YYYY"))
                Monta_MesAno_Civil()

                If Me.txtMesAno.Text = "" Then
                    Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Date.Now), Year(Date.Now)) & "/" & VB6.Format(Date.Now, "MM/YYYY")).ToOADate)
                Else
                    Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Me.txtMesAno.Text), Year(Me.txtMesAno.Text)) & "/" & VB6.Format(Me.txtMesAno.Text, "MM/YYYY")).ToOADate)
                End If

            Else
                MessageBox.Show("Mês e Ano inválido!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.txtMesAno.Focus()
            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 txtParCatHoras_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtParCatHoras.Enter

        Try



            With Me.txtParCatHoras
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txtParCatHoras_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtParCatHoras.Leave

        Try


            With Me.txtParCatHoras
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#0")
                End If
            End With



        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 txtParCatMWhMedio_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtParCatMWhMedio.Enter

        Try


            With Me.txtParCatMWhMedio
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtParCatMWhMedio_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtParCatMWhMedio.Leave

        Try


            With Me.txtParCatMWhMedio
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,########0.00000000")
                End If
            End With



        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 txtReverso_p_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_p.Enter

        Try


            With Me.txtReverso_p
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtReverso_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_p.Leave

        Try


            With Me.txtReverso_p
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtReverso_fp_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_fp.Enter

        Try



            With Me.txtReverso_fp
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txtReverso_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_fp.Leave

        Try



            With Me.txtReverso_fp
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With


        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 txtReverso_Residuo_p_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_Residuo_p.Enter

        Try



            With Me.txtReverso_Residuo_p
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With


        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 txtReverso_Residuo_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_Residuo_p.Leave

        Try


            With Me.txtReverso_Residuo_p
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtReverso_Residuo_fp_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_Residuo_fp.Enter

        Try


            With Me.txtReverso_Residuo_fp
                .Text = CStr(CDbl(IIf(IsNumeric(.Text), .Text, 0)))
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With



        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 txtReverso_Residuo_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReverso_Residuo_fp.Leave

        Try


            With Me.txtReverso_Residuo_fp
                If Len(Trim(.Text)) <= 0 Then
                    .Text = "0"
                Else
                    .Text = VB6.Format(.Text, "#,##0.00000")
                End If
            End With



        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 txtZona_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Enter

        Try



            txtZona.SelectionStart = 0
            txtZona.SelectionLength = Len(txtZona.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 txtZona_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Leave

        Try


            If Len(txtZona.Text) >= 1 Then
                If IsNumeric(txtZona.Text) Then
                    txtZona.Text = VB6.Format(txtZona.Text, "000")
                Else
                    txtZona.Text = ""
                    'txtZona.SetFocus
                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 txtLivro_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Leave

        Try


            If Len(txtLivro.Text) >= 1 Then
                If IsNumeric(txtLivro.Text) Then
                    txtLivro.Text = VB6.Format(txtLivro.Text, "00")
                Else
                    txtLivro.Text = ""
                    'txtLivro.SetFocus
                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 cmdGravaLeitura_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGravaLeitura.Click

        Try

            LigDesBotoes(False)
            Grava_Leitura(False)
            LigDesBotoes(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 cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.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

    Private Sub cmdCCEEEnergiaComprada_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCCEEEnergiaComprada.Click

        Try


            If CDbl(IIf(IsNumeric(txtCCEEConsumoTotal.Text), txtCCEEConsumoTotal.Text, 0)) > 0 And CDbl(IIf(IsNumeric(Me.txtCCEEPrecoMedio.Text), Me.txtCCEEPrecoMedio.Text, 0)) > 0 Then
                Me.txtCCEEEnergiaComprada.Text = VB6.Format(Arredondar(CDbl(Me.txtCCEEConsumoTotal.Text) * CDbl(Me.txtCCEEPrecoMedio.Text), 2), "#,##0.00")
            Else
                Me.txtCCEEEnergiaComprada.Text = CStr(0)
            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 cmdImpFaturas_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImpFaturas.Click

        Dim ifrmimpFaturas As New frmImpFaturas
        Dim classAPIGerarFaturas As New classAPIGerarFaturas

        Try



            If idblUnidId > 0 Then

                idblNumNf = BuscaNumeroFaturaTransicao(idblUnidId)

                If idblNumNf > 0 Then
                    LigDesBotoes(False)
                    classAPIGerarFaturas.frmImpFaturas = ifrmimpFaturas
                    classAPIGerarFaturas.GeraFaturaGrupoA("FORM", 0, Me.txtMesAno.Text, idblNumNf, 0, "nftransicao", 0,,,, Me.Name)
                    LigDesBotoes(True)
                Else
                    MessageBox.Show("Não existe fatura em transição desta unidade consumidora.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                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 cmdCCEEBuscaDados_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCCEEBuscaDados.Click

        Dim ldblAux As Double
        Dim lstrIte As String
        Dim ldteAux As Date
        Dim lstrSql As String

        Dim dt As DataTable
        Dim dt_1 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            Me.txtCCEEAliquotaCofins.Text = ""
            Me.txtCCEEAliquotaPis.Text = ""
            Me.txtCCEEAliquotaIcms.Text = ""
            Me.txtCCEEBaseIcms.Text = ""
            Me.txtCCEEBaseIntermediaria.Text = ""
            Me.txtCCEEBasePisCof.Text = ""
            Me.txtCCEEConsumoTotal.Text = ""
            Me.txtCCEEEnergiaComprada.Text = ""
            Me.txtCCEEIcmsIntermediario.Text = ""
            Me.txtCCEEPrecoMedio.Text = ""
            Me.txtCCEEValorCofins.Text = ""
            Me.txtCCEEValorIcms.Text = ""
            Me.txtCCEEValorPis.Text = ""

            ldteAux = System.DateTime.FromOADate(CDate(UltimoDiaMes((Me.dtpMesAnoConsumo.Value.Month), (Me.dtpMesAnoConsumo.Value.Year)) & "/" & VB6.Format(Me.dtpMesAnoConsumo.Value, "MM/YYYY")).ToOADate + 1)

            lstrSql = ""
            lstrSql = lstrSql & "SELECT * "
            lstrSql = lstrSql & "  FROM `precomediolivre` "
            lstrSql = lstrSql & " WHERE `referencia` = " & CInt(VB6.Format(Me.dtpMesAnoConsumo.Value, "YYYYMM")) & " "
            lstrSql = lstrSql & "   AND `unid_id` = " & idblUnidId & " "
            lstrSql = lstrSql & "   AND `cons_id` = " & idblConsId & " "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    ldblAux = CDbl(IIf(IsDBNull(row("preco_medio_mwh")), 0, row("preco_medio_mwh")))
                    Me.txtCCEEPrecoMedio.Text = VB6.Format(ldblAux / 1000, "#,#####0.00000")

                Next

            End If

            If ldblAux > 0 Then

                lstrSql = ""
                lstrSql = lstrSql & "SELECT * "
                lstrSql = lstrSql & "  FROM `nf` "
                lstrSql = lstrSql & " WHERE `nf`.`mesano` = '" & VB6.Format(ldteAux, "MM/YYYY") & "' "
                lstrSql = lstrSql & "   AND `nf`.`mesano_ref` = " & CInt(VB6.Format(ldteAux, "YYYYMM")) & " "
                lstrSql = lstrSql & "   AND `nf`.`zona` = '" & Me.txtZona.Text & "' "
                lstrSql = lstrSql & "   AND `nf`.`livro` = '" & Me.txtLivro.Text & "' "
                lstrSql = lstrSql & "   AND `nf`.`conta` = '" & Me.txtConta.Text & "' "
                lstrSql = lstrSql & "   AND `nf`.`unid_id` = " & idblUnidId & " "
                lstrSql = lstrSql & "   AND `nf`.`cons_id` = " & idblConsId & " "
                lstrSql = lstrSql & "   AND `nf`.`grupo` = 'A' "
                lstrSql = lstrSql & "   AND `nf`.`fatura_complementar` = 0 "
                lstrSql = lstrSql & "UNION "
                lstrSql = lstrSql & "SELECT * "
                lstrSql = lstrSql & "  FROM `nftransicao` "
                lstrSql = lstrSql & " WHERE `nftransicao`.`mesano` = '" & VB6.Format(ldteAux, "MM/yyyy") & "' "
                lstrSql = lstrSql & "   AND `nftransicao`.`mesano_ref` = " & CInt(VB6.Format(ldteAux, "yyyyMM")) & " "
                lstrSql = lstrSql & "   AND `nftransicao`.`zona` = '" & Me.txtZona.Text & "' "
                lstrSql = lstrSql & "   AND `nftransicao`.`livro` = '" & Me.txtLivro.Text & "' "
                lstrSql = lstrSql & "   AND `nftransicao`.`conta` = '" & Me.txtConta.Text & "' "
                lstrSql = lstrSql & "   AND `nftransicao`.`unid_id` = " & idblUnidId & " "
                lstrSql = lstrSql & "   AND `nftransicao`.`cons_id` = " & idblConsId & " "
                lstrSql = lstrSql & "   AND `nftransicao`.`grupo` = 'A' "
                lstrSql = lstrSql & "   AND `nftransicao`.`fatura_complementar` = 0 "

                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                If dt.Rows.Count <> 0 Then

                    For Each row As DataRow In dt.Rows

                        lstrIte = Trim(IIf(IsDBNull(row("itensserv")), "", row("itensserv")))
                        Me.txtCCEEAliquotaPis.Text = CStr(0) 'Strings.Format(BuscaVlrItem(lstrIte, "40PIS00001"), "#,#####0.00000")
                        Me.txtCCEEAliquotaCofins.Text = CStr(0) 'Strings.Format(BuscaVlrItem(lstrIte, "40COF00001"), "#,#####0.00000")
                        Me.txtCCEEAliquotaIcms.Text = VB6.Format(BuscaVlrItem(lstrIte, "0302030002"), "#,#####0.00000")

                        If iblnParCativo Then
                            Me.txtCCEEConsumoTotal.Text = VB6.Format(BuscaVlrItem(lstrIte, "0302010060") + BuscaVlrItem(lstrIte, "0302010061"), "#,##0.00")
                            If Me.txtCCEEConsumoTotal.Text = "0,00" Then
                                Me.txtCCEEConsumoTotal.Text = VB6.Format(BuscaVlrItem(lstrIte, "0302010010") + BuscaVlrItem(lstrIte, "0302010011"), "#,##0.00")
                            End If
                        Else
                            Me.txtCCEEConsumoTotal.Text = VB6.Format(BuscaVlrItem(lstrIte, "0302010010") + BuscaVlrItem(lstrIte, "0302010011"), "#,##0.00")
                        End If

                    Next

                Else


                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT * "
                    lstrSql = lstrSql & "  FROM `nf` "
                    lstrSql = lstrSql & " WHERE `nf`.`mesano` = '" & VB6.Format(ldteAux, "MM/YYYY") & "' "
                    lstrSql = lstrSql & "   AND `nf`.`mesano_ref` = " & CInt(VB6.Format(ldteAux, "YYYYMM")) & " "
                    lstrSql = lstrSql & "   AND `nf`.`zona` = '" & Me.txtZona.Text & "' "
                    lstrSql = lstrSql & "   AND `nf`.`livro` = '" & Me.txtLivro.Text & "' "
                    lstrSql = lstrSql & "   AND `nf`.`conta` = '" & Me.txtConta.Text & "' "
                    lstrSql = lstrSql & "   AND `nf`.`unid_id` = " & idblUnidId & " "
                    lstrSql = lstrSql & "   AND `nf`.`grupo` = 'A' "
                    lstrSql = lstrSql & "   AND `nf`.`fatura_complementar` = 0 "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            lstrIte = Trim(IIf(IsDBNull(row("itensserv")), "", row("itensserv")))
                            'Arlindo 02/03/2021
                            'Me.txtCCEEAliquotaPis.Text = Strings.Format(BuscaVlrItem(lstrIte, "40PIS00001"), "#,#####0.00000")
                            'Me.txtCCEEAliquotaCofins.Text = Strings.Format(BuscaVlrItem(lstrIte, "40COF00001"), "#,#####0.00000")
                            Me.txtCCEEAliquotaPis.Text = CStr(0)
                            Me.txtCCEEAliquotaCofins.Text = CStr(0)

                            Me.txtCCEEAliquotaIcms.Text = VB6.Format(BuscaVlrItem(lstrIte, "0302030002"), "#,#####0.00000")
                            Me.txtCCEEConsumoTotal.Text = VB6.Format(BuscaVlrItem(lstrIte, "0302010010") + BuscaVlrItem(lstrIte, "0302010011"), "#,##0.00")


                        Next

                    Else
                        Me.txtCCEEAliquotaIcms.Text = CStr(0)
                        Me.txtCCEEAliquotaPis.Text = CStr(0)
                        Me.txtCCEEConsumoTotal.Text = CStr(0)
                        Me.txtCCEEAliquotaCofins.Text = CStr(0)
                    End If


                End If

                Me.txtCCEEEnergiaComprada.Text = VB6.Format(Arredondar(CDbl(Me.txtCCEEConsumoTotal.Text) * CDbl(Me.txtCCEEPrecoMedio.Text), 2), "#,##0.00")

            Else
                MessageBox.Show("Não existe preço médio para este período", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            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 cmdCobDev_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCobDev.Click


        Try


            frmCadCobDevGrupoA.SetaParametros(Me, Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, CInt(idblUnidId), CInt(idblConsId), "A", Me.txtTA.Text, Me.txtNome.Text, iintBanderiaVigente, idteBandeira)
            frmCadCobDevGrupoA.Show()

        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 cmdImprimir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImprimir.Click

        Try



            LigDesBotoes(False)

            frmRelLeitGrupoA.Show()

            LigDesBotoes(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 cmdPercLivres_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdPercLivres.Click

        Try


            frmCadPercentualLivres.SetaParametros(Me, Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, CInt(idblUnidId), "A")
            frmCadPercentualLivres.Show()


        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 cmdPrecoMedio_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdPrecoMedio.Click

        Try

            frmCadPrecoMedioLivre.SetaParametros(Me, Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, CInt(idblUnidId), "A")
            frmCadPrecoMedioLivre.Show()

        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 cmdCalcular_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCalcular.Click

        Dim ldte_Base As Date


        Try

            LigDesBotoes(False)
            CarregaGridFatura()

            If Not IsDate(Me.txtDt_Leit_Anterior.Text) Or Not IsDate(Me.txtDt_Leit_Atual.Text) Then
                MessageBox.Show("É necessário informar as datas de leitura!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.txtDt_Leit_Atual.Focus()
            ElseIf Trim(Me.txt_Msg_Periodo_Teste.Text) <> "" Then
                MessageBox.Show("Este consumidor possui problema nos dados de demanda do período de teste!" & vbCrLf & "Revise o cadastro da unidade consumidora!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else

                ldte_Base = DateValue(UltimoDiaMes(CShort(Microsoft.VisualBasic.Right(CStr(ilngAnoMes_Fat), 2)), CShort(Microsoft.VisualBasic.Left(CStr(ilngAnoMes_Fat), 4))) & "/" & Microsoft.VisualBasic.Right(CStr(ilngAnoMes_Fat), 2) & "/" & Microsoft.VisualBasic.Left(CStr(ilngAnoMes_Fat), 4))

                If IsDate(Me.txtDt_Faturamento.Text) Then
                    If istrFlgCalcPisCof = "N" Then
                        idblAliqPIS = 0
                        idblAliqCofins = 0
                        If istrFlgCalcPisCofNAss = "S" Then
                            If ilngMatricula = 0 Then
                                idblAliqPIS = Aliquota_PIS(ldte_Base) 'Conversion.CDate(Me.txtDt_Faturamento.Text))
                                idblAliqCofins = Aliquota_COFINS(ldte_Base) 'Conversion.CDate(Me.txtDt_Faturamento.Text))
                            End If
                        End If
                    Else
                        idblAliqPIS = Aliquota_PIS(ldte_Base) 'Conversion.CDate(Me.txtDt_Faturamento.Text))
                        idblAliqCofins = Aliquota_COFINS(ldte_Base) 'Conversion.CDate(Me.txtDt_Faturamento.Text))
                    End If
                End If

                If iintTipoTarifa = 0 Then 'Convencional
                    Calc_Convencional()
                ElseIf iintTipoTarifa = 3 Then  'AutoProdutor
                    '
                Else 'Horo Sazonal
                    Calc_HoroSazonal()
                End If

            End If

            FlexCores(Me.grid_fatura, &H80000005, &HFFC0C0) '   &H8000000F

            LigDesBotoes(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 frmFatGrupoA_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.Escape Then
                lClose()
            ElseIf 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 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 Monta_MesAno_Civil()

        Dim ldteAux As Date

        Try
            'REN 863/2019 - mês civil

            If CLng(Strings.Right(Me.txtMesAno.Text, 4) & Strings.Left(Me.txtMesAno.Text, 2)) > CLng(IIf(IsNumeric(gstrREN_863_2019_12_GRUPO_A), gstrREN_863_2019_12_GRUPO_A, 999999)) Then
                ldteAux = CDate("01/" & Me.txtMesAno.Text)
                ilngAnoMes_Fat = CLng(Strings.Format(DateAndTime.DateAdd(DateInterval.Month, -1, ldteAux).Date, "yyyyMM"))
            Else
                ilngAnoMes_Fat = CLng(Strings.Right(Me.txtMesAno.Text, 4) & Strings.Left(Me.txtMesAno.Text, 2))
            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub LigDesBotoes(ByVal ablnModo As Boolean)

        Try


            Me.cmdCalcular.Enabled = ablnModo
            Me.cmdFechar.Enabled = ablnModo
            Me.cmdGravaLeitura.Enabled = ablnModo
            Me.cmdGravarFatura.Enabled = ablnModo
            Me.cmdImpFaturas.Enabled = ablnModo
            Me.cmdImprimir.Enabled = ablnModo
            Me.cmdCCEEBuscaDados.Enabled = ablnModo
            Me.cmdCCEEEnergiaComprada.Enabled = ablnModo

            If InStr(1, Me.txtTA.Text, "AL") Then
                If idblUnidId > 0 Then
                    Me.cmdPercLivres.Enabled = ablnModo
                    Me.cmdPrecoMedio.Enabled = ablnModo
                Else
                    Me.cmdPercLivres.Enabled = False
                    Me.cmdPrecoMedio.Enabled = False
                End If
            Else
                Me.cmdPercLivres.Enabled = False
                Me.cmdPrecoMedio.Enabled = False
            End If

            System.Windows.Forms.Application.DoEvents()

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CarregaGridUnidade()

        Try

            With mhgDados
                .Clear()
                .Rows = 2
                .set_ColWidth(0, 1200)
                .set_ColWidth(1, 6400)
                .set_ColWidth(2, 460)
                .set_ColWidth(3, 460)
                .set_ColWidth(4, 460)
                .set_ColWidth(5, 460)
                '
                .set_ColAlignment(0, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
                .set_ColAlignment(1, MSFlexGridLib.AlignmentSettings.flexAlignLeftCenter)
                .set_ColAlignment(2, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
                .set_ColAlignment(3, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
                .set_ColAlignment(4, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
                .set_ColAlignment(5, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
                '
                .set_TextMatrix(0, 0, "Identificação")
                .set_TextMatrix(0, 1, "Nome")
                .set_TextMatrix(0, 2, "Leit.")
                .set_TextMatrix(0, 3, "Fat.")
                .set_TextMatrix(0, 4, "Tar.")
                .set_TextMatrix(0, 5, "Sit.")
                .FixedRows = 1

            End With
            '
            CarregaGridFatura()
            System.Windows.Forms.Application.DoEvents()

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CarregaGridFatura()

        Try


            Me.lblTotal.Text = ""
            Me.lblTotalLiq.Text = ""

            With grid_fatura
                .Clear()
                .Rows = 2
                .set_ColWidth(0, 1200)
                .set_ColWidth(1, 5000)
                .set_ColWidth(2, 1480)
                .set_ColWidth(3, 1480)
                .set_ColWidth(4, 0)
                '
                .set_TextMatrix(0, 0, "Código")
                .set_TextMatrix(0, 1, "Descrição")
                .set_TextMatrix(0, 2, "Quantidade")
                .set_TextMatrix(0, 3, "Valor")
                .set_TextMatrix(0, 4, "Composição")
            End With

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub PreencherGridUnidade()

        Dim llngUnidId As Integer
        Dim llngConsId As Integer
        Dim lstrZona As String
        Dim lstrLivro As String
        Dim lstrConta As String
        Dim lstrNome As String
        Dim lstrGrTar As String
        Dim lstrSituacao As String
        Dim lstrLeitura As String
        Dim lstrFatura As String
        Dim lstrSql As String

        Dim dt As DataTable
        Dim dt_1 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            CarregaGridUnidade()

            Me.mhgDados.Redraw = False

            lstrSql = ""
            lstrSql = lstrSql & "SELECT *"
            lstrSql = lstrSql & "  FROM `uc_faturamento` "
            If Me.opbLigados.Checked Then
                lstrSql = lstrSql & " WHERE `situacao` = 'L'  AND `grupo` = 'A' "
            ElseIf Me.opbDesligados.Checked Then
                lstrSql = lstrSql & " WHERE `situacao` <> 'L' AND `grupo` = 'A' "
            End If
            If Me.optZLC.Checked = True Then
                lstrSql = lstrSql & "ORDER BY `zona` ASC, `livro` ASC, `conta` ASC, `nome` ASC, `ta` ASC "
            ElseIf optNome.Checked = True Then
                lstrSql = lstrSql & "ORDER BY `nome` ASC, `zona` ASC, `livro` ASC, `conta` ASC, `ta` ASC "
            ElseIf optTarifa.Checked Then
                lstrSql = lstrSql & "ORDER BY `ta` ASC, `zona` ASC, `livro` ASC, `conta` ASC, `nome` ASC"
            End If

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    llngUnidId = CInt(IIf(IsDBNull(row("unid_id")), 0, row("unid_id")))
                    llngConsId = CInt(IIf(IsDBNull(row("cons_id")), 0, row("cons_id")))
                    lstrZona = Trim(IIf(IsDBNull(row("zona")), "", row("zona")))
                    lstrLivro = Trim(IIf(IsDBNull(row("livro")), "", row("livro")))
                    lstrConta = Trim(IIf(IsDBNull(row("conta")), "", row("conta")))
                    lstrNome = Trim(IIf(IsDBNull(row("nome")), "", row("nome")))
                    lstrGrTar = Trim(IIf(IsDBNull(row("ta")), "01A4", row("ta")))
                    lstrSituacao = UCase(Trim(IIf(IsDBNull(row("situacao")), "L", row("situacao"))))
                    lstrLeitura = "NÃO"

                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT * "
                    lstrSql = lstrSql & "  FROM `leitura` "
                    lstrSql = lstrSql & " WHERE `id_unid` = " & llngUnidId & " "
                    lstrSql = lstrSql & "   AND `id_consumidor` = " & llngConsId & " "
                    lstrSql = lstrSql & "   AND `mesano` = '" & Me.txtMesAno.Text & "' "
                    lstrSql = lstrSql & " LIMIT 0, 1"

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt_1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                    lstrLeitura = IIf(dt_1.Rows.Count > 0, "SIM", "NÃO")


                    lstrFatura = "NÃO"
                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT * "
                    lstrSql = lstrSql & "  FROM `nftransicao` "
                    lstrSql = lstrSql & " WHERE `unid_id` = " & llngUnidId & " "
                    lstrSql = lstrSql & "   AND `cons_id` = " & llngConsId & " "
                    lstrSql = lstrSql & "   AND `mesano` = '" & Me.txtMesAno.Text & "' "
                    lstrSql = lstrSql & "   AND `fatura_complementar`=0 "
                    lstrSql = lstrSql & " LIMIT 0, 1"

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt_1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                    lstrFatura = IIf(dt_1.Rows.Count > 0, "SIM", "NÃO")

                    With Me.mhgDados

                        .set_TextMatrix(.Rows - 1, 0, lstrZona & "." & lstrLivro & "." & lstrConta)
                        .set_TextMatrix(.Rows - 1, 1, lstrNome)
                        .set_TextMatrix(.Rows - 1, 2, lstrLeitura)
                        .set_TextMatrix(.Rows - 1, 3, lstrFatura)
                        .set_TextMatrix(.Rows - 1, 4, Mid(lstrGrTar, 3, 2))
                        .set_TextMatrix(.Rows - 1, 5, lstrSituacao)

                        .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillRepeat

                        If lstrSituacao <> "L" Then
                            .Row = .Rows - 1
                            .Col = 0
                            .ColSel = .Cols - 1
                            .CellForeColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                        Else
                            .Row = .Rows - 1
                            .Col = 0
                            .ColSel = .Cols - 1
                            .CellForeColor = System.Drawing.ColorTranslator.FromOle(&H80000008)
                        End If

                        .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillSingle
                        .Rows = .Rows + 1
                    End With


                Next

            End If

            Me.mhgDados.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightNever
            Me.mhgDados.Redraw = True

            System.Windows.Forms.Application.DoEvents()


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function IncideICMS(ByVal astrCodigo As String) As Boolean

        Dim lstrAux As String
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            lstrAux = "N"

            lstrSql = "SELECT `flgcasc` FROM `codigos` WHERE `num` = '" & astrCodigo & "' LIMIT 0, 1"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    lstrAux = IIf(IsDBNull(row("flgcasc")), "N", row("flgcasc"))
                Next

            End If

            IncideICMS = (lstrAux = "S")

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function IncidePisCof(ByVal astrCodigo As String) As Boolean

        Dim lstrAux As String
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            lstrAux = "N"

            lstrSql = "SELECT `flgPisCof` FROM `codigos` WHERE `num` = '" & astrCodigo & "'"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    lstrAux = IIf(IsDBNull(row("flgPisCof")), "N", row("flgPisCof"))
                Next

            End If

            IncidePisCof = lstrAux = "S"


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub CobrarSobreTaxaEflul(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByRef vlrTotal As Double, ByRef row_grid As Short, ByRef aliq As Double, ByRef coef As Double, ByRef vlrIsentoIcms As Double)
        Dim ldblValor As Double
        Dim ldblVlrAux As Double
        Dim lstrRefere As String
        Dim lstrCodigo As String
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            lstrSql = " "
            lstrSql = "SELECT * "
            lstrSql = lstrSql & "  FROM `sobretaxa` "
            lstrSql = lstrSql & " WHERE `zona` = '" & astrZona & "' "
            lstrSql = lstrSql & "   AND `livro` = '" & astrLivro & "' "
            lstrSql = lstrSql & "   AND `conta` = '" & astrConta & "' "
            lstrSql = lstrSql & "   AND `cons_id` = " & alngConsId & " "
            lstrSql = lstrSql & "   AND `unid_id` = " & alngUnidId & " "
            lstrSql = lstrSql & "   AND ((`flag` = '' OR `flag` IS NULL) OR (`flag` = 'P' AND `mesano` = '" & Me.txtMesAno.Text & "')) "


            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    ldblValor = CDbl(IIf(IsDBNull(row("valor")), 0, row("valor")))
                    lstrCodigo = IIf(IsDBNull(row("codigo")), 0, row("codigo"))
                    lstrRefere = IIf(IsDBNull(row("referencia")), "", row("referencia"))

                    If ldblValor > 0 Then

                        row_grid = 1 + row_grid

                        With Me.grid_fatura
                            .Rows = row_grid + 1
                            .Row = row_grid
                            .Col = 0
                            .Text = lstrCodigo
                            .Col = 1
                            .Text = Trim(codTodescri(lstrCodigo))
                            .Col = 2
                            .Text = ""
                            .Col = 3
                            .Text = VB6.Format(ldblValor, "#,##0.00")
                            .Col = 4
                            .Text = lstrRefere
                        End With

                        If Mid(lstrCodigo, 1, 4) = "9070" Then
                            vlrTotal = vlrTotal - ldblValor
                        Else
                            vlrIsentoIcms = vlrIsentoIcms + CDbl(Replace(CStr(ldblValor), ".", ","))
                            vlrTotal = vlrTotal + ldblValor
                        End If

                    End If

                    '----- Seta a parcela como paga ---------------------------------------------

                    lstrSql = " "
                    lstrSql = "UPDATE `sobretaxa` SET "
                    lstrSql = lstrSql & "         `flag`   = 'P'"
                    lstrSql = lstrSql & "       , `mesano` = '" & Me.txtMesAno.Text & "'"
                    lstrSql = lstrSql & "       , `cons_id` = " & alngConsId & ""
                    lstrSql = lstrSql & "       , `unid_id` = " & alngUnidId
                    lstrSql = lstrSql & " WHERE `zona`   = '" & astrZona & "' "
                    lstrSql = lstrSql & "   AND `livro`  = '" & astrLivro & "' "
                    lstrSql = lstrSql & "   AND `conta`  = '" & astrConta & "' "
                    lstrSql = lstrSql & "   AND ((`flag` = '' OR `flag` IS NULL) OR (`flag`='P' AND `mesano` = '" & Me.txtMesAno.Text & "')) "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

                    '----------------------------------------------------------------------------

                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub GetDemandasLivre(ByVal alngReferencia As Integer, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByRef alngUnidId As Integer, ByRef pdblDemanda As Double, ByRef pdblConsumo As Double)

        Dim ldblTarP As Double
        Dim ldblTarFp As Double
        Dim ldblConsumo As Double
        Dim lstrItens As String
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            lstrSql = "SELECT * "
            lstrSql = lstrSql & "  FROM `nf` "
            lstrSql = lstrSql & " WHERE `mesano_ref` = " & alngReferencia
            lstrSql = lstrSql & "   AND `zona` = '" & astrZona & "' "
            lstrSql = lstrSql & "   AND `livro` = '" & astrLivro & "' "
            lstrSql = lstrSql & "   AND `conta` = '" & astrConta & "' "
            lstrSql = lstrSql & "   AND `unid_id` = '" & alngUnidId & "' "
            lstrSql = lstrSql & "   AND `grupo` = 'A' "
            lstrSql = lstrSql & "   AND `ta` = '01AL00' "
            lstrSql = lstrSql & "   AND `fatura_complementar` = 0"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrItens = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))

                    'Clipboard.Clear
                    'Clipboard.SetText lstrItens
                    ldblTarP = BuscaValorItem(lstrItens, "01AL011101")
                    If ldblTarP = 0 Then ldblTarP = BuscaValorItem(lstrItens, "01AL011105")
                    ldblTarFp = BuscaValorItem(lstrItens, "01AL011102")
                    If ldblTarFp = 0 Then ldblTarFp = BuscaValorItem(lstrItens, "01AL011106")
                    ldblConsumo = BuscaValorItem(lstrItens, "0302010010")
                    pdblDemanda = BuscaValorItem(lstrItens, "0302020023")
                    pdblConsumo = Truncate(ldblConsumo * (ldblTarP - ldblTarFp), 2)


                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function CobrarDescontoProvisorio(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByRef vlrTotal As Double, ByRef row_grid As Short, ByVal aliq As Double, ByVal acoefTribIcms As Double, ByVal adblDemP As Double, ByRef adblDemFP As Double, ByVal adblDemLidaP As Double, ByRef adblDemLidaFP As Double, ByRef abaseICMSisenta As Double, ByVal adblConsumoP As Double, ByVal adblConsumoFP As Double, ByVal adblDemFP_Dif As Double, ByVal adblConsumoP_Q As Double, ByVal ldblDemandaContratadaForaPonta As Double, ByVal idblTarDemanda_fp As Double) As Double

        Dim ldblPerc_Atu As Double
        Dim ldblPerc_Ant As Double
        Dim ldblDem_P As Double
        Dim ldblDem_FP As Double
        Dim ldblCon_P As Double
        Dim ldblCon_FP As Double
        Dim ldblValor As Double
        Dim ldblValor1 As Double
        Dim ldblValor2 As Double
        Dim ldblVlrAux As Double
        Dim llngRefere As Integer
        Dim lstrCodigo As String
        Dim lstrTextoRef As String
        Dim lstrSql As String
        Dim ldblDem_FP_ant As Double
        Dim ldblCon_P_ant As Double

        Dim dt As DataTable
        Dim dt_1 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try


            lstrSql = ""
            lstrSql = lstrSql & "SELECT * "
            lstrSql = lstrSql & "  FROM `descontoprovisorio` "
            lstrSql = lstrSql & " WHERE `zona` = '" & astrZona & "' "
            lstrSql = lstrSql & "   AND `livro` = '" & astrLivro & "' "
            lstrSql = lstrSql & "   AND `conta` = '" & astrConta & "' "
            lstrSql = lstrSql & "   AND `mesano` = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
            lstrSql = lstrSql & " ORDER BY `referencia` DESC "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrCodigo = IIf(IsDBNull(row("codigo")), 0, row("codigo"))
                    llngRefere = CInt(IIf(IsDBNull(row("referencia")), 0, row("referencia")))
                    ldblPerc_Atu = CDbl(IIf(IsDBNull(row("valor")), 0, row("valor")))
                    lstrTextoRef = IIf(IsDBNull(row("texto_ref")), "", row("texto_ref"))
                    ldblValor = 0

                    If lstrCodigo = "0302010051" Then

                        If llngRefere <> CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) Then
                            adblDemP = 0
                            GetDemandasLivre(llngRefere, astrZona, astrLivro, astrConta, alngUnidId, adblDemFP, adblConsumoP)
                        End If

                        lstrSql = ""
                        lstrSql = lstrSql & "UPDATE `descontoprovisorio` SET "
                        lstrSql = lstrSql & "       `demanda_p` = " & Replace(CStr(adblDemP), ",", ".")
                        lstrSql = lstrSql & "     , `demanda_fp` = " & Replace(CStr(adblDemFP + adblDemFP_Dif), ",", ".")
                        lstrSql = lstrSql & " WHERE `zona`       = '" & astrZona & "' "
                        lstrSql = lstrSql & "   AND `livro`      = '" & astrLivro & "' "
                        lstrSql = lstrSql & "   AND `conta`      = '" & astrConta & "' "
                        lstrSql = lstrSql & "   AND `mesano`     = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
                        lstrSql = lstrSql & "   AND `referencia` = " & llngRefere & " "
                        lstrSql = lstrSql & "   AND `codigo`     = '0302010051' "

                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                        'If adblDemLidaP > 0 Then
                        '  ldblValor = Truncate((adblDemLidaP + adblDemLidaFP) * ((ldblPerc_Atu / 100)), 2)
                        'Else
                        ldblValor = Truncate((adblDemP + adblDemFP + adblDemFP_Dif) * ((ldblPerc_Atu / 100)), 2)
                        'End If

                        If ldblValor > 0 Then

                            row_grid = 1 + row_grid
                            grid_fatura.Rows = row_grid + 1
                            grid_fatura.Row = row_grid
                            grid_fatura.Col = 0
                            grid_fatura.Text = "0302020051"
                            grid_fatura.Col = 1
                            'grid_fatura.Text = Trim(codTodescri("0302020051")) & " ( " & IIf(lstrTextoRef = "", Arredondar(adblDemP + adblDemFP, 2) & " x " & Truncate(ldblPerc_Atu, 6) & "% - " & (Right(llngRefere, 2) & "/" & Left(llngRefere, 4)), lstrTextoRef) & ")"
                            grid_fatura.Text = Trim(codTodescri("0302020051")) & " ( " & IIf(lstrTextoRef = "", Arredondar(adblDemP + adblDemFP + adblDemFP_Dif, 2) & " x " & Truncate(ldblPerc_Atu, 6) & "% - " & (Microsoft.VisualBasic.Right(CStr(ilngAnoMes_Fat), 2) & "/" & Microsoft.VisualBasic.Left(CStr(ilngAnoMes_Fat), 4)), lstrTextoRef) & ")"
                            grid_fatura.Col = 2
                            grid_fatura.Text = ""
                            grid_fatura.Col = 3
                            grid_fatura.Text = VB6.Format(ldblValor, "#,##0.00")
                            grid_fatura.Col = 4
                            'grid_fatura.Text = " ( " & IIf(lstrTextoRef = "", Truncate(adblDemP + adblDemFP, 5) & " x " & ldblPerc_Atu & "% - " & (Right(llngRefere, 2) & "/" & Left(llngRefere, 4)), lstrTextoRef) & ")"
                            grid_fatura.Text = " ( " & IIf(lstrTextoRef = "", Truncate(adblDemP + adblDemFP, 5) & " x " & ldblPerc_Atu & "% - " & (Microsoft.VisualBasic.Right(CStr(ilngAnoMes_Fat), 2) & "/" & Microsoft.VisualBasic.Left(CStr(ilngAnoMes_Fat), 4)), lstrTextoRef) & ")"
                            vlrTotal = vlrTotal - ldblValor

                            'Alterado pela portaria SEF 344/2019
                            If CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) < glngPortaria_Sef_344_2019 Then

                                If (adblDemLidaP + adblDemLidaFP) > 0 Then
                                    ldblValor = Truncate((adblDemLidaP + adblDemLidaFP) * ((ldblPerc_Atu / 100)), 2)
                                End If

                                ldblVlrAux = Truncate(ldblValor / acoefTribIcms, 2)

                                If (adblDemLidaP + adblDemLidaFP) > 0 Then
                                    'Faturado
                                    ldblValor1 = Truncate((adblDemP + adblDemFP) * ((ldblPerc_Atu / 100)), 2)
                                    ldblValor1 = Truncate(ldblValor1 / acoefTribIcms, 2)
                                    ldblValor1 = Calc_ICMS(ldblValor1, gstrEmpresa_UF, aliq, 5)
                                    ldblValor1 = Arredondar(ldblValor1 - Calc_ICMS(ldblVlrAux, gstrEmpresa_UF, aliq, 5), 2)
                                    'Diferença faturado e lido
                                    abaseICMSisenta = abaseICMSisenta + ldblValor1
                                    Item_Fatura = Trim(Item_Fatura & "0302030021?" & Replace(CStr(ldblValor1), ",", ".") & ";")
                                End If

                                ldblVlrAux = Calc_ICMS(ldblVlrAux, gstrEmpresa_UF, aliq, 5) * -1
                                BaseICMS = Arredondar(BaseICMS + ldblVlrAux, 2)

                            End If

                        End If

                    End If

                    If lstrCodigo = "0302010055" Then

                        If llngRefere <> CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) Then
                            adblDemP = 0
                            GetDemandasLivre(llngRefere, astrZona, astrLivro, astrConta, alngUnidId, adblDemFP, adblConsumoP)
                        End If

                        lstrSql = ""
                        lstrSql = lstrSql & "UPDATE `descontoprovisorio` "
                        lstrSql = lstrSql & "   SET consumo_p = " & Replace(CStr(adblConsumoP), ",", ".") & ", "
                        lstrSql = lstrSql & "       consumo_fp = " & Replace(CStr(adblConsumoFP), ",", ".") & " "
                        lstrSql = lstrSql & " WHERE zona       = '" & astrZona & "' "
                        lstrSql = lstrSql & "   AND livro      = '" & astrLivro & "' "
                        lstrSql = lstrSql & "   AND conta      = '" & astrConta & "' "
                        lstrSql = lstrSql & "   AND mesano     = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
                        lstrSql = lstrSql & "   AND referencia = " & llngRefere & " "
                        lstrSql = lstrSql & "   AND codigo     = '0302010055' "

                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                        'ldblValor = Truncate((adblConsumoP + adblConsumoFP) * ((ldblPerc_Atu / 100)), 2)
                        ldblValor = Truncate((adblConsumoP_Q * (idblTarConsumo_fp - idblTarConsumo_p)) * ((ldblPerc_Atu / 100)), 2)
                        If ldblValor < 0 Then ldblValor *= -1

                        If ldblValor > 0 Then

                            row_grid = 1 + row_grid
                            grid_fatura.Rows = row_grid + 1
                            grid_fatura.Row = row_grid
                            grid_fatura.Col = 0
                            grid_fatura.Text = "0302020055"
                            grid_fatura.Col = 1

                            'grid_fatura.Text = Trim(codTodescri("0302020055")) & " ( " & IIf(lstrTextoRef = "", Arredondar(adblConsumoP + adblConsumoFP, 2) & " x " & Truncate(ldblPerc_Atu, 6) & "% - " & (Right(llngRefere, 2) & "/" & Left(llngRefere, 4)), lstrTextoRef) & ")"
                            grid_fatura.Text = Trim(codTodescri("0302020055")) & " ( " & IIf(lstrTextoRef = "", Arredondar(adblConsumoP_Q, 2) & " x " & Truncate(ldblPerc_Atu, 6) & "% - " & (Microsoft.VisualBasic.Right(CStr(ilngAnoMes_Fat), 2) & "/" & Microsoft.VisualBasic.Left(CStr(ilngAnoMes_Fat), 4)), lstrTextoRef) & ")"
                            grid_fatura.Col = 2
                            grid_fatura.Text = ""
                            grid_fatura.Col = 3
                            grid_fatura.Text = VB6.Format(ldblValor, "#,##0.00")
                            grid_fatura.Col = 4
                            'grid_fatura.Text = " ( " & IIf(lstrTextoRef = "", Truncate(adblConsumoP + adblConsumoFP, 5) & " x " & ldblPerc_Atu & "% - " & (Right(llngRefere, 2) & "/" & Left(llngRefere, 4)), lstrTextoRef) & ")"
                            grid_fatura.Text = " ( " & IIf(lstrTextoRef = "", Truncate(adblConsumoP_Q, 5) & " x " & ldblPerc_Atu & "% - " & (Microsoft.VisualBasic.Right(CStr(ilngAnoMes_Fat), 2) & "/" & Microsoft.VisualBasic.Left(CStr(ilngAnoMes_Fat), 4)), lstrTextoRef) & ")"
                            vlrTotal = vlrTotal - ldblValor
                            'Alterado pela portaria SEF 344/2019

                            If CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) < glngPortaria_Sef_344_2019 Then
                                ldblVlrAux = Truncate(ldblValor / acoefTribIcms, 2)
                                ldblVlrAux = Calc_ICMS(ldblVlrAux, gstrEmpresa_UF, aliq, 5) * -1
                                BaseICMS = Arredondar(BaseICMS + ldblVlrAux, 2)
                            End If

                        End If

                    End If

                    If lstrCodigo = "0302010052" Then

                        lstrSql = ""
                        lstrSql = lstrSql & "SELECT codigo, valor, demanda_p, demanda_fp, demanda_fp_ant  "
                        lstrSql = lstrSql & "  FROM `descontoprovisorio` "
                        lstrSql = lstrSql & " WHERE zona = """ & astrZona & """ "
                        lstrSql = lstrSql & "   AND livro = """ & astrLivro & """ "
                        lstrSql = lstrSql & "   AND conta = """ & astrConta & """ "
                        lstrSql = lstrSql & "   AND codigo = '0302010052' "
                        lstrSql = lstrSql & "   AND mesano     = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
                        lstrSql = lstrSql & "   AND referencia = " & llngRefere & " "

                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                        dt_1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                        If dt_1.Rows.Count <> 0 Then

                            For Each row_1 As DataRow In dt_1.Rows

                                ldblPerc_Ant = CDbl(IIf(IsDBNull(row_1("valor")), 0, row_1("valor")))
                                ldblDem_P = CDbl(IIf(IsDBNull(row_1("demanda_p")), 0, row_1("demanda_p"))) '38550.22
                                ldblDem_FP = CDbl(IIf(IsDBNull(row_1("demanda_fp")), 0, row_1("demanda_fp"))) '20088
                                ldblDem_FP_ant = CDbl(IIf(IsDBNull(row_1("demanda_fp_ant")), 0, row_1("demanda_fp_ant")))

                                If ldblDem_P = 0 Or ldblDem_FP = 0 Then
                                    BuscaDemandasDescProv(astrZona, astrLivro, astrConta, alngConsId, alngUnidId, ldblDem_P, ldblDem_FP, llngRefere, ldblDem_FP_ant)
                                End If

                                If ldblPerc_Atu <> 0 Then
                                    'ldblValor = Truncate(((ldblDem_P + ldblDem_FP) * (1 + (ldblPerc_Ant / 100))) - ((ldblDem_P + ldblDem_FP) * (1 + (ldblPerc_Atu / 100))), 2)
                                    'ldblValor = Truncate(((ldblDem_P + ldblDem_FP) * ldblPerc_Ant / 100), 2)
                                    ldblValor = Truncate(((ldblDemandaContratadaForaPonta * idblTarDemanda_fp) * ldblPerc_Ant / 100), 2)
                                    ldblValor = Arredondar(ldblDem_FP_ant - ldblValor, 2)
                                Else
                                    ldblValor = 0
                                End If

                                row_grid = 1 + row_grid
                                grid_fatura.Rows = row_grid + 1
                                grid_fatura.Row = row_grid
                                grid_fatura.Col = 0

                                If ldblValor < 0 Then
                                    'DEVOLVO
                                    grid_fatura.Text = "0302020053"
                                    grid_fatura.Col = 1
                                    grid_fatura.Text = Trim(codTodescri("0302020053")) & " ( " & Truncate(ldblPerc_Atu, 6) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                    'grid_fatura.Text = Trim(codTodescri("0302020053")) & " ( " & Truncate(ldblPerc_Atu, 6) & "% - " & (Right(ilngAnoMes_Fat, 2) & "/" & Left(ilngAnoMes_Fat, 4)) & ")"
                                    grid_fatura.Col = 3
                                    grid_fatura.Text = VB6.Format(ldblValor * -1, "#,##0.00")
                                    grid_fatura.Col = 4
                                    grid_fatura.Text = " ( " & Truncate(ldblPerc_Atu, 5) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                    'grid_fatura.Text = " ( " & Truncate(ldblPerc_Atu, 5) & "% - " & (Right(ilngAnoMes_Fat, 2) & "/" & Left(ilngAnoMes_Fat, 4)) & ")"

                                Else
                                    'COBRO
                                    grid_fatura.Text = "0302020054"
                                    grid_fatura.Col = 1
                                    grid_fatura.Text = Trim(codTodescri("0302020054")) & " ( " & Truncate(ldblPerc_Atu, 6) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                    'grid_fatura.Text = Trim(codTodescri("0302020054")) & " ( " & Truncate(ldblPerc_Atu, 6) & "% - " & (Right(ilngAnoMes_Fat, 2) & "/" & Left(ilngAnoMes_Fat, 4)) & ")"
                                    grid_fatura.Col = 3
                                    grid_fatura.Text = VB6.Format(ldblValor, "#,##0.00")
                                    grid_fatura.Col = 4
                                    grid_fatura.Text = " ( " & Truncate(ldblPerc_Atu, 5) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                    'grid_fatura.Text = " ( " & Truncate(ldblPerc_Atu, 5) & "% - " & (Right(ilngAnoMes_Fat, 2) & "/" & Left(ilngAnoMes_Fat, 4)) & ")"
                                End If

                                grid_fatura.Col = 2
                                grid_fatura.Text = ""
                                vlrTotal = vlrTotal + ldblValor

                                'Alterado pela portaria SEF 344/2019
                                If CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) < glngPortaria_Sef_344_2019 Then
                                    ldblVlrAux = Truncate(IIf(ldblValor < 0, ldblValor * -1, ldblValor) / acoefTribIcms, 2)
                                    ldblVlrAux = Calc_ICMS(ldblVlrAux, gstrEmpresa_UF, aliq, 5)
                                    If ldblValor < 0 Then ldblVlrAux = ldblVlrAux * -1
                                    BaseICMS = Arredondar(BaseICMS + ldblVlrAux, 2)
                                End If


                            Next

                        End If


                    End If

                    If lstrCodigo = "0302010056" Then

                        lstrSql = ""
                        lstrSql = lstrSql & "SELECT codigo, valor, consumo_p, consumo_fp, consumo_p_ant "
                        lstrSql = lstrSql & "  FROM `descontoprovisorio` "
                        lstrSql = lstrSql & " WHERE zona = """ & astrZona & """ "
                        lstrSql = lstrSql & "   AND livro = """ & astrLivro & """ "
                        lstrSql = lstrSql & "   AND conta = """ & astrConta & """ "
                        lstrSql = lstrSql & "   AND codigo = '0302010056' "
                        lstrSql = lstrSql & "   AND mesano     = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
                        lstrSql = lstrSql & "   AND referencia = " & llngRefere & " "

                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                        dt_1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                        If dt_1.Rows.Count <> 0 Then

                            For Each row_1 As DataRow In dt_1.Rows

                                ldblPerc_Ant = CDbl(IIf(IsDBNull(row_1("valor")), 0, row_1("valor")))
                                ldblCon_P = CDbl(IIf(IsDBNull(row_1("consumo_p")), 0, row_1("consumo_p")))
                                ldblCon_FP = CDbl(IIf(IsDBNull(row_1("consumo_fp")), 0, row_1("consumo_fp")))
                                ldblCon_P_ant = CDbl(IIf(IsDBNull(row_1("consumo_p_ant")), 0, row_1("consumo_p_ant")))

                                If ldblCon_P = 0 Or ldblCon_FP = 0 Then
                                    BuscaEnergiaDescProv(astrZona, astrLivro, astrConta, alngConsId, alngUnidId, ldblCon_P, ldblCon_FP, llngRefere, ldblCon_P_ant)
                                End If

                                ldblCon_FP = 0

                                If ldblPerc_Atu <> 0 Then
                                    'ldblValor = Truncate(((ldblCon_P + ldblCon_FP) * (1 + (ldblPerc_Ant / 100))) - ((ldblCon_P + ldblCon_FP) * (1 + (ldblPerc_Atu / 100))), 2)
                                    ldblValor = Truncate(((ldblCon_P * ldblPerc_Ant) / 100), 2)
                                    ldblValor = Arredondar(ldblCon_P_ant - ldblValor, 2)
                                Else
                                    ldblValor = 0
                                End If

                                row_grid = 1 + row_grid
                                grid_fatura.Rows = row_grid + 1
                                grid_fatura.Row = row_grid
                                grid_fatura.Col = 0

                                If ldblValor < 0 Then
                                    'DEVOLVO
                                    grid_fatura.Text = "0302020057"
                                    grid_fatura.Col = 1
                                    grid_fatura.Text = Trim(codTodescri("0302020057")) & " ( " & Truncate(ldblPerc_Atu, 6) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                    grid_fatura.Col = 3
                                    grid_fatura.Text = VB6.Format(ldblValor * -1, "#,##0.00")
                                    grid_fatura.Col = 4
                                    grid_fatura.Text = " ( " & Truncate(ldblPerc_Atu, 5) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                Else
                                    'COBRO
                                    grid_fatura.Text = "0302020058"
                                    grid_fatura.Col = 1
                                    grid_fatura.Text = Trim(codTodescri("0302020058")) & " ( " & Truncate(ldblPerc_Atu, 6) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                    grid_fatura.Col = 3
                                    grid_fatura.Text = VB6.Format(ldblValor, "#,##0.00")
                                    grid_fatura.Col = 4
                                    grid_fatura.Text = " ( " & Truncate(ldblPerc_Atu, 5) & "% - " & (Microsoft.VisualBasic.Right(CStr(llngRefere), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRefere), 4)) & ")"
                                End If

                                grid_fatura.Col = 2
                                grid_fatura.Text = ""
                                vlrTotal = vlrTotal + ldblValor

                                'Alterado pela portaria SEF 344/2019
                                If CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) < glngPortaria_Sef_344_2019 Then
                                    ldblVlrAux = Truncate(IIf(ldblValor < 0, ldblValor * -1, ldblValor) / acoefTribIcms, 2)
                                    ldblVlrAux = Calc_ICMS(ldblVlrAux, gstrEmpresa_UF, aliq, 5)
                                    If ldblValor < 0 Then ldblVlrAux = ldblVlrAux * -1
                                    BaseICMS = Arredondar(BaseICMS + ldblVlrAux, 2)
                                End If


                            Next

                        End If


                    End If

                Next

            End If


            CobrarDescontoProvisorio = 0

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub BuscaDemandasDescProv(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByRef adblDemP As Double, ByRef adblDemFP As Double, ByVal alngReferencia As Integer, ByRef adblDemP_ant As Double)

        Dim lstrIte As String
        Dim lstrSql As String

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            lstrSql = "SELECT * "
            lstrSql = lstrSql & " FROM `nf`"
            lstrSql = lstrSql & " WHERE `mesano_ref` = " & alngReferencia & " "
            lstrSql = lstrSql & "   AND zona = '" & astrZona & "' "
            lstrSql = lstrSql & "   AND livro = '" & astrLivro & "' "
            lstrSql = lstrSql & "   AND conta = '" & astrConta & "' "
            If alngConsId > 0 Then
                lstrSql = lstrSql & "   AND cons_id = " & alngConsId & " "
            End If
            If alngUnidId > 0 Then
                lstrSql = lstrSql & "   AND unid_id = " & alngUnidId & " "
            End If
            lstrSql = lstrSql & "   AND `fatura_complementar` = 0"
            lstrSql = lstrSql & " LIMIT 0, 1"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    lstrIte = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))
                    adblDemP = BuscaValorItem(lstrIte, "0302020021")
                    adblDemFP = BuscaValorItem(lstrIte, "0302020023")
                    adblDemP_ant = BuscaValorItem(lstrIte, "0302020051")
                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub BuscaEnergiaDescProv(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByRef adblConsumoP As Double, ByRef adblConsumoFP As Double, ByVal alngReferencia As Integer, ByRef adblConsumoP_ant As Double)

        Dim ldblCoP As Double
        Dim ldblTap As Double
        Dim ldblTafp As Double
        Dim lstrIte As String
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try

            lstrSql = "SELECT * "
            lstrSql = lstrSql & " FROM `nf`"
            lstrSql = lstrSql & " WHERE `mesano_ref` = " & alngReferencia & " "
            lstrSql = lstrSql & "   AND zona = '" & astrZona & "' "
            lstrSql = lstrSql & "   AND livro = '" & astrLivro & "' "
            lstrSql = lstrSql & "   AND conta = '" & astrConta & "' "
            If alngConsId > 0 Then
                lstrSql = lstrSql & "   AND cons_id = " & alngConsId & " "
            End If
            If alngUnidId > 0 Then
                lstrSql = lstrSql & "   AND unid_id = " & alngUnidId & " "
            End If
            lstrSql = lstrSql & "   AND `fatura_complementar` = 0"
            lstrSql = lstrSql & " LIMIT 0, 1"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrIte = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))

                    If adblConsumoP = 0 Then adblConsumoP = BuscaValorItem(lstrIte, "0302020010")
                    If adblConsumoFP = 0 Then adblConsumoFP = 0 'BuscaValorItem(lstrIte, "0302020011")

                    If adblConsumoP_ant = 0 Then adblConsumoP_ant = BuscaValorItem(lstrIte, "0302020055")

                    '011101
                    '011105
                    ldblTap = BuscaValorItem(lstrIte, "01AL011101")
                    If ldblTap = 0 Then
                        ldblTap = BuscaValorItem(lstrIte, "01AL011105")
                    End If
                    ldblTafp = BuscaValorItem(lstrIte, "01AL011102")
                    If ldblTafp = 0 Then
                        ldblTafp = BuscaValorItem(lstrIte, "01AL011106")
                    End If
                    ldblCoP = BuscaValorItem(lstrIte, "0302010060")
                    If ldblCoP = 0 Then ldblCoP = BuscaValorItem(lstrIte, "0302010010")

                    adblConsumoP = Truncate(ldblCoP * (ldblTap - ldblTafp), 2)


                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CobrarParcelamento(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByRef vlrTotal As Double, ByRef row_grid As Short, ByRef aliq As Double, ByRef coef As Double, ByRef vlrIsentoIcms As Double)

        Dim ldteBase As Date
        Dim ldblId As Double
        Dim ldblValor As Double
        Dim ldblVlrAux As Double
        Dim lstrRefere As String
        Dim lstrCodigo As String
        Dim lstrSql As String

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            ldteBase = CDate("01/" & Me.txtMesAno.Text)
            ldteBase = CDate(UltimoDiaMes(Month(ldteBase), Year(ldteBase)) & "/" & Me.txtMesAno.Text)

            lstrSql = "SELECT * "
            lstrSql = lstrSql & "  FROM `parcelamento` "
            lstrSql = lstrSql & " WHERE `zona` = '" & astrZona & "' "
            lstrSql = lstrSql & "   AND `livro` = '" & astrLivro & "' "
            lstrSql = lstrSql & "   AND `conta` = '" & astrConta & "' "
            lstrSql = lstrSql & "   AND `cons_id` = " & alngConsId & " "
            lstrSql = lstrSql & "   AND `unid_id` = " & alngUnidId & " "
            lstrSql = lstrSql & "   AND `data_referencia` >= '" & VB6.Format(ldteBase, "yyyy-MM-dd") & "' "
            'lstrSql = lstrSql & "   AND ((`flg` = '' OR `flg` IS NULL) OR (`flg` = 'P' AND `anomes_fat` = " & Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) & ")) "
            lstrSql = lstrSql & "   AND (`flg` = '' OR `flg` IS NULL) LIMIT 1 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows


                    ldblId = CDbl(IIf(IsDBNull(row("id")), 0, row("id")))
                    ldblValor = CDbl(IIf(IsDBNull(row("valor")), 0, row("valor")))
                    lstrCodigo = IIf(IsDBNull(row("codigo")), 0, row("codigo"))
                    lstrRefere = IIf(IsDBNull(row("referencia")), "", row("referencia"))

                    If ldblValor > 0 Then

                        row_grid = 1 + row_grid
                        With Me.grid_fatura
                            .Rows = row_grid + 1
                            .Row = row_grid
                            .Col = 0
                            .Text = lstrCodigo
                            .Col = 1
                            .Text = Trim(codTodescri(lstrCodigo))
                            .Col = 2
                            .Text = ""
                            .Col = 3
                            .Text = VB6.Format(ldblValor, "#,##0.00")
                            .Col = 4
                            .Text = lstrRefere
                        End With

                        vlrIsentoIcms = vlrIsentoIcms + CDbl(Replace(CStr(ldblValor), ".", ","))
                        vlrTotal = vlrTotal + ldblValor

                        '----- Seta a parcela como paga ---------------------------------------------
                        lstrSql = "UPDATE `parcelamento` SET "
                        lstrSql = lstrSql & "         `flg`   = 'P'"
                        lstrSql = lstrSql & "       , `anomes_fat` = " & Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) & ""
                        lstrSql = lstrSql & "       , `cons_id` = " & alngConsId & ""
                        lstrSql = lstrSql & "       , `unid_id` = " & alngUnidId
                        lstrSql = lstrSql & " WHERE `id` = " & ldblId
                        '----------------------------------------------------------------------------

                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                    End If



                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobrarSobreTaxa(ByRef vlrTotal As Double, ByRef row_grid As Short, ByRef aliq As Double, ByRef coef As Double, ByRef vlrIsentoIcms As Double)

        Dim lstrSql As String
        Dim valor As Double


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            lstrSql = "SELECT * "
            lstrSql = lstrSql & "FROM `sobretaxa` "
            lstrSql = lstrSql & "WHERE zona = '" & txtZona.Text & "' "
            lstrSql = lstrSql & "AND livro = '" & txtLivro.Text & "' "
            lstrSql = lstrSql & "AND conta = '" & txtConta.Text & "' "
            lstrSql = lstrSql & "AND mesano = '" & txtMesAno.Text & "' "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    row_grid = 1 + row_grid

                    grid_fatura.Rows = row_grid + 1
                    grid_fatura.Row = row_grid
                    grid_fatura.Col = 0
                    grid_fatura.Text = row("codigo")
                    grid_fatura.Col = 1
                    grid_fatura.Text = Trim(codTodescri(row("codigo"))) & " " & row("referencia")
                    grid_fatura.Col = 2
                    grid_fatura.Text = ""
                    grid_fatura.Col = 3
                    grid_fatura.Text = VB6.Format(row("valor"), "#,##0.00")

                    '    If IncideICMS(consulta!codigo) Then
                    '      'valor = Arredondar(consulta!valor / coef, 2)
                    '      valor = valor + Calc_ICMS(consulta!valor, LeConfig("EMPRESA_UF"), aliq, 5)
                    '      vlrTotal = vlrTotal + consulta!valor 'Calc_ICMS(valor, LeConfig("EMPRESA_UF"), aliq, 5)
                    '      BaseICMS = BaseICMS + valor 'Calc_ICMS(valor, LeConfig("EMPRESA_UF"), aliq, 5)
                    '    Else
                    vlrIsentoIcms = vlrIsentoIcms + CDbl(Replace(row("valor"), ".", ","))
                    vlrTotal = vlrTotal + CDbl(Replace(row("valor"), ".", ","))
                    '    End If

                    lstrSql = "UPDATE `sobretaxa` SET "
                    lstrSql = lstrSql & "`flag` = 'P' "
                    lstrSql = lstrSql & "WHERE `zona` = '" & txtZona.Text & "' "
                    lstrSql = lstrSql & "AND `livro` = '" & txtLivro.Text & "' "
                    lstrSql = lstrSql & "AND `conta` = '" & txtConta.Text & "' "
                    lstrSql = lstrSql & "AND `mesano` = '" & txtMesAno.Text & "' "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CobrarConvenios(ByRef adblVlrTot As Double, ByRef row_grid As Short, ByVal adblAliquota As Double, ByVal adblCoeficiente As Double, ByRef adblVlrIsento As Double, ByVal adblCoefIsento As Double)

        Dim lstrSql As String
        Dim ldteFatura As Date
        Dim lstrInIcms As String
        Dim lstrInPiCo As String
        Dim ldblValor As Double
        Dim lstrRefere As String
        Dim lstrCdConv As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            ldteFatura = CDate("01/" & Me.txtMesAno.Text)

            lstrSql = ""
            lstrSql = lstrSql & "SELECT `convenios`.`convenio`   AS `codigo`, "
            lstrSql = lstrSql & "       `codigos`.`flgcasc`      AS `incideicms`, "
            lstrSql = lstrSql & "       `codigos`.`flgpiscof`    AS `incidepico`, "
            lstrSql = lstrSql & "       `convenios`.`ref`        AS `ref`, "
            lstrSql = lstrSql & "       SUM(`convenios`.`valor`) AS `valor` "
            lstrSql = lstrSql & "  FROM `convenios`, "
            lstrSql = lstrSql & "       `codigos` "
            lstrSql = lstrSql & " WHERE `convenios`.`zona`    = '" & Me.txtZona.Text & "' "
            lstrSql = lstrSql & "   AND `convenios`.`livro`   = '" & Me.txtLivro.Text & "' "
            lstrSql = lstrSql & "   AND `convenios`.`conta`   = '" & Me.txtConta.Text & "' "
            lstrSql = lstrSql & "   AND IFNULL(`convenios`.`sit`, '') NOT IN('Cancelado','Removido') "
            lstrSql = lstrSql & "   AND `codigos`.`num`       = `convenios`.`convenio` "
            lstrSql = lstrSql & "   AND """ & VB6.Format(ldteFatura, "yyyy-MM-dd") & """ BETWEEN `convenios`.`dt_ini` AND `convenios`.`dt_fim` "
            lstrSql = lstrSql & "GROUP BY 1, 2, 3, 4 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrCdConv = VB6.Format(IIf(IsDBNull(row("codigo")), "0", row("codigo")), "0000000000")
                    lstrInIcms = Trim(IIf(IsDBNull(row("incideicms")), "", row("incideicms")))
                    lstrInPiCo = Trim(IIf(IsDBNull(row("incidepico")), "", row("incidepico")))
                    lstrRefere = Trim(IIf(IsDBNull(row("ref")), "", row("ref")))
                    ldblValor = CDbl(IIf(IsDBNull(row("valor")), 0, row("valor")))
                    If Len(lstrRefere) > 0 Then
                        lstrRefere = "( " & lstrRefere & " )"
                    End If
                    With Me.grid_fatura
                        row_grid = 1 + row_grid
                        .Rows = row_grid + 1
                        .Row = row_grid
                        .Col = 0
                        .Text = lstrCdConv
                        .Col = 1
                        .Text = Trim(codTodescri(lstrCdConv)) & "  " & lstrRefere
                        .Col = 2
                        .Text = ""
                        .Col = 3
                        .Text = VB6.Format(ldblValor, "#,##0.00")
                        .Col = 4
                        .Text = lstrRefere
                    End With
                    If Mid(lstrCdConv, 1, 4) = "9070" Then
                        adblVlrTot = adblVlrTot - ldblValor
                        '            If lstrInIcms = "S" Then
                        '              'ldblValor = Arredondar(ldblValor / adblCoeficiente, 2)
                        '              ldblValor = Truncate(ldblValor / adblCoeficiente, 2)
                        '              BaseICMS = BaseICMS - Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              If lstrInPiCo = "S" Then
                        '                BasePis = BasePis - Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '                BaseCofins = BaseCofins - Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              End If
                        '            Else
                        adblVlrIsento = adblVlrIsento - ldblValor
                        '            End If
                    Else
                        adblVlrTot = adblVlrTot + ldblValor
                        '            If lstrInIcms = "S" Then
                        '              'ldblValor = Arredondar(ldblValor / adblCoeficiente, 2)
                        '              ldblValor = Truncate(ldblValor / adblCoeficiente, 2)
                        '              BaseICMS = BaseICMS + Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              If lstrInPiCo = "S" Then
                        '                BasePis = BasePis + Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '                BaseCofins = BaseCofins + Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              End If
                        '            Else
                        '              If lstrInPiCo = "S" Then
                        '                BasePis = BasePis + Calc_ICMS(Truncate(ldblValor / adblCoefIsento, 2), gstrEmpresa_UF, adblAliquota, 5)
                        '                BaseCofins = BaseCofins + Calc_ICMS(Truncate(ldblValor / adblCoefIsento, 2), gstrEmpresa_UF, adblAliquota, 5)
                        '              End If
                        '              adblVlrIsento = adblVlrIsento + ldblValor
                        '            End If
                    End If


                Next

                System.Windows.Forms.Application.DoEvents()

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobrarTaxas(ByRef adblVlrTot As Double, ByRef row_grid As Short, ByVal adblAliquota As Double, ByVal adblCoeficiente As Double, ByRef adblVlrIsento As Double)

        Dim lstrSql As String
        Dim ldteFatura As Date
        Dim lstrInIcms As String
        Dim lstrInPiCo As String
        Dim ldblValor As Double
        Dim lstrRefere As String
        Dim lstrCdTaxa As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            ldteFatura = CDate("01/" & Me.txtMesAno.Text)

            lstrSql = ""
            lstrSql = lstrSql & "SELECT `taxas`.`codigo`      AS `codigo`, "
            lstrSql = lstrSql & "       `codigos`.`flgcasc`   AS `incideicms`, "
            lstrSql = lstrSql & "       `codigos`.`flgpiscof` AS `incidepico`, "
            lstrSql = lstrSql & "       `taxas`.`ref`         AS `ref`, "
            lstrSql = lstrSql & "       SUM(`taxas`.`valor`)  AS `valor` "
            lstrSql = lstrSql & "  FROM `taxas`, "
            lstrSql = lstrSql & "       `codigos` "
            lstrSql = lstrSql & " WHERE `taxas`.`zona`    = '" & Me.txtZona.Text & "' "
            lstrSql = lstrSql & "   AND `taxas`.`livro`   = '" & Me.txtLivro.Text & "' "
            lstrSql = lstrSql & "   AND `taxas`.`conta`   = '" & Me.txtConta.Text & "' "
            lstrSql = lstrSql & "   AND IFNULL(`taxas`.`sit`, '') NOT IN('Cancelado','Removido') "
            lstrSql = lstrSql & "   AND `codigos`.`num`   = `taxas`.`codigo` "
            lstrSql = lstrSql & "   AND """ & VB6.Format(ldteFatura, "yyyy-MM-dd") & """ BETWEEN `taxas`.`dt_ini` AND `taxas`.`dt_fim` "
            lstrSql = lstrSql & "GROUP BY 1, 2, 3, 4 "


            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrCdTaxa = VB6.Format(IIf(IsDBNull(row("codigo")), "0", row("codigo")), "0000000000")
                    lstrInIcms = Trim(IIf(IsDBNull(row("incideicms")), "", row("incideicms")))
                    lstrInPiCo = Trim(IIf(IsDBNull(row("incidepico")), "", row("incidepico")))
                    lstrRefere = Trim(IIf(IsDBNull(row("ref")), "", row("ref")))
                    ldblValor = CDbl(IIf(IsDBNull(row("valor")), 0, row("valor")))

                    If Len(lstrRefere) > 0 Then
                        lstrRefere = "( " & lstrRefere & " )"
                    End If

                    With Me.grid_fatura
                        row_grid = 1 + row_grid
                        .Rows = row_grid + 1
                        .Row = row_grid
                        .Col = 0
                        .Text = lstrCdTaxa
                        .Col = 1
                        .Text = Trim(codTodescri(lstrCdTaxa)) & "  " & lstrRefere
                        .Col = 2
                        .Text = ""
                        .Col = 3
                        .Text = VB6.Format(ldblValor, "#,##0.00")
                        .Col = 4
                        .Text = lstrRefere
                    End With

                    If Mid(lstrCdTaxa, 1, 4) = "9070" Then

                        adblVlrTot = adblVlrTot - ldblValor
                        '            If lstrInIcms = "S" Then
                        '              'ldblValor = Arredondar(ldblValor / adblCoeficiente, 2)
                        '              ldblValor = Truncate(ldblValor / adblCoeficiente, 2)
                        '              BaseICMS = BaseICMS - Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              If lstrInPiCo = "S" Then
                        '                BasePis = BasePis - Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '                BaseCofins = BaseCofins - Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              End If
                        '            Else
                        adblVlrIsento = adblVlrIsento - ldblValor
                        '            End If

                    Else

                        adblVlrTot = adblVlrTot + ldblValor
                        '            If lstrInIcms = "S" Then
                        '              'ldblValor = Arredondar(ldblValor / adblCoeficiente, 2)
                        '              ldblValor = Truncate(ldblValor / adblCoeficiente, 2)
                        '              BaseICMS = BaseICMS + Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              If lstrInPiCo = "S" Then
                        '                BasePis = BasePis + Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '                BaseCofins = BaseCofins + Calc_ICMS(ldblValor, gstrEmpresa_UF, adblAliquota, 5)
                        '              End If
                        '            Else
                        adblVlrIsento = adblVlrIsento + ldblValor
                        '            End If

                    End If

                Next

                System.Windows.Forms.Application.DoEvents()

            End If

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub Loca_Consumidor()

        Dim lstr_classe As String
        Dim ldteBase As Date
        Dim lstrSql As String
        Dim lstrSql1 As String
        Dim lintDiaVenc As Integer

        Dim dt As DataTable
        Dim dt1 As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            LigDesBotoes(False)
            LimpaCamposFatGrupoA()

            Me.txtBaseTributacao.Text = "0,00"
            iblnMicroGeracaoConvenioSefaz = False
            ldteBase = CDate("01/" & Me.txtMesAno.Text)

            If Trim(txtZona.Text) <> "" And Trim(txtLivro.Text) <> "" And Trim(txtConta.Text) <> "" Then

                lstrSql = ""
                lstrSql = lstrSql & "SELECT * "
                lstrSql = lstrSql & "  FROM `uc_faturamento` "
                lstrSql = lstrSql & " WHERE `zona`  ='" & Me.txtZona.Text & "' "
                lstrSql = lstrSql & "   AND `livro` ='" & Me.txtLivro.Text & "' "
                lstrSql = lstrSql & "   AND `conta` ='" & Me.txtConta.Text & "' "

                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                If dt.Rows.Count <> 0 Then

                    For Each row As DataRow In dt.Rows

                        Me.txtNome.Text = Trim(IIf(IsDBNull(row("nome")), "", row("nome")))

                        Me.txtTA.Text = Trim(IIf(IsDBNull(row("ta")), "01A400", row("ta")))

                        idblConsId = CDbl(IIf(IsDBNull(row("cons_id")), 0, row("cons_id")))

                        lstrSql1 = ""
                        lstrSql1 = lstrSql1 & "SELECT * "
                        lstrSql1 = lstrSql1 & "  FROM `consum` "
                        lstrSql1 = lstrSql1 & " WHERE `consreg`  ='" & idblConsId & "' "

                        objAtualizaBancoDados.QUERY_NAME = lstrSql1
                        dt1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                        If dt1.Rows.Count <> 0 Then
                            For Each row_1 As DataRow In dt1.Rows
                                ilngMatricula = IIf(IsDBNull(row_1("matricula")), 0, row_1("matricula"))
                            Next
                        End If

                        idblUnidId = CDbl(IIf(IsDBNull(row("id")), 0, row("id")))

                        istrClasse = VB6.Format(Trim(IIf(IsDBNull(row("clas")), "0000", row("clas"))), "0000")
                        '
                        If CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 1)) < 4 Then
                            lstr_classe = "Industrial"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 1)) = 4 Then
                            lstr_classe = "Comercial"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 1)) = 5 Then
                            lstr_classe = "Rural"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 1)) = 7 Then
                            lstr_classe = "Serviço Público"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 1)) = 8 Then
                            lstr_classe = "Consumo Próprio"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 1)) = 9 Then
                            lstr_classe = "Residencial"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 2)) = 61 Then
                            lstr_classe = "Poder Público Municipal"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 2)) = 62 Then
                            lstr_classe = "Poder Público Estadual"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 2)) = 63 Then
                            lstr_classe = "Poder Público Federal"
                        ElseIf CShort(Microsoft.VisualBasic.Left(IIf(IsNumeric(istrClasse), istrClasse, 0), 2)) = 64 Then
                            lstr_classe = "Iluminação Pública"
                        End If

                        Me.txt_Descricao_Classe_Consumo.Text = lstr_classe & " / " & GetValorTabela(" `classe`", "`descricao`", "`codigo` = '" & istrClasse & "'", "")
                        '

                        istrQH = IIf(IsDBNull(row("qh")), "N", row("qh"))

                        istrNrBco = Trim(IIf(IsDBNull(row("banco")), "0", row("banco")))
                        If IsNumeric(istrNrBco) Then
                            istrNmBco = RetornaNomeBanco(CInt(istrNrBco))
                        Else
                            istrNmBco = ""
                        End If

                        istrAgencia = Trim(IIf(IsDBNull(row("agenc")), "", row("agenc")))

                        istrContaCorrente = Trim(IIf(IsDBNull(row("cc")), "", row("cc")))

                        istrCpfCnpj = IIf(IsDBNull(row("cpf_cnpj")), "", row("cpf_cnpj"))

                        istrInsEst = IIf(IsDBNull(row("insc")), "", row("insc"))

                        istrUF = Trim(IIf(IsDBNull(row("uf")), gstrEmpresa_UF, row("uf")))

                        istrTensao = Trim(IIf(IsDBNull(row("tensao")), "380", row("tensao")))

                        istrFase = Trim(IIf(IsDBNull(row("fase")), "T", row("fase")))

                        istrRota = Trim(IIf(IsDBNull(row("rota")), "0", row("rota")))

                        istrcaderno = Trim(IIf(IsDBNull(row("caderno")), "0", row("caderno")))

                        idblCfop = CDbl(Trim(IIf(IsDBNull(row("cfop")), 0, row("cfop"))))

                        If idblCfop = 0 Then
                            idblCfop = (GetCFOP(istrClasse, "A") / 1000)
                        Else
                            idblCfop = idblCfop / 1000
                        End If
                        '

                        Me.txtDemContr_p.Text = VB6.Format(IIf(IsDBNull(row("dem_contr_ponta")), 0, row("dem_contr_ponta")), "#,##0.00")

                        Me.txtDemContr_fp.Text = VB6.Format(IIf(IsDBNull(row("dem_contr_fp")), 0, row("dem_contr_fp")), "#,##0.00")

                        Me.txtDemContr_Anterior_p.Text = FormatNumber(IIf(IsDBNull(row("dem_contr_ponta_anterior")), 0, row("dem_contr_ponta_anterior")), 2)

                        Me.txtDemContr_Anterior_fp.Text = FormatNumber(IIf(IsDBNull(row("dem_contr_fp_anterior")), 0, row("dem_contr_fp_anterior")), 2)                        '

                        iblnIcmsDemLida = (Trim(IIf(IsDBNull(row("icms_demanda_lida")), "N", row("icms_demanda_lida"))) = "S")

                        iblnParCativo = (CShort(IIf(IsDBNull(row("parcialmente_cativo")), 0, row("parcialmente_cativo"))) = 1)

                        iblnPeriodoTeste = (CShort(IIf(IsDBNull(row("periodo_teste")), 0, row("periodo_teste"))) = 1)

                        idteIniPeriodoTeste = IIf(IsDBNull(row("ini_periodo_teste")), "01/01/1900", row("ini_periodo_teste"))

                        idteFimPeriodoTeste = IIf(IsDBNull(row("fim_periodo_teste")), "01/01/1900", row("fim_periodo_teste"))
                        Me.txt_Msg_Periodo_Teste.Text = ""
                        Me.txt_Msg_Periodo_Teste.BackColor = System.Drawing.ColorTranslator.FromOle(&H8000000F)

                        If iblnPeriodoTeste Then

                            Valida_Periodo_Teste(idteIniPeriodoTeste, idteFimPeriodoTeste, CDbl(IIf(IsNumeric(Me.txtDemContr_Anterior_p.Text), Me.txtDemContr_Anterior_p.Text, 0)), CDbl(IIf(IsNumeric(Me.txtDemContr_Anterior_fp.Text), Me.txtDemContr_Anterior_fp.Text, 0)), CDbl(IIf(IsNumeric(Me.txtDemContr_p.Text), Me.txtDemContr_p.Text, 0)), CDbl(IIf(IsNumeric(Me.txtDemContr_fp.Text), Me.txtDemContr_fp.Text, 0)))
                            'Me.txt_Periodo_Teste.Text = "Sim - De: " & Strings.Format(idteIniPeriodoTeste, "MM/yyyy") & " Até: " & Strings.Format(idteFimPeriodoTeste, "MM/yyyy")
                            'If CDbl(IIf(IsNumeric(Me.txtDemContr_p.Text), Me.txtDemContr_p.Text, 0)) > 0 Then
                            '  If CDbl(IIf(IsNumeric(Me.txtDemContr_Anterior_p.Text), Me.txtDemContr_Anterior_p.Text, 0)) = 0 Then
                            '    Me.txt_Msg_Periodo_Teste.Text = "Erro Demanda Ponta! Revise."
                            '    Me.txt_Msg_Periodo_Teste.BackColor = &HFF&
                            '  End If
                            'End If
                            'If CDbl(IIf(IsNumeric(Me.txtDemContr_fp.Text), Me.txtDemContr_fp.Text, 0)) > 0 Then
                            '  If CDbl(IIf(IsNumeric(Me.txtDemContr_Anterior_fp.Text), Me.txtDemContr_Anterior_fp.Text, 0)) = 0 Then
                            '    Me.txt_Msg_Periodo_Teste.Text = "Erro Demanda Fora Ponta! Revise."
                            '    Me.txt_Msg_Periodo_Teste.BackColor = &HFF&
                            '  End If
                            'End If
                            'If CLng(Strings.Format(idteFimPeriodoTeste, "yyyyMM")) < CLng(Strings.Right(Me.txtMesAno.Text, 4) & Strings.Left(Me.txtMesAno.Text, 2)) Then
                            '  Me.txt_Msg_Periodo_Teste.Text = "Teste Vencido!, Revise"
                            '  Me.txt_Msg_Periodo_Teste.BackColor = &HFF&
                            'End If
                        Else
                            Me.txt_Periodo_Teste.Text = "Não"
                        End If

                        iintLivreEspecial = IIf(IsDBNull(row("livreespecial")), 0, row("livreespecial"))

                        iintLivreVerde = IIf(IsDBNull(row("livre_verde")), 0, row("livre_verde"))

                        iintLivreLeituraConsumo = CShort(IIf(IsDBNull(row("livre_leitura_consumo")), 0, row("livre_leitura_consumo")))

                        iintMicroGeracao = IIf(IsDBNull(row("micro_geracao")), 0, row("micro_geracao"))

                        'Define o tipo de Tarifa
                        If Mid(Me.txtTA.Text, 3, 2) = "AV" Or iintLivreVerde = 1 Then
                            iintTipoTarifa = 1
                        ElseIf Mid(Me.txtTA.Text, 3, 2) = "AA" Or Mid(Me.txtTA.Text, 3, 2) = "AL" Or Mid(Me.txtTA.Text, 3, 2) = "AX" Then
                            iintTipoTarifa = 2
                        ElseIf Mid(Me.txtTA.Text, 3, 2) = "AP" Then
                            iintTipoTarifa = 3
                        ElseIf Mid(Me.txtTA.Text, 3, 2) = "A4" Or Mid(Me.txtTA.Text, 3, 2) = "AS" Then
                            'iintTipoTarifa = 0
                            iintTipoTarifa = 1
                        End If

                        'Outros
                        'Me.txtFmKwhP.Text = Strings.Format(IIf(IsNull(row("const_cons_p")), 0, row("const_cons_p")), "#,#####0.00000")
                        'Me.txtFmKwhFP.Text = Strings.Format(IIf(IsNull(row("const_cons_fp")), 0, row("const_cons_fp")), "#,#####0.00000")
                        'Me.txtFmKwP.Text = Strings.Format(IIf(IsNull(row("const_demanda")), 0, row("const_demanda")), "#,#####0.00000")
                        'Me.txtFmKwFP.Text = Strings.Format(IIf(IsNull(row("const_demanda_fp")), 0, row("const_demanda_fp")), "#,#####0.00000")
                        'Me.txtFmKvarhP.Text = Strings.Format(IIf(IsNull(row("const_kvarh_p")), 0, row("const_kvarh_p")), "#,#####0.00000")
                        'Me.txtFmKvarhFP.Text = Strings.Format(IIf(IsNull(row("const_kvarh_fp")), 0, row("const_kvarh_fp")), "#,#####0.00000")
                        ''

                        Me.txtFmKwhP.Text = VB6.Format(IIf(IsDBNull(row("const_kwh_p")), 0, row("const_kwh_p")), "#,#####0.00000")

                        Me.txtFmKwhFP.Text = VB6.Format(IIf(IsDBNull(row("const_kwh_fp")), 0, row("const_kwh_fp")), "#,#####0.00000")

                        Me.txtFmKwP.Text = VB6.Format(IIf(IsDBNull(row("const_kw_p")), 0, row("const_kw_p")), "#,#####0.00000")

                        Me.txtFmKwFP.Text = VB6.Format(IIf(IsDBNull(row("const_kw_fp")), 0, row("const_kw_fp")), "#,#####0.00000")

                        Me.txtFmKvarhP.Text = VB6.Format(IIf(IsDBNull(row("const_kvarh_p")), 0, row("const_kvarh_p")), "#,#####0.00000")

                        Me.txtFmKvarhFP.Text = VB6.Format(IIf(IsDBNull(row("const_kvarh_fp")), 0, row("const_kvarh_fp")), "#,#####0.00000")
                        '
                        'Me.txtPerdas.Text = VB6.Format(IIf(IsDBNull(row("final")), 0, row("final")), "#,##0.00")
                        Me.txtPerdas.Text = IIf(IsDBNull(row("final")), 0, row("final"))
                        '
                        'Me.txtReverso_Residuo_p.Text = VB6.Format(CDbl(IIf(IsDBNull(row("kwh_reverso_res_p")), 0, row("kwh_reverso_res_p"))), "#,##0.00000")

                        Me.txtReverso_Residuo_fp.Text = VB6.Format(CDbl(IIf(IsDBNull(row("kwh_reverso_res_fp")), 0, row("kwh_reverso_res_fp"))), "#,##0.00000")
                        '
                        iblnMicroGeracaoConvenioSefaz = True ' VerificaExisteRegistro("micro_geracao_convenio_sefaz", "grupo = 'A' AND unid_id = " & idblUnidId & " AND vigencia_inicio <= '" & VB6.Format(ldteBase, "yyyy-MM-dd") & "' AND vigencia_fim >= '" & VB6.Format(ldteBase, "yyyy-MM-dd") & "' AND `ativo` = 1")

                        iCep = Trim(IIf(IsDBNull(row("cep")), "0", row("cep")))

                        iCidade = Trim(IIf(IsDBNull(row("codcidade")), "", row("codcidade")))

                        iUF = Trim(IIf(IsDBNull(row("uf")), "", row("uf")))

                        iIBGE = fRetornaIBGE(iCidade)

                        lintDiaVenc = IIf(IsDBNull(row("diavenc")), "10", row("diavenc"))

                    Next

                End If


                'Carrega as leituras anteriores
                If idblUnidId > 0 And idblConsId > 0 Then

                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT * "
                    lstrSql = lstrSql & "  FROM `leitura` "
                    lstrSql = lstrSql & " WHERE `id_unid`       =  " & idblUnidId
                    lstrSql = lstrSql & "   AND `id_consumidor` =  " & idblConsId
                    lstrSql = lstrSql & "   AND `mesano`        = '" & Me.txtMesAno.Text & "' "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            iblnExisteLeitura = True
                            'Datas

                            Me.txtDt_Faturamento.Text = VB6.Format(CDate(IIf(IsDBNull(row("dt_faturamento")), idteBase, row("dt_faturamento"))), "DD/MM/YYYY")

                            Me.txtDt_Leit_Anterior.Text = VB6.Format(CDate(IIf(IsDBNull(row("dt_leit_anterior")), idteBase, row("dt_leit_anterior"))), "DD/MM/YYYY")

                            Me.txtDt_Prox_Leit.Text = VB6.Format(CDate(IIf(IsDBNull(row("dt_prox_leit")), idteBase, row("dt_prox_leit"))), "DD/MM/YYYY")

                            ' Me.txtDt_Leit_Atual.Text = VB6.Format(CDate(IIf(IsDBNull(row("dt_leit_atual")), idteBase, row("dt_leit_atual"))), "DD/MM/YYYY")

                            Me.txtDt_Vencto.Text = lintDiaVenc & VB6.Format(CDate(IIf(IsDBNull(row("dt_vencto")), idteBase, row("dt_vencto"))), "/MM/YYYY")

                            Me.txtDt_Apresenta.Text = VB6.Format(CDate(IIf(IsDBNull(row("dt_apresenta")), idteBase, row("dt_apresenta"))), "DD/MM/YYYY")
                            'Valores
                            If iintTipoTarifa < 1 Then 'Convencional não possui posto tarifário

                                Me.txtLeit_Consumo.Text = VB6.Format(CDbl(IIf(IsDBNull(row("consumo_p")), 0, row("consumo_p"))), "#,##0.00")

                                Me.txtLeit_Demanda.Text = VB6.Format(CDbl(IIf(IsDBNull(row("demanda_p")), 0, row("demanda_p"))), "#,##0.00")

                                Me.txtLeit_Kvarh.Text = VB6.Format(CDbl(IIf(IsDBNull(row("kvarh")), 0, row("kvarh"))), "#,##0.00")
                            Else

                                Me.txtConsumo_p.Text = VB6.Format(CDbl(IIf(IsDBNull(row("consumo_p")), 0, row("consumo_p"))), "#,##0.00000")

                                Me.txtDemanda_p.Text = VB6.Format(CDbl(IIf(IsDBNull(row("demanda_p")), 0, row("demanda_p"))), "#,##0.00000")

                                Me.txtKvarh_P.Text = VB6.Format(CDbl(IIf(IsDBNull(row("kvarh")), 0, row("kvarh"))), "#,##0.00000")

                                Me.txtConsumo_FP.Text = VB6.Format(CDbl(IIf(IsDBNull(row("consumo_fp")), 0, row("consumo_fp"))), "#,##0.00000")

                                Me.txtDemanda_FP.Text = VB6.Format(CDbl(IIf(IsDBNull(row("demanda_fp")), 0, row("demanda_fp"))), "#,##0.00000")

                                Me.txtKvarh_FP.Text = VB6.Format(CDbl(IIf(IsDBNull(row("kvarh_fp")), 0, row("kvarh_fp"))), "#,##0.00000")

                                Me.txtDem_Exc_Ponta.Text = VB6.Format(CDbl(IIf(IsDBNull(row("dem_exc_ponta")), 0, row("dem_exc_ponta"))), "#,##0.00000")

                                Me.txtDem_Exc_FP.Text = VB6.Format(CDbl(IIf(IsDBNull(row("dem_exc_fp")), 0, row("dem_exc_fp"))), "#,##0.00000")

                                Me.txtParCatMWhMedio.Text = VB6.Format(CDbl(IIf(IsDBNull(row("par_cat_mwh_medio")), 0, row("par_cat_mwh_medio"))), "#,########0.00000000")

                                Me.txtParCatHoras.Text = VB6.Format(CDbl(IIf(IsDBNull(row("par_cat_horas")), 0, row("par_cat_horas"))), "#0")

                                Me.txtReverso_p.Text = VB6.Format(CDbl(IIf(IsDBNull(row("reverso_p")), 0, row("reverso_p"))), "#,##0.00000")

                                Me.txtReverso_fp.Text = VB6.Format(CDbl(IIf(IsDBNull(row("reverso_fp")), 0, row("reverso_fp"))), "#,##0.00000")
                                '
                                'If Me.txtReverso_Residuo_p.Text = "" Then Me.txtReverso_Residuo_p.Text = VB6.Format(CDbl(IIf(IsDBNull(row("reverso_res_p")), Me.txtReverso_Residuo_p.Text, row("reverso_res_p"))), "#,##0.00000")
                                If Me.txtReverso_Residuo_fp.Text = "" Then Me.txtReverso_Residuo_fp.Text = VB6.Format(CDbl(IIf(IsDBNull(row("reverso_res_fp")), Me.txtReverso_Residuo_fp.Text, row("reverso_res_fp"))), "#,##0.00000")

                            End If

                        Next

                    Else
                        iblnExisteLeitura = False
                    End If


                    idblAliqICMS = Busca_Aliquota_ICMS(istrUF, 0, istrClasse)

                End If 'idblUnidId > 0 And idblConsId > 0

                Me.dtpMesAnoConsumo.Value = CDate("01/" & VB6.Format(System.DateTime.FromOADate(CDate("01/" & VB6.Format(System.DateTime.FromOADate(CDate("01/" & Me.txtMesAno.Text).ToOADate - 1), "MM/yyyy")).ToOADate - 1), "MM/yyyy"))

                HabilitaGuias()

                Me.sstLeituras.SelectedIndex = IIf((iintTipoTarifa = 1 Or iintTipoTarifa = 2), 2, IIf(iintTipoTarifa = 3, 1, iintTipoTarifa))

                If Mid(Me.txtTA.Text, 3, 2) = "AL" Then
                    If CInt(VB6.Format(Me.dtpMesAnoConsumo, "yyyyMM")) >= 201309 Then
                        cmdCCEEBuscaDados_Click(cmdCCEEBuscaDados, New System.EventArgs())
                    End If
                End If

            End If 'Strings.Trim(txtZona.Text) <> "" And Strings.Trim(txtLivro.Text) <> "" And Strings.Trim(txtConta.Text) <> ""

            iintBanderiaVigente = BuscaBandeira(CDate("01/" & Me.txtMesAno.Text), idteBandeira, istrClasse)
            LigDesBotoes(True)


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub MontaPercentual_demanda()

        'esta rotina foi criada por a procedure Calc_Horosazonal Estourou o limite de linhas do VB6 para uma procedure
        Dim lstrPercDemU As String
        Dim ldblPercDemUP As Double
        Dim ldblPercDemUFP As Double

        Try

            lstrPercDemU = Trim(GetConfig("grupoa.percentual.kw.ultra.p"))

            If lstrPercDemU = "-1" Then
                If Mid(txtTA.Text, 1, 4) = "01AL" Then 'Consumidor Livre
                    ldblPercDemUP = 5
                Else
                    ldblPercDemUP = 10
                End If
                SetConfig("grupoa.percentual.kw.ultra.p", "String", CStr(ldblPercDemUP), CStr(ldblPercDemUP), "Percentual de Demanda Ultrapassagem na ponta")
            ElseIf Len(lstrPercDemU) = 0 Then
                If Mid(txtTA.Text, 1, 4) = "01AL" Then 'Consumidor Livre
                    ldblPercDemUP = 5
                Else
                    ldblPercDemUP = 10
                End If
                SetConfig("grupoa.percentual.kw.ultra.p", "String", CStr(ldblPercDemUP), CStr(ldblPercDemUP), "Percentual de Demanda Ultrapassagem na ponta")
            Else
                ldblPercDemUP = CDbl(lstrPercDemU)
            End If
            '
            lstrPercDemU = Trim(GetConfig("grupoa.percentual.kw.ultra.fp"))
            If lstrPercDemU = "-1" Then
                If Mid(txtTA.Text, 1, 4) = "01AL" Then 'Consumidor Livre
                    ldblPercDemUFP = 5
                Else
                    ldblPercDemUFP = 10
                End If
                SetConfig("grupoa.percentual.kw.ultra.fp", "String", CStr(ldblPercDemUFP), CStr(ldblPercDemUFP), "Percentual de Demanda Ultrapassagem fora da ponta")
            ElseIf Len(lstrPercDemU) = 0 Then
                If Mid(txtTA.Text, 1, 4) = "01AL" Then 'Consumidor Livre
                    ldblPercDemUFP = 5
                Else
                    ldblPercDemUFP = 10
                End If
                SetConfig("grupoa.percentual.kw.ultra.fp", "String", CStr(ldblPercDemUFP), CStr(ldblPercDemUFP), "Percentual de Demanda Ultrapassagem fora da ponta")
            Else
                ldblPercDemUFP = CDbl(lstrPercDemU)
            End If


        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Private Sub Inicializa_Campos_Text_Para_Evitar_Branco()


        Try


            'esta rotina foi criada por a procedure Calc_Horosazonal Estourou o limite de linhas do VB6 para uma procedure
            If Len(Trim(Me.txtAjusteDemandaP.Text)) = 0 Then Me.txtAjusteDemandaP.Text = "0"
            If Len(Trim(Me.txtAjusteDemandaFP.Text)) = 0 Then Me.txtAjusteDemandaFP.Text = "0"
            If Len(Trim(Me.txtConsumo_FP.Text)) = 0 Then Me.txtConsumo_FP.Text = "0"
            If Len(Trim(Me.txtConsumo_p.Text)) = 0 Then Me.txtConsumo_p.Text = "0"
            If Len(Trim(Me.txtDemanda_p.Text)) = 0 Then Me.txtDemanda_p.Text = "0"
            If Len(Trim(Me.txtDemanda_FP.Text)) = 0 Then Me.txtDemanda_FP.Text = "0"
            If Len(Trim(Me.txtKvarh_P.Text)) = 0 Then Me.txtKvarh_P.Text = "0"
            If Len(Trim(Me.txtKvarh_FP.Text)) = 0 Then Me.txtKvarh_FP.Text = "0"
            If Len(Trim(Me.txtDem_Exc_FP.Text)) = 0 Then Me.txtDem_Exc_FP.Text = "0"
            If Len(Trim(Me.txtDem_Exc_Ponta.Text)) = 0 Then Me.txtDem_Exc_Ponta.Text = "0"
            If Len(Trim(Me.txtParCatMWhMedio.Text)) = 0 Then Me.txtParCatMWhMedio.Text = "0,00000000"
            If Len(Trim(Me.txtParCatHoras.Text)) = 0 Then Me.txtParCatHoras.Text = "0"

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Function Virada_Medidor(ByVal adbl_Valor_Atual As Double, ByVal adbl_Valor_Anterior As Object) As Double

        Dim ldbl_Leitura_Atual As Double
        Dim ldbl_Valor_Atual As Double

        Try

            ldbl_Leitura_Atual = adbl_Valor_Atual
            If ldbl_Leitura_Atual > 0 Then

                ldbl_Valor_Atual = ldbl_Leitura_Atual - adbl_Valor_Anterior

                If ldbl_Valor_Atual < 0 Then

                    Select Case Len(Trim(Str(adbl_Valor_Anterior)))
                        Case 4
                            ldbl_Leitura_Atual = 9999 + ldbl_Leitura_Atual + 1
                        Case 5
                            ldbl_Leitura_Atual = 99999 + ldbl_Leitura_Atual + 1
                        Case 6
                            ldbl_Leitura_Atual = 999999 + ldbl_Leitura_Atual + 1
                        Case 7
                            ldbl_Leitura_Atual = 9999999 + ldbl_Leitura_Atual + 1
                        Case 8
                            ldbl_Leitura_Atual = 99999999 + ldbl_Leitura_Atual + 1
                    End Select
                End If
                'Refazer os calculo de consumo para apurar consumo real

                ldbl_Valor_Atual = (ldbl_Leitura_Atual - adbl_Valor_Anterior)

            End If
            Virada_Medidor = ldbl_Valor_Atual




        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function Monta_Codigos_Inviduais_Tributacao(ByVal aint_Index As Short, ByVal astr_Tipo As String, ByVal astr_Campo As String) As String

        Dim lstr_Prefixo As String
        Dim lstr_Codigo As String


        Try

            '
            If astr_Tipo = "BASE" Then
                lstr_Prefixo = "1"
            ElseIf astr_Tipo = "TRIBUTO" Then
                lstr_Prefixo = "2"
            ElseIf astr_Tipo = "VALOR" Then
                lstr_Prefixo = "3"
            End If
            '
            If astr_Campo = "ICMS" Then
                lstr_Prefixo = lstr_Prefixo & "0"
            ElseIf astr_Campo = "PIS" Then
                lstr_Prefixo = lstr_Prefixo & "1"
            ElseIf astr_Campo = "COFINS" Then
                lstr_Prefixo = lstr_Prefixo & "2"
            End If
            '
            Select Case aint_Index
                Case Is = 0 'Consumo Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020010"
                Case Is = 1 'Encargo Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020060"
                Case Is = 2 'Bandeira Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "120010"
                Case Is = 3 'Consumo Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020011"
                Case Is = 4 'Encargo Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020061"
                Case Is = 5 'Bandeira Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "120011"
                Case Is = 6 'Demanda Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020021"
                Case Is = 7 'Demanda Ultrapassagem Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020022"
                Case Is = 8 'Diferença Contrato de Demanda Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020121"
                Case Is = 9 'Demanda Fora Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020023"
                Case Is = 10 'Demanda Ultrapassagem Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020026"
                Case Is = 11 'Diferença Contrato de Demanda Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020123"
                Case Is = 12 'Ufer Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020013"
                Case Is = 13 'Ufer Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020014"
                Case Is = 14 'Dmcr Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020027"
                Case Is = 15 'Dmcr Fora de Ponta
                    lstr_Codigo = "05" & lstr_Prefixo & "020028"
            End Select

            Monta_Codigos_Inviduais_Tributacao = lstr_Codigo


        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Public Sub SalvaGD(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngConsId As Long, ByVal alngUnidId As Long, ByVal adblconsumo_p As Double, ByVal adblconsumo_fp As Double, ByVal adblReverso_p As Double, ByVal adblReverso_fp As Double, ByVal adteLeitura As Date, ByVal adteFatur As Date, ByVal ldblReversokWhCompMes_Ponta As Double, ByVal ldblReversokWhCompMes_ForaPonta As Double, ByVal adblDifReverso As Double, ByVal aintTarifaBranca As Short, ByVal ldblReversokWhTranfOutro As Double, ByVal ldblReversokWhSaldoAtual As Double, ByVal ldblGerado_Recebido As Double, ByVal ldblReversokWhSaldoAnterior As Double)

        Dim ldblDifReverso As Double

        Dim dt As DataTable

        Dim objGDCompensacao As New entidadeGDCompensacao
        Dim repositorioGDCompensacao As New repositorioGDCompensacao

        Dim objGDMovimentacao As New entidadeGDMovimentacao
        Dim repositorioGDMovimentacao As New repositorioGDMovimentacao

        Dim vlist As Object

        Try

            'If adblDifReverso < 0 Then
            ldblDifReverso = adblDifReverso
            'End If

            objGDCompensacao.ZONA = astrZona
            objGDCompensacao.LIVRO = astrLivro
            objGDCompensacao.CONTA = astrConta
            objGDCompensacao.CONS_ID = alngConsId
            objGDCompensacao.UNID_ID = alngUnidId
            objGDCompensacao.ANOMES_FAT = Convert.ToInt32(Format(adteFatur, "yyyyMM"))

            dt = repositorioGDCompensacao.SelectCount(objGDCompensacao)

            If Convert.ToInt32(dt.Rows(0).ItemArray(0).ToString()) = 0 Then

                objGDCompensacao.CONSUMO_PONTA = adblconsumo_p
                objGDCompensacao.CONSUMO_FORAPONTA = adblconsumo_fp
                objGDCompensacao.COMPENSACAO_MES_PONTA = ldblReversokWhCompMes_Ponta
                objGDCompensacao.COMPENSACAO_MES_FORAPONTA = ldblReversokWhCompMes_ForaPonta

                If ldblGerado_Recebido = 1 Then
                    objGDCompensacao.INJETADO_PONTA = adblReverso_p
                    objGDCompensacao.INJETADO_FORAPONTA = adblReverso_fp
                Else
                    objGDCompensacao.RECEBIDO_TRANSFERENCIA = 0
                End If

                objGDCompensacao.TRANSFERENCIA_OUTRO = ldblReversokWhTranfOutro
                objGDCompensacao.SALDO_ATUAL = ldblReversokWhSaldoAtual
                objGDCompensacao.SALDO_ANTERIOR = ldblReversokWhSaldoAnterior

                objGDCompensacao.ZONA = astrZona
                objGDCompensacao.LIVRO = astrLivro
                objGDCompensacao.CONTA = astrConta
                objGDCompensacao.CONS_ID = alngConsId
                objGDCompensacao.UNID_ID = alngUnidId
                objGDCompensacao.DATA_LEITURA = adteLeitura
                objGDCompensacao.DATA_FATURAMENTO = adteFatur
                objGDCompensacao.ANOMES_FAT = Convert.ToInt32(Format(adteFatur, "yyyyMM"))

                repositorioGDCompensacao.Insert(objGDCompensacao)
            Else

                objGDCompensacao.CONSUMO_PONTA = adblconsumo_p
                objGDCompensacao.CONSUMO_FORAPONTA = adblconsumo_fp
                objGDCompensacao.COMPENSACAO_MES_PONTA = ldblReversokWhCompMes_Ponta
                objGDCompensacao.COMPENSACAO_MES_FORAPONTA = ldblReversokWhCompMes_ForaPonta

                If ldblGerado_Recebido = 1 Then
                    objGDCompensacao.INJETADO_PONTA = adblReverso_p
                    objGDCompensacao.INJETADO_FORAPONTA = adblReverso_fp
                Else
                    objGDCompensacao.RECEBIDO_TRANSFERENCIA = 0
                End If

                objGDCompensacao.SALDO_ANTERIOR = ldblReversokWhSaldoAnterior
                objGDCompensacao.TRANSFERENCIA_OUTRO = ldblReversokWhTranfOutro
                objGDCompensacao.SALDO_ATUAL = ldblReversokWhSaldoAtual
                objGDCompensacao.ZONA = astrZona
                objGDCompensacao.LIVRO = astrLivro
                objGDCompensacao.CONTA = astrConta
                objGDCompensacao.CONS_ID = alngConsId
                objGDCompensacao.UNID_ID = alngUnidId
                objGDCompensacao.ANOMES_FAT = Convert.ToInt32(Format(adteFatur, "yyyyMM"))

                repositorioGDCompensacao.Update(objGDCompensacao)

            End If


            objGDMovimentacao.ZONA = astrZona
            objGDMovimentacao.LIVRO = astrLivro
            objGDMovimentacao.CONTA = astrConta
            objGDMovimentacao.CONS_ID = alngConsId
            objGDMovimentacao.UNID_ID = alngUnidId
            objGDMovimentacao.CODIGO = 1
            objGDMovimentacao.ANOMES_FAT = Convert.ToInt32(Format(adteFatur, "yyyyMM"))

            dt = repositorioGDMovimentacao.SelectCount(objGDMovimentacao)

            If Convert.ToInt32(dt.Rows(0).ItemArray(0).ToString()) = 0 Then
                'If dt.Rows.Count <> 0 Then

                objGDMovimentacao.VALOR = (adblconsumo_p + adblconsumo_fp)
                objGDMovimentacao.ZONA = astrZona
                objGDMovimentacao.LIVRO = astrLivro
                objGDMovimentacao.CONTA = astrConta
                objGDMovimentacao.CONS_ID = alngConsId
                objGDMovimentacao.UNID_ID = alngUnidId
                objGDMovimentacao.CODIGO = 1
                If ldblGerado_Recebido = 1 Then
                    objGDMovimentacao.DESCRICAO = "GERAÇÃO"
                Else
                    objGDMovimentacao.DESCRICAO = "RECEBIDO"
                End If

                objGDMovimentacao.ANOMES = Convert.ToInt32(Format(adteFatur, "yyyyMM"))
                objGDMovimentacao.ANOMES_FAT = Convert.ToInt32(Format(adteFatur, "yyyyMM"))

                repositorioGDMovimentacao.Insert(objGDMovimentacao)

            Else

                objGDMovimentacao.VALOR = (adblconsumo_p + adblconsumo_fp)
                objGDMovimentacao.ZONA = astrZona
                objGDMovimentacao.LIVRO = astrLivro
                objGDMovimentacao.CONTA = astrConta
                objGDMovimentacao.CONS_ID = alngConsId
                objGDMovimentacao.UNID_ID = alngUnidId
                objGDMovimentacao.CODIGO = 1
                objGDMovimentacao.ANOMES_FAT = Convert.ToInt32(Format(adteFatur, "yyyyMM"))

                repositorioGDMovimentacao.Update(objGDMovimentacao)
            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Public Function SaldoAnteriorGD(ByVal alngConsId As Long, ByVal alngUnidId As Long, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrFatur As String) As Double

        Dim result As Double = 0
        Dim ldblRet As Double = 0

        Dim objGDCompensacao As New entidadeGDCompensacao
        Dim repositorioGDCompensacao As New repositorioGDCompensacao

        Dim vlist As Object

        Try

            objGDCompensacao.ZONA = astrZona
            objGDCompensacao.LIVRO = astrLivro
            objGDCompensacao.CONTA = astrConta
            objGDCompensacao.CONS_ID = alngConsId
            objGDCompensacao.UNID_ID = alngUnidId
            If Mid(astrFatur, 5, 2) = "01" Then
                astrFatur = Mid(astrFatur, 1, 4) - 1 & 12
                objGDCompensacao.ANOMES_FAT = astrFatur
            Else
                objGDCompensacao.ANOMES_FAT = astrFatur - 1
            End If

            vlist = repositorioGDCompensacao.Select(objGDCompensacao)

            If vlist.Count > 0 Then
                For Each objGDCompensacaoFor As entidadeGDCompensacao In vlist
                    ldblRet = Trim(IIf(IsDBNull(objGDCompensacaoFor.SALDO_ATUAL), 0, objGDCompensacaoFor.SALDO_ATUAL))
                Next
            End If

            result = ldblRet

        Catch ex As Exception
            result = 0
        End Try


        SaldoAnteriorGD = result

    End Function

    Private Sub Calc_HoroSazonal()

        'Dados Cadastrais do Consumidor
        Dim strIsentIlum As String
        Dim isento_demanda As String
        Dim lblnIcms_Demada_Lida As Boolean
        Dim lblnFlagSazonal As Boolean
        Dim lstrZona As String
        Dim lstrLivro As String
        Dim lstrConta As String
        Dim lintConsId As Integer
        Dim lintUnidId As Integer
        Dim lstrUf As String
        Dim llngCodigoCidade As Integer
        Dim lstrCidade As String
        '
        Dim ldblDemandaContratadaPonta As Double
        Dim ldblDemandaContratadaForaPonta As Double
        Dim ldblDemandaAnteriorContratadaPonta As Double
        Dim ldblDemandaAnteriorContratadaForaPonta As Double
        Dim ldblDemandaAtualContratadaPonta As Double
        Dim ldblDemandaAtualContratadaForaPonta As Double
        '
        Dim Constante_Consumo_P As Double
        Dim Constante_Consumo_FP As Double
        Dim Constante_Demanda_P As Double
        Dim Constante_Demanda_FP As Double
        Dim Constante_Kvarh_P As Double
        Dim Constante_Kvarh_FP As Double
        Dim ldblPerdas As Double
        Dim strMesRefMulta As String
        Dim TpConsumo As String
        Dim TpFaixaC As String
        Dim lblnCobrarReativo As Boolean
        Dim lblnReativoNegativo As Boolean
        Dim leitura_reativo As Short
        Dim ldblParCatMWhMedio As Double
        Dim ldblParCatHoras As Double
        Dim ldblParCatConsumoTotal As Double
        Dim ldblParCatConsumoPonta As Double
        Dim ldblParCatConsumoFPonta As Double
        Dim ldblParCatVlrkWhPonta As Double
        Dim ldblParCatVlrkWhFPonta As Double
        Dim ldblParCatPerPonta As Double
        Dim ldblParCatPerFPonta As Double
        '
        Dim row_grid As Short
        Dim dtDataRefMulta As Date
        Dim dtDataFat As Date
        Dim auxdemanda As Double
        Dim auxDemandaReativa As Double
        '
        Dim consumo_p As Double
        Dim vlrConsumo_P As Double
        Dim vlrConsumo_P_Tusd As Double
        Dim vlrConsumo_P_te As Double
        Dim vlrConsumoBan_P As Double
        Dim vlrConsumo_Sefaz_P As Double
        Dim vlrConsumoBan_Sefaz_P As Double
        '
        Dim consumo_fp As Double
        Dim vlrConsumo_FP As Double
        Dim vlrConsumo_FP_tusd As Double
        Dim vlrConsumo_FP_te As Double
        Dim vlrConsumoBan_FP As Double
        Dim vlrConsumo_Sefaz_FP As Double
        Dim vlrConsumoBan_Sefaz_FP As Double
        'Micro Geração
        Dim reverso_p As Double
        Dim vlrReverso_P As Double
        Dim vlrReverso_Ponta As Double
        Dim reverso_fp As Double
        Dim vlrReverso_FP As Double
        Dim vlrReverso_ForaPonta As Double
        Dim reverso_res_p As Double
        Dim reverso_res_fp As Double
        Dim reverso_Saldo_p As Double
        Dim reverso_Saldo_fp As Double
        Dim micro_geracao As Double
        Dim grupo_GD As Integer
        Dim porcen_desconto_GD As Double
        Dim cod_tarifa As String
        Dim ldblReversokWhSaldoAnterior As Double
        '
        Dim vlrTotal As Double
        Dim vlrIsentoIcms As Double
        Dim vlrLiqui As Double
        Dim vlrPis As Double
        Dim vlrCofins As Double
        '  Dim basePisCofins               As Double
        'demanda lida
        Dim Demanda_Lida_P As Double
        Dim Demanda_Lida_FP As Double
        'demanda faturada (que sempre será o valor calculado em cima da demanda lida
        Dim Demanda_Faturada_P As Double
        Dim vlrDemanda_P As Double
        Dim Demanda_Faturada_FP As Double
        Dim vlrDemanda_FP As Double
        'Demanda de ultrapassagem
        Dim Dem_Ultrapassagem_P As Double
        Dim vlrDem_Ultrapassagem_P As Double
        Dim Dem_Ultrapassagem_FP As Double
        Dim vlrDem_Ultrapassagem_FP As Double
        'Novas variaveis para calcular a diferença da demanda lida contra o contrato quando a lida for menor que o contrato
        'pois não se tributa mais em cima da demanda contratada
        Dim qtd_Demanda_Dif_Cont_P As Double
        Dim vlr_Demanda_Dif_Cont_P As Double
        Dim qtd_Demanda_Dif_Cont_FP As Double
        Dim vlr_Demanda_Dif_Cont_FP As Double
        '
        Dim BaseConsumo_Reativo As Double
        Dim Kvarh_P As Double
        Dim vlrKvarh_Consumo_p As Double
        Dim vlrBaseConsumo_Reativo As Double
        Dim leitConsumo_aux As Double
        Dim Kvarh_fp As Double
        Dim vlrKvarh_Demanda_fp As Double
        Dim lstrDescKVarh_demanda_fp As String
        Dim vlrKvarh_Consumo_fp As Double
        '
        Dim vlrKvarh_Demanda_p As Double
        Dim lstrDescKVarh_demanda_p As String
        Dim BaseDemanda_Reativa As Double
        Dim Base_Demanda_Reativa_p As Double
        Dim Base_Demanda_Reativa_fp As Double
        '
        Dim leitura_maxima As Double
        Dim Ilum As Double
        Dim vlr_ajuste_demanda_p As Double
        Dim vlr_ajuste_demanda_fp As Double
        Dim ldbl_Reativo_Aux As Double
        Dim vlrConsumoReativoCapacitivo As Double
        Dim fator_potencia As Double
        Dim vlrqh As Double
        'Dim base_retencao    As Double
        Dim coefTribIcms As Double
        Dim coefTribSIcms As Double
        Dim vlrConsumoPT As Double
        Dim vlrConsumoPTBan As Double
        Dim vlrConsumoFPT As Double
        Dim vlrConsumoFPTBan As Double
        Dim vlrDemandaPT As Double
        Dim vlrDemandaFPT As Double
        Dim vlrDemUltraPT As Double
        Dim vlrDemUltraFPT As Double
        Dim vlrConsReatPT As Double
        Dim vlrConsReatFPT As Double
        Dim vlrDemReatPT As Double
        Dim vlrDemReatFPT As Double
        Dim dblDemReatAux As Double
        Dim vlrConsCapFPT As Double
        Dim baseIcmsAux As Double
        Dim baseICMSisenta As Double
        Dim baseRetCons As Double
        Dim baseRetDem As Double
        Dim retPis As Double
        Dim retCofins As Double
        Dim retCsll As Double
        Dim retIRCons As Double
        Dim retIRDem As Double
        Dim vlrRetPis As Double
        Dim vlrRetCofins As Double
        Dim vlrRetCsll As Double
        Dim vlrRetIRCons As Double
        Dim vlrRetIRDem As Double
        Dim consTotal As Double
        'Dim leitAtual        As Double
        '
        Dim ldblDemaAuxP As Double
        Dim ldblDemaAuxFP As Double
        '
        Dim lstrPercDemU As String
        Dim ldblPercDemUP As Double
        Dim ldblPercDemUFP As Double
        '
        Dim ldbl_Ajuste_Vlr_Trib_P As Double
        Dim ldbl_Ajuste_Vlr_Trib_C As Double
        Dim ldbl_Ajuste_Vlr_Trib As Double
        '  Dim ldbl_Ajuste_Base_PisCof As Double
        '  Dim ldbl_Ajuste_Base_ICMS As Double
        Dim lstr_Referencia_Item As String
        Dim ldbl_Quantidade_Item As Double
        Dim lstr_Descricao_Item As String
        '
        Dim lstr_Referencia_Item_tusd As String
        Dim lstr_Referencia_Item_te As String
        '
        Dim ldbl_Per_Des_SP As Double
        Dim lint_Aux_Trib As Short
        '
        Dim lbln_Continua As Boolean
        Dim lstr_Msg_Continua As String
        '
        Dim ldblTotalVrlItens As Double

        Dim lbdCompensacao_Perda As Double = "1,025"

        Dim lstrSql As String

        Dim dt, dt1 As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Try
            'Monta_Codigos_Inviduais_Tributacao - para serem usado na gravacao dos itens tributados
            For lint_Aux_Trib = LBound(istr_Bas_Icm) To UBound(istr_Bas_Icm)

                istr_Bas_Icm(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "BASE", "ICMS")
                istr_Bas_Pis(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "BASE", "PIS")
                istr_Bas_Cof(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "BASE", "COFINS")
                istr_Vlr_Icm(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "TRIBUTO", "ICMS")
                istr_Vlr_Pis(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "TRIBUTO", "PIS")
                istr_Vlr_Cof(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "TRIBUTO", "COFINS")
                istr_Ite_Icm(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "VALOR", "ICMS")
                istr_Ite_Pis(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "VALOR", "PIS")
                istr_Ite_Cof(lint_Aux_Trib) = Monta_Codigos_Inviduais_Tributacao(lint_Aux_Trib, "VALOR", "COFINS")
                '
                'Inicializa tudo com zero
                idbl_Ite_Pic(lint_Aux_Trib) = 0
                idbl_Ite_Icm(lint_Aux_Trib) = 0
                idbl_Bas_Icm(lint_Aux_Trib) = 0
                idbl_Bas_Pic(lint_Aux_Trib) = 0
                idbl_Vlr_Pis(lint_Aux_Trib) = 0
                idbl_Vlr_Cof(lint_Aux_Trib) = 0
                idbl_Vlr_Icm(lint_Aux_Trib) = 0
                idbl_Ret_Con(lint_Aux_Trib) = 0
                idbl_Ret_Dem(lint_Aux_Trib) = 0

            Next

            idblBasePisCofins = 0

            'Percentual de controle de ultrapassagem de demanda
            MontaPercentual_demanda()
            lstrPercDemU = Trim(GetConfig("grupoa.percentual.kw_ultra.p"))
            ldblPercDemUP = CDbl(IIf(IsNumeric(lstrPercDemU), lstrPercDemU, 5))
            lstrPercDemU = Trim(GetConfig("grupoa.percentual.kw.ultra.fp"))
            ldblPercDemUFP = CDbl(IIf(IsNumeric(lstrPercDemU), lstrPercDemU, 5))
            '
            Inicializa_Campos_Text_Para_Evitar_Branco()
            '
            Item_Fatura = ""
            lstr_Msg_Continua = ""

            vResp = MessageBox.Show("Deseja cobrar consumo e demanda reativos?", "Informação", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

            If vResp = DialogResult.Yes Then
                lblnCobrarReativo = True
            Else
                lblnCobrarReativo = False
            End If

            lstrSql = "SELECT * " & "  FROM `uc_faturamento` " & " WHERE zona  = '" & Me.txtZona.Text & "' " & "   AND livro = '" & Me.txtLivro.Text & "' " & "   AND conta = '" & Me.txtConta.Text & "';"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrZona = IIf(IsDBNull(row("zona")), "", row("zona"))

                    lstrLivro = IIf(IsDBNull(row("livro")), "", row("livro"))

                    lstrConta = IIf(IsDBNull(row("conta")), "", row("conta"))

                    lintConsId = IIf(IsDBNull(row("cons_id")), 0, row("cons_id"))

                    lintUnidId = IIf(IsDBNull(row("id")), 0, row("id"))

                    istrInsEst = IIf(IsDBNull(row("insc")), "", row("insc"))

                    ldblPerdas = IIf(IsDBNull(row("final")), 0, row("final"))

                    lstrCidade = Trim(IIf(IsDBNull(row("codcidade")), "", row("codcidade")))

                    lstrUf = Trim(IIf(IsDBNull(row("uf")), "", row("uf")))

                    iblnParCativo = (CShort(IIf(IsDBNull(row("parcialmente_cativo")), 0, row("parcialmente_cativo"))) = 1)

                    iblnPeriodoTeste = (CShort(IIf(IsDBNull(row("periodo_teste")), 0, row("periodo_teste"))) = 1)

                    idteIniPeriodoTeste = IIf(IsDBNull(row("ini_periodo_teste")), "01/01/1900", row("ini_periodo_teste"))

                    idteFimPeriodoTeste = IIf(IsDBNull(row("fim_periodo_teste")), "01/01/1900", row("fim_periodo_teste"))

                    iintLivreEspecial = CShort(IIf(IsDBNull(row("livreespecial")), 0, row("livreespecial")))

                    iintLivreVerde = IIf(IsDBNull(row("livre_verde")), 0, row("livre_verde"))

                    iintLivreLeituraConsumo = CShort(IIf(IsDBNull(row("livre_leitura_consumo")), 0, row("livre_leitura_consumo")))

                    istrClasse = VB6.Format(Trim(IIf(IsDBNull(row("clas")), "0000", row("clas"))), "0000")

                    ldblDemandaContratadaPonta = IIf(IsDBNull(row("dem_contr_ponta")), 0, row("dem_contr_ponta"))

                    ldblDemandaContratadaForaPonta = IIf(IsDBNull(row("dem_contr_fp")), 0, row("dem_contr_fp"))
                    ldblDemandaAtualContratadaPonta = ldblDemandaContratadaPonta
                    ldblDemandaAtualContratadaForaPonta = ldblDemandaContratadaForaPonta

                    ldblDemandaAnteriorContratadaPonta = IIf(IsDBNull(row("dem_contr_ponta_anterior")), 0, row("dem_contr_ponta_anterior"))

                    ldblDemandaAnteriorContratadaForaPonta = IIf(IsDBNull(row("dem_contr_fp_anterior")), 0, row("dem_contr_fp_anterior"))
                    '
                    lbln_Continua = True

                    'ldblReversokWhSaldoAnterior = SaldoAnteriorGD(lintConsId, lintUnidId, lstrZona, lstrLivro, lstrConta, VB6.Format(txtMesAno.Text, "yyyyMM"))
                    'reverso_res_fp = ldblReversokWhSaldoAnterior
                    reverso_res_p = IIf(IsNumeric(Me.txtReverso_Residuo_p.Text), Me.txtReverso_Residuo_p.Text, 0)
                    reverso_res_fp = IIf(IsNumeric(Me.txtReverso_Residuo_fp.Text), Me.txtReverso_Residuo_fp.Text, 0)

                    If iblnPeriodoTeste Then
                        lbln_Continua = Valida_Periodo_Teste(idteIniPeriodoTeste, idteFimPeriodoTeste, ldblDemandaAnteriorContratadaPonta, ldblDemandaAnteriorContratadaForaPonta, ldblDemandaAtualContratadaPonta, ldblDemandaAtualContratadaForaPonta)
                        If Not lbln_Continua Then lstr_Msg_Continua = "Este consumidor possui problema nos dados de demanda do período de teste!" & vbCrLf & "Revise o cadastro da unidade consumidora!"
                    End If
                    '
                    If iblnPeriodoTeste And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) >= VB6.Format(idteIniPeriodoTeste, "yyyyMM") And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) <= VB6.Format(idteFimPeriodoTeste, "yyyyMM") And ldblDemandaAtualContratadaPonta <> ldblDemandaAnteriorContratadaPonta Then
                        ldblDemandaContratadaPonta = ldblDemandaAnteriorContratadaPonta
                    End If
                    If iblnPeriodoTeste And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) >= VB6.Format(idteIniPeriodoTeste, "yyyyMM") And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) <= VB6.Format(idteFimPeriodoTeste, "yyyyMM") And ldblDemandaAtualContratadaForaPonta <> ldblDemandaAnteriorContratadaForaPonta Then
                        ldblDemandaContratadaForaPonta = ldblDemandaAnteriorContratadaForaPonta
                    End If

                    'Constante_Consumo_P = IIf(IsNull(row("const_cons_p")), 0, row("const_cons_p"))
                    'Constante_Consumo_FP = IIf(IsNull(row("const_cons_fp")), 0, row("const_cons_fp"))
                    'Constante_Demanda_P = IIf(IsNull(row("const_demanda")), 0, row("const_demanda"))
                    'Constante_Demanda_FP = IIf(IsNull(row("const_demanda_fp")), 0, row("const_demanda_fp"))
                    'Constante_Kvarh_P = IIf(IsNull(row("const_kvarh_p")), 0, row("const_kvarh_p"))
                    'Constante_Kvarh_FP = IIf(IsNull(row("const_kvarh_fp")), 0, row("const_kvarh_fp"))

                    Constante_Consumo_P = CDbl(VB6.Format(IIf(IsDBNull(row("const_kwh_p")), 0, row("const_kwh_p")), "#,#####0.00000"))

                    Constante_Consumo_FP = CDbl(VB6.Format(IIf(IsDBNull(row("const_kwh_fp")), 0, row("const_kwh_fp")), "#,#####0.00000"))

                    Constante_Demanda_P = CDbl(VB6.Format(IIf(IsDBNull(row("const_kw_p")), 0, row("const_kw_p")), "#,#####0.00000"))

                    Constante_Demanda_FP = CDbl(VB6.Format(IIf(IsDBNull(row("const_kw_fp")), 0, row("const_kw_fp")), "#,#####0.00000"))

                    Constante_Kvarh_P = CDbl(VB6.Format(IIf(IsDBNull(row("const_kvarh_p")), 0, row("const_kvarh_p")), "#,#####0.00000"))

                    Constante_Kvarh_FP = CDbl(VB6.Format(IIf(IsDBNull(row("const_kvarh_fp")), 0, row("const_kvarh_fp")), "#,#####0.00000"))
                    '
                    leitura_maxima = IIf(IsDBNull(row("maior")), 0, row("maior"))

                    lblnFlagSazonal = IIf(IsDBNull(row("flg_sazonal")), "N", row("flg_sazonal")) = "S"

                    idteContratoDemanda = IIf(IsDBNull(row("data_contrato_demanda")), "1951-01-01", row("data_contrato_demanda"))
                    '
                    isento_demanda = UCase(Trim(IIf(IsDBNull(row("icms_isento_demanda")), "N", row("icms_isento_demanda"))))

                    lblnIcms_Demada_Lida = IIf(IsDBNull(row("icms_demanda_lida")), "N", row("icms_demanda_lida")) = "S"

                    strIsentIlum = UCase(IIf(IsDBNull(row("ilum")), "N", row("ilum")))

                    leitura_reativo = IIf(IsDBNull(row("leitreativo")), 0, row("leitreativo"))
                    '
                    ccee_titul_anterior = IIf(IsDBNull(row("ccee_titul_anterior")), "", row("ccee_titul_anterior"))

                    micro_geracao = IIf(IsDBNull(row("micro_geracao")), 0, row("micro_geracao"))

                Next

            End If

            If lbln_Continua Then

                '* Busca o código da cidade de acordo com o nome da cidade que esta nos dados da unidade consumidora.           *
                'llngCodigoCidade = CInt(GetValorTabela("`munic`", "cod", "`cod` LIKE '%" & Replace(lstrCidade, "'", "\'") & "%' ", "0"))
                'Municipio
                lstrSql = "SELECT * " & "  FROM `munic` " & " WHERE cod LIKE ""%" & lstrCidade & "%"" " & " LIMIT 1 "
                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                If dt.Rows.Count <> 0 Then

                    For Each row As DataRow In dt.Rows
                        llngCodigoCidade = IIf(IsDBNull(row("cod")), 0, row("cod"))
                    Next
                Else
                    MessageBox.Show("Atenção! O município " & lstrCidade & " não está cadastrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If

                If llngCodigoCidade = 0 Then
                    llngCodigoCidade = lstrCidade
                End If

                'Carrega as tarifas nas variáveis instanciadas
                TarifaHorosazonal(iblnParCativo)
                Carr_Leit_Anterior(idteContratoDemanda, ldblDemandaContratadaPonta, ldblDemandaContratadaForaPonta)

                'leituras anteriores e atuais
                'Consumo
                Item_Fatura = Trim(Item_Fatura & "0302040007?" & Replace(CStr(ant_consumo_p), ",", ".") & ";") 'consumo ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040008?" & Replace(Replace(txtConsumo_p.Text, ".", ""), ",", ".") & ";") 'consumo ponta atual
                Item_Fatura = Trim(Item_Fatura & "0302040009?" & Replace(CStr(ant_consumo_fp), ",", ".") & ";") 'consumo f ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040010?" & Replace(Replace(txtConsumo_FP.Text, ".", ""), ",", ".") & ";") 'consumo f ponta atual
                'Demanda
                Item_Fatura = Trim(Item_Fatura & "0302040011?" & Replace(CStr(ant_demanda_p), ",", ".") & ";") 'demanda ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040012?" & Replace(Replace(txtDemanda_p.Text, ".", ""), ",", ".") & ";") 'demanda ponta atual
                Item_Fatura = Trim(Item_Fatura & "0302040013?" & Replace(CStr(ant_demanda_fp), ",", ".") & ";") 'demanda f ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040014?" & Replace(Replace(txtDemanda_FP.Text, ".", ""), ",", ".") & ";") 'demanda f ponta atual
                'Reativo
                Item_Fatura = Trim(Item_Fatura & "0302040015?" & Replace(CStr(ant_kvarh), ",", ".") & ";") 'reativo ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040016?" & Replace(Replace(txtKvarh_P.Text, ".", ""), ",", ".") & ";") 'reativo ponta atual
                Item_Fatura = Trim(Item_Fatura & "0302040017?" & Replace(CStr(ant_kvarh_fp), ",", ".") & ";") 'reativo f ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040018?" & Replace(Replace(txtKvarh_FP.Text, ".", ""), ",", ".") & ";") 'reativo f ponta atual
                '
                'Micro Geração
                Item_Fatura = Trim(Item_Fatura & "0302040021?" & Replace(CStr(ant_reverso_p), ",", ".") & ";") 'reverso ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040022?" & Replace(Replace(txtReverso_p.Text, ".", ""), ",", ".") & ";") 'reverso ponta atual
                Item_Fatura = Trim(Item_Fatura & "0302040023?" & Replace(CStr(ant_reverso_fp), ",", ".") & ";") 'reverso f ponta anterior
                Item_Fatura = Trim(Item_Fatura & "0302040024?" & Replace(Replace(txtReverso_fp.Text, ".", ""), ",", ".") & ";") 'reverso f ponta atual
                '
                'MWh Médio/Horas ' Implementado em 04/06/2014
                Item_Fatura = Trim(Item_Fatura & "0302040030?" & Replace(Replace(IIf(Len(Trim(Me.txtParCatMWhMedio.Text)) = 0, 0, Me.txtParCatMWhMedio.Text), ".", ""), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0302040031?" & Replace(Replace(IIf(Len(Trim(Me.txtParCatHoras.Text)) = 0, 0, txtParCatHoras.Text), ".", ""), ",", ".") & ";")
                ldblParCatMWhMedio = CDbl(Me.txtParCatMWhMedio.Text)
                ldblParCatHoras = CDbl(Me.txtParCatHoras.Text)
                '
                idblAliqICMS = Busca_Aliquota_ICMS(lstrUf, 0, istrClasse)
                '
                If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 5 And lstrUf <> "GO" And lstrUf <> "RS" And Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) <> "01AX" Then
                    '-- Aplica desconto de 10% para tarifas rurais
                    idblTarConsumo_p = Arredondar(idblTarConsumo_p * 0.9, 5)
                    idblTarConsumo_fp = Arredondar(idblTarConsumo_fp * 0.9, 5)
                    idblTarDemanda_p = Arredondar(idblTarDemanda_p * 0.9, 5)
                    idblTarDemanda_fp = Arredondar(idblTarDemanda_fp * 0.9, 5)
                    idblTarDemUltra_p = Arredondar(idblTarDemUltra_p * 0.9, 5)
                    idblTarDemUltra_fp = Arredondar(idblTarDemUltra_fp * 0.9, 5)
                End If
                '
                coefTribIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCofins / 100)) / (1 - (idblAliqICMS / 100))), 11)

                If gstrEmpresa_Sigla = "CERIS" Then
                    coefTribSIcms = Truncate(1 - (idblAliqPIS + idblAliqCofins + idblAliqICMS) / 100, 5)
                Else
                    coefTribSIcms = Truncate(1 - ((idblAliqPIS / 100) + (idblAliqCofins / 100)), 11)
                End If
                '
                vlrPis = 0
                vlrCofins = 0
                vlrTotal = 0
                vlrLiqui = 0
                BaseICMS = 0
                baseIcmsAux = 0
                baseICMSisenta = 0

                grid_fatura.Redraw = False
                '
                'Virada de Medidor - consumo na ponta
                consumo_p = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtConsumo_p.Text), Me.txtConsumo_p.Text, 0)), ant_consumo_p)
                If Constante_Consumo_P > 0 Then
                    consumo_p = consumo_p * Constante_Consumo_P
                End If

                If ldblPerdas > 0 Then
                    'consumo_p = consumo_p + (consumo_p * (ldblPerdas / 100))
                    'consumo_p = Math.Round(((consumo_p * ldblPerdas) + consumo_p), 0)
                    consumo_p = ((consumo_p * ldblPerdas) + consumo_p)
                Else
                    consumo_p = consumo_p
                End If
                '
                'Virada de Medidor - Reverso na ponta
                reverso_p = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtReverso_p.Text), Me.txtReverso_p.Text, 0)), ant_reverso_p)
                If Constante_Consumo_P > 0 Then
                    reverso_p = reverso_p * Constante_Consumo_P
                End If
                '
                'Virada de Medidor - consumo fora de ponta
                consumo_fp = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtConsumo_FP.Text), Me.txtConsumo_FP.Text, 0)), ant_consumo_fp)
                If Constante_Consumo_FP > 0 Then
                    consumo_fp = consumo_fp * Constante_Consumo_FP
                End If

                If ldblPerdas > 0 Then
                    'consumo_fp = consumo_fp + (consumo_fp * (ldblPerdas / 100))
                    consumo_fp = ((consumo_fp * ldblPerdas) + consumo_fp)
                Else
                    consumo_fp = consumo_fp
                End If
                '
                'Virada de medidor - Reverso na fora ponta
                reverso_fp = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtReverso_fp.Text), Me.txtReverso_fp.Text, 0)), ant_reverso_fp)
                If Constante_Consumo_FP > 0 Then
                    reverso_fp = reverso_fp * Constante_Consumo_FP
                End If
                If ldblPerdas > 0 Then
                    reverso_fp = (reverso_fp - (reverso_fp * ldblPerdas))
                End If
                '
                'consTotal = consumo_p + consumo_fp
                If consTotal > (reverso_p + reverso_res_p) Then
                        consTotal = consTotal - (reverso_p - reverso_res_p)
                    Else
                        consTotal = 0
                    End If

                    If consTotal > (reverso_fp + reverso_res_fp) Then
                        consTotal = consTotal - (reverso_fp + reverso_res_fp)
                    Else
                        consTotal = 0
                    End If
                    '
                    'Parcialmente Cativo - Recalculo para achar o kwh consumido com base no percentual de horas contratada
                    If iblnParCativo Then
                        ldblParCatPerPonta = consumo_p / (consumo_p + consumo_fp)
                        ldblParCatPerFPonta = 1 - ldblParCatPerPonta
                        ldblParCatConsumoTotal = (ldblParCatMWhMedio * ldblParCatHoras) * 1000
                        ldblParCatConsumoPonta = Arredondar(ldblParCatConsumoTotal * ldblParCatPerPonta, 2)
                        ldblParCatConsumoFPonta = ldblParCatConsumoTotal - ldblParCatConsumoPonta
                    End If
                '
                If CDbl(IIf(IsNumeric(Me.txtConsumo_p.Text), Me.txtConsumo_p.Text, 0)) > 0 Then 'Val(Replace(Me.txtConsumo_p.Text, ",", ".")) > 0 Then
                    If iblnParCativo Then
                        vlrConsumo_P = Truncate(ldblParCatConsumoPonta * idblTarConsumo_p, 2)
                        ldblParCatVlrkWhPonta = Truncate((consumo_p - ldblParCatConsumoPonta) * idblTarConsumoLiv_p, 2)
                        vlrConsumo_Sefaz_P = vlrConsumo_P
                    Else
                        vlrConsumo_P = Truncate(IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0) * idblTarConsumo_p, 2)
                        If (reverso_p + reverso_res_p) <= consumo_p Then
                            vlrReverso_P = Truncate(consumo_p * idblTarConsumo_p, 2) - (Truncate((reverso_p + reverso_res_p) * idblTarConsumo_p, 2))
                        End If
                        If Not iblnMicroGeracaoConvenioSefaz Then
                            vlrConsumo_Sefaz_P = Truncate(consumo_p * idblTarConsumo_p, 2)
                        Else
                            vlrConsumo_Sefaz_P = vlrConsumo_P
                        End If
                    End If
                    '
                    'Consumo Ponta
                    If vlrConsumo_P > 0 Then
                        If iblnParCativo Then
                            lstr_Referencia_Item = "( " & Truncate(ldblParCatConsumoPonta, 6) & " x " & Arredondar(idblTarConsumo_p, 5) & " )"
                            ldbl_Quantidade_Item = ldblParCatConsumoPonta
                        Else
                            If micro_geracao = 0 Then
                                lstr_Referencia_Item = "( " & Truncate(IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0), 6) & " x " & Arredondar(idblTarConsumo_p, 5) & " )"
                                ldbl_Quantidade_Item = IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0)
                                AdicionaGridItem(row_grid, "0302020010", Trim(codTodescri(IIf(iblnParCativo, "0302020010", IIf(Me.txtTA.Text = "01AL00", "0302020060", "0302020010")))), ldbl_Quantidade_Item, vlrConsumo_P, lstr_Referencia_Item, "S")
                            Else

                                'vlrConsumo_P_Tusd = Truncate(IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0) * idblTarConsumo_p_tusd, 2)
                                'vlrConsumo_P_te = Truncate(IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0) * idblTarConsumo_p_te, 2)
                                vlrConsumo_P_Tusd = Truncate((consumo_p * idblTarConsumo_p_tusd), 2)
                                vlrConsumo_P_te = Truncate((consumo_p * idblTarConsumo_p_te), 2)

                                vlrConsumo_P = vlrConsumo_P_Tusd + vlrConsumo_P_te

                                Item_Fatura = Trim(Item_Fatura & "0302020010?" & Replace(CStr(vlrConsumo_P), ",", ".") & "$;") 'Consumo Ponta

                                'GD - TUSD
                                lstr_Referencia_Item = "( " & Truncate(consumo_p, 6) & " x " & Arredondar(idblTarConsumo_p_tusd, 5) & " )"
                                ldbl_Quantidade_Item = consumo_p
                                AdicionaGridItem(row_grid, "0303020091", Trim(codTodescri("0303020091")), ldbl_Quantidade_Item, vlrConsumo_P_Tusd, lstr_Referencia_Item, "S")
                                Item_Fatura = Trim(Item_Fatura & "0303010091?" & ldbl_Quantidade_Item & ";") 'TUSD ponta

                                'GD - TE
                                lstr_Referencia_Item = "( " & Truncate(consumo_p, 6) & " x " & Arredondar(idblTarConsumo_p_te, 5) & " )"
                                ldbl_Quantidade_Item = consumo_p
                                AdicionaGridItem(row_grid, "0304020091", Trim(codTodescri("0304020091")), ldbl_Quantidade_Item, vlrConsumo_P_te, lstr_Referencia_Item, "S")
                                Item_Fatura = Trim(Item_Fatura & "0304010091?" & ldbl_Quantidade_Item & ";") 'TE ponta

                            End If
                        End If
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrConsumo_P

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(0) = Arredondar(IIf(iblnMicroGeracaoConvenioSefaz, vlrConsumo_P, vlrConsumo_Sefaz_P) * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(0) = idbl_Ite_Pic(0)
                        '
                        idbl_Bas_Pic(0) = Arredondar(idbl_Ite_Pic(0) / coefTribSIcms, 2)
                        idbl_Bas_Icm(0) = Arredondar(idbl_Bas_Pic(0) / (1 - (idblAliqICMS / 100)), 2)

                        idbl_Vlr_Pis(0) = Arredondar(idbl_Bas_Pic(0) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(0) = Arredondar(idbl_Bas_Pic(0) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(0) = Arredondar(idbl_Bas_Icm(0) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(0) = idbl_Bas_Icm(0)
                        idbl_Ret_Dem(0) = 0
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumo_P
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010010?" & Replace(CStr(consumo_p), ",", ".") & "$;") 'Consumo Ponta
                        Item_Fatura = Trim(Item_Fatura & "0302012010?" & Replace(CStr(reverso_p), ",", ".") & "$;") 'Reverso Ponta
                        Item_Fatura = Trim(Item_Fatura & "0302013010?" & Replace(CStr(reverso_res_p), ",", ".") & "$;") 'Resíduo de Reverso Ponta
                        '
                        'Modificado para usar o reverso utilizado - ricardo 01/12/2019
                        vlrReverso_Ponta = 0
                        If (reverso_p + reverso_res_p) > 0 Then
                            If (reverso_p + reverso_res_p) <= consumo_p Then
                                vlrReverso_Ponta = Arredondar((reverso_p + reverso_res_p) * idblTarConsumo_p, 2)
                            Else
                                vlrReverso_Ponta = Arredondar(consumo_p * idblTarConsumo_p, 2)
                            End If
                        End If
                        Item_Fatura = Trim(Item_Fatura & "0302022010?" & Replace(CStr(vlrReverso_Ponta), ",", ".") & "$;") 'Valor Reverso Ponta
                    End If 'vlrConsumo_P > 0
                End If
                '
                'Bandeira Ponta
                If CDbl(IIf(IsNumeric(Me.txtConsumo_p.Text), Me.txtConsumo_p.Text, 0)) > 0 Then 'Val(Replace(txtConsumo_p.Text, ",", ".")) > 0 Then
                    If iblnParCativo Then
                        vlrConsumoBan_P = Truncate(ldblParCatConsumoPonta * (idblTarConsumoBan_p - idblTarConsumoSemDesconto_p), 2)
                        vlrConsumoBan_Sefaz_P = vlrConsumoBan_P
                    Else
                        vlrConsumoBan_P = Truncate(IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0) * (idblTarConsumoBan_p - idblTarConsumoSemDesconto_p), 2)
                        If (reverso_p + reverso_res_p) <= consumo_p Then
                            vlrReverso_P = vlrReverso_P + Truncate(consumo_p * idblTarConsumoBan_p, 2) - Truncate((reverso_p + reverso_res_p) * idblTarConsumoBan_p, 2)
                        End If
                        If Not iblnMicroGeracaoConvenioSefaz Then
                            vlrConsumoBan_Sefaz_P = Truncate(consumo_p * (idblTarConsumoBan_p - idblTarConsumoSemDesconto_p), 2)
                        Else
                            vlrConsumoBan_Sefaz_P = vlrConsumoBan_P
                        End If
                    End If
                    '
                    'Bandeira Ponta
                    If vlrConsumoBan_P > 0 Then
                        If iblnParCativo Then
                            lstr_Referencia_Item = "( " & Truncate(ldblParCatConsumoPonta, 6) & " x " & Arredondar(idblTarConsumoBan_p - idblTarConsumoSemDesconto_p, 5) & " )"
                            ldbl_Quantidade_Item = ldblParCatConsumoPonta
                        Else
                            lstr_Referencia_Item = "( " & Truncate(IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0), 6) & " x " & Arredondar(idblTarConsumoBan_p - idblTarConsumoSemDesconto_p, 5) & " )"
                            ldbl_Quantidade_Item = IIf((reverso_p + reverso_res_p) <= consumo_p, (consumo_p - (reverso_p + reverso_res_p)), 0)
                        End If
                        AdicionaGridItem(row_grid, "0302120010", Trim(codTodescri("0302120010")), ldbl_Quantidade_Item, vlrConsumoBan_P, lstr_Referencia_Item, "S")
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrConsumoBan_P

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(1) = Arredondar(IIf(iblnMicroGeracaoConvenioSefaz, vlrConsumoBan_P, vlrConsumoBan_Sefaz_P) * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(1) = idbl_Ite_Pic(1)
                        '
                        idbl_Bas_Pic(1) = Arredondar(idbl_Ite_Pic(1) / coefTribSIcms, 2)
                        idbl_Bas_Icm(1) = Arredondar(idbl_Bas_Pic(1) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(1) = Arredondar(idbl_Bas_Pic(1) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(1) = Arredondar(idbl_Bas_Pic(1) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(1) = Arredondar(idbl_Bas_Icm(1) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(1) = idbl_Bas_Icm(1)
                        idbl_Ret_Dem(1) = 0

                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumoBan_P
                        '
                        If iblnParCativo Then
                                Item_Fatura = Trim(Item_Fatura & "0302110010?" & Replace(CStr(ldblParCatConsumoPonta), ",", ".") & "$;") 'Consumo Ponta
                            Else
                                If Mid(Me.txtTA.Text, 3, 2) = "AL" Then
                                    Item_Fatura = Trim(Item_Fatura & "0302110010?" & Replace(CStr(0), ",", ".") & "$;") 'Consumo Ponta
                                Else
                                    Item_Fatura = Trim(Item_Fatura & "0302110010?" & Replace(CStr(consumo_p), ",", ".") & "$;") 'Consumo Ponta
                                End If
                            End If
                            '
                            'Modificado para usar o reverso utilizado - ricardo 01/12/2019
                            vlrReverso_Ponta = 0
                            If (reverso_p + reverso_res_p) > 0 Then
                                If (reverso_p + reverso_res_p) <= consumo_p Then
                                    vlrReverso_Ponta = Arredondar((reverso_p + reverso_res_p) * (idblTarConsumoBan_p - idblTarConsumoSemDesconto_p), 2)
                                Else
                                    vlrReverso_Ponta = Arredondar(consumo_p * (idblTarConsumoBan_p - idblTarConsumoSemDesconto_p), 2)
                                End If
                            End If
                            Item_Fatura = Trim(Item_Fatura & "0302022110?" & Replace(CStr(vlrReverso_Ponta), ",", ".") & "$;") 'Valor Reverso Ponta
                        End If 'vlrConsumo_P > 0
                    End If
                '
                'Consumo Fora de Ponta
                If CDbl(IIf(IsNumeric(Me.txtConsumo_FP.Text), Me.txtConsumo_FP.Text, 0)) > 0 Then 'Val(Replace(txtConsumo_FP.Text, ",", ".")) > 0 Then
                    If iblnParCativo Then
                        vlrConsumo_FP = Truncate(ldblParCatConsumoFPonta * idblTarConsumo_fp, 2)
                        ldblParCatVlrkWhFPonta = Truncate((consumo_fp - ldblParCatConsumoFPonta) * idblTarConsumoLiv_fp, 2)
                        vlrConsumo_Sefaz_FP = vlrConsumo_FP
                    Else
                        vlrConsumo_FP = Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0) * idblTarConsumo_fp, 2)
                        If (reverso_fp + reverso_res_fp) <= consumo_fp Then
                            vlrReverso_FP = Truncate(consumo_fp * idblTarConsumo_fp, 2) - Truncate((reverso_fp + reverso_res_fp) * idblTarConsumo_fp, 2)
                        End If
                        If Not iblnMicroGeracaoConvenioSefaz Then
                            vlrConsumo_Sefaz_FP = Truncate(consumo_fp * idblTarConsumo_fp, 2)
                        Else
                            vlrConsumo_Sefaz_FP = vlrConsumo_FP
                        End If
                    End If
                    '
                    'Consumo Fora de Ponta
                    If vlrConsumo_FP > 0 Then
                        If iblnParCativo Then
                            lstr_Referencia_Item = "( " & Truncate(ldblParCatConsumoFPonta, 6) & " x " & Arredondar(idblTarConsumo_fp, 5) & " )"
                            ldbl_Quantidade_Item = ldblParCatConsumoFPonta
                        Else

                            If micro_geracao = 0 Then
                                lstr_Referencia_Item = "( " & Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0), 6) & " x " & Arredondar(idblTarConsumo_fp, 5) & " )"
                                ldbl_Quantidade_Item = IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0)
                                AdicionaGridItem(row_grid, "0302020011", Trim(codTodescri(IIf(iblnParCativo, "0302020011", IIf(Me.txtTA.Text = "01AL00", "0302020061", "0302020011")))), ldbl_Quantidade_Item, vlrConsumo_FP, lstr_Referencia_Item, "S")
                            Else
                                'vlrConsumo_FP_tusd = Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, (consumo_fp - (reverso_fp + reverso_res_fp)), 0) * idblTarConsumo_fp_tusd, 2)
                                'vlrConsumo_FP_te = Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, (consumo_fp - (reverso_fp + reverso_res_fp)), 0) * idblTarConsumo_fp_te, 2)
                                vlrConsumo_FP_tusd = Truncate((consumo_fp * idblTarConsumo_fp_tusd), 2)
                                vlrConsumo_FP_te = Truncate((consumo_fp * idblTarConsumo_fp_te), 2)

                                vlrConsumo_FP = vlrConsumo_FP_tusd + vlrConsumo_FP_te

                                Item_Fatura = Trim(Item_Fatura & "0302020011?" & Replace(CStr(vlrConsumo_FP), ",", ".") & "$;") 'Consumo Fora Ponta

                                'GD - TUSD
                                lstr_Referencia_Item = "( " & Truncate(consumo_fp, 6) & " x " & Arredondar(idblTarConsumo_fp_tusd, 5) & " )"
                                ldbl_Quantidade_Item = consumo_fp
                                AdicionaGridItem(row_grid, "0303020092", Trim(codTodescri("0303020092")), ldbl_Quantidade_Item, vlrConsumo_FP_tusd, lstr_Referencia_Item, "S")
                                Item_Fatura = Trim(Item_Fatura & "0303010092?" & ldbl_Quantidade_Item & ";") 'TUSd f ponta

                                'GD - TE
                                lstr_Referencia_Item = "( " & Truncate(consumo_fp, 6) & " x " & Arredondar(idblTarConsumo_fp_te, 5) & " )"
                                ldbl_Quantidade_Item = consumo_fp
                                AdicionaGridItem(row_grid, "0304020092", Trim(codTodescri("0304020092")), ldbl_Quantidade_Item, vlrConsumo_FP_te, lstr_Referencia_Item, "S")
                                Item_Fatura = Trim(Item_Fatura & "0304010092?" & ldbl_Quantidade_Item & ";") 'TE f ponta
                            End If
                        End If
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrConsumo_FP

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(2) = Arredondar(IIf(iblnMicroGeracaoConvenioSefaz, vlrConsumo_FP, vlrConsumo_Sefaz_FP) * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(2) = idbl_Ite_Pic(2)
                        '
                        idbl_Bas_Pic(2) = Arredondar(idbl_Ite_Pic(2) / coefTribSIcms, 2)
                        idbl_Bas_Icm(2) = Arredondar(idbl_Bas_Pic(2) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(2) = Arredondar(idbl_Bas_Pic(2) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(2) = Arredondar(idbl_Bas_Pic(2) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(2) = Arredondar(idbl_Bas_Icm(2) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(2) = idbl_Bas_Icm(2)
                        idbl_Ret_Dem(2) = 0
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumo_FP
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010011?" & Replace(CStr(consumo_fp), ",", ".") & "$;") 'Consumo Fora de Ponta
                        Item_Fatura = Trim(Item_Fatura & "0302012011?" & Replace(CStr(reverso_fp), ",", ".") & "$;") 'Reverso Fora de Ponta
                        Item_Fatura = Trim(Item_Fatura & "0302013011?" & Replace(CStr(reverso_res_fp), ",", ".") & "$;") 'Reverso Fora de Ponta
                        '
                        vlrReverso_ForaPonta = 0
                        If (reverso_fp + reverso_res_fp) > 0 Then
                            If (reverso_fp + reverso_res_fp) <= consumo_fp Then
                                vlrReverso_ForaPonta = Arredondar((reverso_fp + reverso_res_fp) * idblTarConsumo_fp, 2)
                            Else
                                vlrReverso_ForaPonta = Arredondar(consumo_fp * idblTarConsumo_fp, 2)
                            End If
                        End If
                        Item_Fatura = Trim(Item_Fatura & "0302022011?" & Replace(CStr(vlrReverso_ForaPonta), ",", ".") & "$;") 'Valor Reverso Fora Ponta
                    Else 'vlrConsumo_FP = 0

                        If micro_geracao = 0 Then
                            AdicionaGridItem(row_grid, "0302020011", Trim(codTodescri("0302020011")), IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0), vlrConsumo_FP, "( " & Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0), 6) & " x " & Arredondar(idblTarConsumo_fp, 5) & " )", "S")
                            '
                            'Totaliza e coloca os itens de quantidade
                            vlrTotal = vlrTotal + vlrConsumo_FP
                            '
                            Item_Fatura = Trim(Item_Fatura & "0302010011?" & Replace(CStr(consumo_fp), ",", ".") & "$;") 'Consumo Fora de Ponta
                            Item_Fatura = Trim(Item_Fatura & "0302012011?" & Replace(CStr(reverso_fp), ",", ".") & "$;") 'Reverso Fora de Ponta
                            Item_Fatura = Trim(Item_Fatura & "0302013011?" & Replace(CStr(reverso_res_fp), ",", ".") & "$;") 'Residuo Reverso Fora de Ponta
                            '
                            vlrReverso_ForaPonta = 0
                            If (reverso_fp + reverso_res_fp) > 0 Then
                                If (reverso_fp + reverso_res_fp) <= consumo_fp Then
                                    vlrReverso_ForaPonta = Arredondar((reverso_fp + reverso_res_fp) * idblTarConsumo_fp, 2)
                                Else
                                    vlrReverso_ForaPonta = Arredondar(consumo_fp * idblTarConsumo_fp, 2)
                                End If
                            End If
                            Item_Fatura = Trim(Item_Fatura & "0302022011?" & Replace(CStr(vlrReverso_ForaPonta), ",", ".") & "$;") 'Valor Reverso Fora Ponta
                        Else

                            vlrConsumo_FP_tusd = 0
                            vlrConsumo_FP_te = 0

                            vlrConsumo_FP = vlrConsumo_FP_tusd + vlrConsumo_FP_te

                            Item_Fatura = Trim(Item_Fatura & "0302020011?" & Replace(CStr(vlrConsumo_FP), ",", ".") & "$;") 'Consumo Fora Ponta

                            'GD - TUSD
                            lstr_Referencia_Item = "( " & Truncate(consumo_fp, 6) & " x " & Arredondar(idblTarConsumo_fp_tusd, 5) & " )"
                            ldbl_Quantidade_Item = consumo_fp
                            AdicionaGridItem(row_grid, "0303020092", Trim(codTodescri("0303020092")), ldbl_Quantidade_Item, vlrConsumo_FP_tusd, lstr_Referencia_Item, "S")
                            Item_Fatura = Trim(Item_Fatura & "0303010092?" & ldbl_Quantidade_Item & ";") 'TUSd f ponta

                            'GD - TE
                            lstr_Referencia_Item = "( " & Truncate(consumo_fp, 6) & " x " & Arredondar(idblTarConsumo_fp_te, 5) & " )"
                            ldbl_Quantidade_Item = consumo_fp
                            AdicionaGridItem(row_grid, "0304020092", Trim(codTodescri("0304020092")), ldbl_Quantidade_Item, vlrConsumo_FP_te, lstr_Referencia_Item, "S")
                            Item_Fatura = Trim(Item_Fatura & "0304010092?" & ldbl_Quantidade_Item & ";") 'TE f ponta
                        End If
                    End If
                End If 'Val(Replace(txtConsumo_FP.Text, ",", ".")) > 0
                '
                'Bandeira Fora de Ponta
                If CDbl(IIf(IsNumeric(Me.txtConsumo_FP.Text), Me.txtConsumo_FP.Text, 0)) > 0 Then 'Val(Replace(txtConsumo_FP.Text, ",", ".")) > 0 Then
                    If iblnParCativo Then
                        vlrConsumoBan_FP = Truncate(ldblParCatConsumoFPonta * (idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp), 2)
                        vlrConsumoBan_Sefaz_FP = vlrConsumoBan_FP
                    Else
                        vlrConsumoBan_FP = Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0) * (idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp), 2)
                        If (reverso_fp + reverso_res_fp) <= consumo_fp Then
                            vlrReverso_FP = vlrReverso_FP + Truncate(consumo_fp * idblTarConsumoBan_fp, 2) - Truncate((reverso_fp + reverso_res_fp) * idblTarConsumoBan_fp, 2)
                        End If
                        If Not iblnMicroGeracaoConvenioSefaz Then
                            vlrConsumoBan_Sefaz_FP = Truncate(consumo_fp * (idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp), 2)
                        Else
                            vlrConsumoBan_Sefaz_FP = vlrConsumoBan_FP
                        End If
                    End If
                    '
                    'Bandeira Fora de Ponta
                    If vlrConsumoBan_FP > 0 Then
                        If iblnParCativo Then
                            lstr_Referencia_Item = " ( " & Truncate(ldblParCatConsumoFPonta, 6) & " x " & Arredondar(idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp, 5) & " )"
                            ldbl_Quantidade_Item = ldblParCatConsumoFPonta
                        Else
                            lstr_Referencia_Item = " ( " & Truncate(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0), 6) & " x " & Arredondar(idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp, 5) & " )"
                            ldbl_Quantidade_Item = IIf((reverso_fp + reverso_res_fp) <= consumo_fp, consumo_fp - (reverso_fp + reverso_res_fp), 0)
                        End If
                        AdicionaGridItem(row_grid, "0302120011", Trim(codTodescri("0302120011")), ldbl_Quantidade_Item, vlrConsumoBan_FP, lstr_Referencia_Item, "S")
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrConsumoBan_FP

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(3) = Arredondar(IIf(iblnMicroGeracaoConvenioSefaz, vlrConsumoBan_FP, vlrConsumoBan_Sefaz_FP) * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(3) = idbl_Ite_Pic(3)
                        '
                        idbl_Bas_Pic(3) = Arredondar(idbl_Ite_Pic(3) / coefTribSIcms, 2)
                        idbl_Bas_Icm(3) = Arredondar(idbl_Bas_Pic(3) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(3) = Arredondar(idbl_Bas_Pic(3) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(3) = Arredondar(idbl_Bas_Pic(3) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(3) = Arredondar(idbl_Bas_Icm(3) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(3) = idbl_Bas_Icm(3)
                        idbl_Ret_Dem(3) = 0
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumoBan_FP
                        '
                        If iblnParCativo Then
                            Item_Fatura = Trim(Item_Fatura & "0302110011?" & Replace(CStr(ldblParCatConsumoFPonta), ",", ".") & "$;") 'Consumo Fora de Ponta
                        Else
                            If Mid(Me.txtTA.Text, 3, 2) = "AL" Then
                                Item_Fatura = Trim(Item_Fatura & "0302110011?" & Replace(CStr(0), ",", ".") & "$;") 'Consumo Fora de Ponta
                            Else
                                Item_Fatura = Trim(Item_Fatura & "0302110011?" & Replace(CStr(consumo_fp), ",", ".") & "$;") 'Consumo Fora de Ponta
                            End If
                        End If
                        '
                        vlrReverso_ForaPonta = 0
                        If (reverso_fp + reverso_res_fp) > 0 Then
                            If (reverso_fp + reverso_res_fp) <= consumo_fp Then
                                vlrReverso_ForaPonta = Arredondar((reverso_fp + reverso_res_fp) * (idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp), 2)
                            Else
                                vlrReverso_ForaPonta = Arredondar(consumo_fp * (idblTarConsumoBan_fp - idblTarConsumoSemDesconto_fp), 2)
                            End If
                        End If
                        Item_Fatura = Trim(Item_Fatura & "0302022111?" & Replace(CStr(vlrReverso_ForaPonta), ",", ".") & "$;") 'Valor Reverso Fora Ponta
                    End If
                End If

                'Compensado GD I, GD II, GD III
                If micro_geracao = 1 Then

                    'ldblReversokWhSaldoAnterior = SaldoAnteriorGD(lintConsId, lintUnidId, lstrZona, lstrLivro, lstrConta, VB6.Format(txtMesAno.Text, "yyyyMM"))

                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT * "
                    lstrSql = lstrSql & " FROM `gd_tipo` "
                    lstrSql = lstrSql & " WHERE `zona` = " & lstrZona & ""
                    lstrSql = lstrSql & " AND `livro` = " & lstrLivro & ""
                    lstrSql = lstrSql & " AND `conta` = " & lstrConta & ""
                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                    If dt1.Rows.Count > 0 Then
                        For Each row1 As DataRow In dt1.Rows
                            grupo_GD = Trim(IIf(IsDBNull(row1("perfil")), "", row1("perfil")))
                        Next
                    Else
                        grupo_GD = 1
                    End If
                    dt1 = Nothing

                    cod_tarifa = Mid(txtTA.Text, 3, 2)
                    If cod_tarifa = "AV" Then
                        cod_tarifa = "A4"
                    Else
                        cod_tarifa = "A3"
                    End If

                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT * "
                    lstrSql = lstrSql & " FROM `tarifa_gd` "
                    lstrSql = lstrSql & " WHERE num LIKE ""%" & cod_tarifa & "%"" "
                    lstrSql = lstrSql & " ORDER BY `num`"
                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                    If dt1.Rows.Count > 0 Then
                        For Each row1 As DataRow In dt1.Rows
                            If row1("posto") = "P" Then
                                If grupo_GD = 1 Then
                                    If row1("num") = "02A4011101" Then
                                        idblDescontoGD_p_tusd = Trim(IIf(IsDBNull(row1("valor_gd1_tusd")), "", row1("valor_gd1_tusd"))) / 100
                                    ElseIf row1("num") = "02A4011102" Then
                                        idblDescontoGD_p_te = Trim(IIf(IsDBNull(row1("valor_gd1_te")), "", row1("valor_gd1_te"))) / 100
                                    End If
                                ElseIf grupo_GD = 2 Then
                                    If row1("num") = "02A4011101" Then
                                        idblDescontoGD_p_tusd = Trim(IIf(IsDBNull(row1("valor_gd2_tusd")), "", row1("valor_gd2_tusd"))) / 100
                                    ElseIf row1("num") = "02A4011102" Then
                                        idblDescontoGD_p_te = Trim(IIf(IsDBNull(row1("valor_gd2_te")), "", row1("valor_gd2_te"))) / 100
                                    End If
                                Else
                                    If row1("num") = "02A4011101" Then
                                        idblDescontoGD_p_tusd = Trim(IIf(IsDBNull(row1("valor_gd3_tusd")), "", row1("valor_gd3_tusd"))) / 100
                                    ElseIf row1("num") = "02A4011102" Then
                                        idblDescontoGD_p_te = Trim(IIf(IsDBNull(row1("valor_gd3_te")), "", row1("valor_gd3_te"))) / 100
                                    End If
                                End If
                            ElseIf row1("posto") = "FP" Then
                                If grupo_GD = 1 Then
                                    If row1("num") = "02A4011103" Then
                                        idblDescontoGD_fp_tusd = Trim(IIf(IsDBNull(row1("valor_gd1_tusd")), "", row1("valor_gd1_tusd"))) / 100
                                    ElseIf row1("num") = "02A4011104" Then
                                        idblDescontoGD_fp_te = Trim(IIf(IsDBNull(row1("valor_gd1_te")), "", row1("valor_gd1_te"))) / 100
                                    End If
                                ElseIf grupo_GD = 2 Then
                                    If row1("num") = "02A4011103" Then
                                        idblDescontoGD_fp_tusd = Trim(IIf(IsDBNull(row1("valor_gd2_tusd")), "", row1("valor_gd2_tusd"))) / 100
                                    ElseIf row1("num") = "02A4011104" Then
                                        idblDescontoGD_fp_te = Trim(IIf(IsDBNull(row1("valor_gd2_te")), "", row1("valor_gd2_te"))) / 100
                                    End If
                                Else
                                    If row1("num") = "02A4011103" Then
                                        idblDescontoGD_fp_tusd = Trim(IIf(IsDBNull(row1("valor_gd3_tusd")), "", row1("valor_gd3_tusd"))) / 100
                                    ElseIf row1("num") = "02A4011104" Then
                                        idblDescontoGD_fp_te = Trim(IIf(IsDBNull(row1("valor_gd3_te")), "", row1("valor_gd3_te"))) / 100
                                    End If
                                End If
                            End If
                        Next
                    End If
                    dt1 = Nothing

                    If (reverso_p + reverso_res_p) > 0 Then

                        reverso_Saldo_p = Arredondar(IIf((reverso_p + reverso_res_p) <= consumo_p, 0, ((reverso_p + reverso_res_p) - consumo_p)), 2)

                        If reverso_Saldo_p = 0 Then
                            lstr_Referencia_Item_tusd = "( " & Truncate(reverso_p + reverso_res_p, 6) & " x " & Arredondar((idblTarConsumo_p_tusd * idblDescontoGD_p_tusd), 5) & " )"
                            ldbl_Quantidade_Item = (reverso_p + reverso_res_p)
                            vlrConsumo_P_Tusd = Truncate((reverso_p + reverso_res_p) * (idblTarConsumo_p_tusd * idblDescontoGD_p_tusd), 2)
                            vlrConsumo_P_Tusd *= -1
                        Else
                            lstr_Referencia_Item_tusd = "( " & Truncate(consumo_p, 6) & " x " & Arredondar((idblTarConsumo_p_tusd * idblDescontoGD_p_tusd), 5) & " )"
                            ldbl_Quantidade_Item = consumo_p
                            vlrConsumo_P_Tusd = Truncate((consumo_p) * (idblTarConsumo_p_tusd * idblDescontoGD_p_tusd), 2)
                            vlrConsumo_P_Tusd *= -1
                        End If

                        AdicionaGridItem(row_grid, "0313020091", Trim(codTodescri("0313020091")), ldbl_Quantidade_Item, vlrConsumo_P_Tusd, lstr_Referencia_Item_tusd, "S")
                        Item_Fatura = Trim(Item_Fatura & "0313010091?" & ldbl_Quantidade_Item & ";") 'Comp. TUSD ponta
                        Item_Fatura = Trim(Item_Fatura & "02" & cod_tarifa & "011101?" & (idblDescontoGD_p_tusd * 100) & ";") 'Porcentagem Desconto GD (I, II, III)

                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumo_P_Tusd
                        '
                        If reverso_Saldo_p = 0 Then
                            lstr_Referencia_Item_te = "( " & Truncate(reverso_p + reverso_res_p, 6) & " x " & Arredondar((idblTarConsumo_p_te * idblDescontoGD_p_te), 5) & " )"
                            ldbl_Quantidade_Item = (reverso_p + reverso_res_p)
                            vlrConsumo_P_te = Truncate((reverso_p + reverso_res_p) * (idblTarConsumo_p_te * idblDescontoGD_p_te), 2)
                            vlrConsumo_P_te *= -1
                        Else
                            lstr_Referencia_Item_te = "( " & Truncate((consumo_p), 6) & " x " & Arredondar((idblTarConsumo_p_te * idblDescontoGD_p_te), 5) & " )"
                            ldbl_Quantidade_Item = consumo_p
                            vlrConsumo_P_te = Truncate((consumo_p) * (idblTarConsumo_p_te * idblDescontoGD_p_te), 2)
                            vlrConsumo_P_te *= -1
                        End If

                        AdicionaGridItem(row_grid, "0314020091", Trim(codTodescri("0314020091")), ldbl_Quantidade_Item, vlrConsumo_P_te, lstr_Referencia_Item_te, "S")
                        Item_Fatura = Trim(Item_Fatura & "0314010091?" & ldbl_Quantidade_Item & ";") 'Comp. TE ponta
                        Item_Fatura = Trim(Item_Fatura & "02" & cod_tarifa & "011102?" & (idblDescontoGD_p_te * 100) & ";") 'Porcentagem Desconto GD (I, II, III)

                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumo_P_te

                    End If

                    If (reverso_fp + reverso_res_fp) > 0 Then

                        reverso_Saldo_fp = Arredondar(IIf((reverso_fp + reverso_res_fp) <= consumo_fp, 0, ((reverso_fp + reverso_res_fp) - consumo_fp)), 2)

                        If reverso_Saldo_fp = 0 Then
                            lstr_Referencia_Item_tusd = "( " & Truncate(reverso_fp + reverso_res_fp, 6) & " x " & Arredondar((idblTarConsumo_fp_tusd * idblDescontoGD_fp_tusd), 5) & " )"
                            ldbl_Quantidade_Item = (reverso_fp + reverso_res_fp)
                            vlrConsumo_FP_tusd = Truncate((reverso_fp + reverso_res_fp) * (idblTarConsumo_fp_tusd * idblDescontoGD_fp_tusd), 2)
                            vlrConsumo_FP_tusd *= -1
                        Else
                            lstr_Referencia_Item_tusd = "( " & Truncate((consumo_fp), 6) & " x " & Arredondar((idblTarConsumo_fp_tusd * idblDescontoGD_fp_tusd), 5) & " )"
                            ldbl_Quantidade_Item = consumo_fp
                            vlrConsumo_FP_tusd = Truncate((consumo_fp) * (idblTarConsumo_fp_tusd * idblDescontoGD_fp_tusd), 2)
                            vlrConsumo_FP_tusd *= -1
                        End If

                        AdicionaGridItem(row_grid, "0313020092", Trim(codTodescri("0313020092")), ldbl_Quantidade_Item, vlrConsumo_FP_tusd, lstr_Referencia_Item_tusd, "S")
                        Item_Fatura = Trim(Item_Fatura & "0313010092?" & ldbl_Quantidade_Item & ";") 'Comp. TUSD f ponta
                        Item_Fatura = Trim(Item_Fatura & "02" & cod_tarifa & "011103?" & (idblDescontoGD_fp_tusd * 100) & ";") 'Porcentagem Desconto GD (I, II, III)

                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumo_FP_tusd
                        '
                        If reverso_Saldo_fp = 0 Then
                            lstr_Referencia_Item_te = "( " & Truncate(reverso_fp + reverso_res_fp, 6) & " x " & Arredondar((idblTarConsumo_fp_te * idblDescontoGD_fp_te), 5) & " )"
                            ldbl_Quantidade_Item = (reverso_fp + reverso_res_fp)
                            vlrConsumo_FP_te = Truncate((reverso_fp + reverso_res_fp) * (idblTarConsumo_fp_te * idblDescontoGD_fp_te), 2)
                            vlrConsumo_FP_te *= -1
                        Else
                            lstr_Referencia_Item_te = "( " & Truncate((consumo_fp), 6) & " x " & Arredondar((idblTarConsumo_fp_te * idblDescontoGD_fp_te), 5) & " )"
                            ldbl_Quantidade_Item = consumo_fp
                            vlrConsumo_FP_te = Truncate((consumo_fp) * (idblTarConsumo_fp_te * idblDescontoGD_fp_te), 2)
                            vlrConsumo_FP_te *= -1
                        End If

                        AdicionaGridItem(row_grid, "0314020092", Trim(codTodescri("0314020092")), ldbl_Quantidade_Item, vlrConsumo_FP_te, lstr_Referencia_Item_te, "S")
                        Item_Fatura = Trim(Item_Fatura & "0314010092?" & ldbl_Quantidade_Item & ";") 'Comp. TE f ponta
                        Item_Fatura = Trim(Item_Fatura & "02" & cod_tarifa & "011104?" & (idblDescontoGD_fp_te * 100) & ";") 'Porcentagem Desconto GD (I, II, III)

                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrConsumo_FP_te
                        '
                    End If


                    Item_Fatura = Trim(Item_Fatura & "0302021001?" & reverso_res_fp & ";") ' Saldo Reverso Fora Ponta Anterior
                    Item_Fatura = Trim(Item_Fatura & "0302013011?" & (reverso_Saldo_p + reverso_Saldo_fp) & ";") ' Saldo Reverso na Fora Ponta Mês
                    Item_Fatura = Trim(Item_Fatura & "0315010090?" & grupo_GD & ";") 'Grupo GD(I,II,III)

                    '[Registra o que foi feito nos GD]
                    SalvaGD(lstrZona, lstrLivro, lstrConta, lintConsId, lintUnidId, Arredondar(consumo_p, 2), Arredondar(consumo_fp, 2), Arredondar(reverso_p, 2), Arredondar(reverso_fp, 2), "01/" & txtMesAno.Text, "01/" & txtMesAno.Text, Arredondar((reverso_p + reverso_res_p), 2), Arredondar((reverso_fp + reverso_res_fp), 2), 0, 0, 0, reverso_Saldo_fp, 1, reverso_res_fp)

                End If
                '
                'Quando livre e se for parcialmente cativo
                If iblnParCativo Then
                    '
                    'Ponta
                    If ldblParCatVlrkWhPonta > 0 Then
                        AdicionaGridItem(row_grid, "0302020060", Trim(codTodescri("0302020060")), (consumo_p - ldblParCatConsumoPonta), ldblParCatVlrkWhPonta, "( " & Truncate(consumo_p - ldblParCatConsumoPonta, 6) & " x " & Arredondar(idblTarConsumoLiv_p, 5) & " )", "S")
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If

                        ldblTotalVrlItens = ldblTotalVrlItens + ldblParCatVlrkWhPonta

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(4) = Arredondar(ldblParCatVlrkWhPonta * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(4) = idbl_Ite_Pic(4)
                        '
                        idbl_Bas_Pic(4) = Arredondar(idbl_Ite_Pic(4) / coefTribSIcms, 2)
                        idbl_Bas_Icm(4) = Arredondar(idbl_Bas_Pic(4) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(4) = Arredondar(idbl_Bas_Pic(4) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(4) = Arredondar(idbl_Bas_Pic(4) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(4) = Arredondar(idbl_Bas_Icm(4) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(4) = idbl_Bas_Icm(4)
                        idbl_Ret_Dem(4) = 0
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + ldblParCatVlrkWhPonta
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010060?" & Replace(CStr(consumo_p - ldblParCatConsumoPonta), ",", ".") & "$;") 'Consumo Ponta
                    End If
                    '
                    'Fora de ponta
                    If ldblParCatConsumoFPonta > 0 Then
                        AdicionaGridItem(row_grid, "0302020061", Trim(codTodescri("0302020061")), (consumo_fp - ldblParCatConsumoFPonta), ldblParCatVlrkWhFPonta, "( " & Truncate(consumo_fp - ldblParCatConsumoFPonta, 6) & " x " & Arredondar(idblTarConsumoLiv_fp, 5) & " )", "S")
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If

                        ldblTotalVrlItens = ldblTotalVrlItens + ldblParCatVlrkWhFPonta

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(5) = Arredondar(ldblParCatVlrkWhFPonta * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(5) = idbl_Ite_Pic(5)
                        '
                        idbl_Bas_Pic(5) = Arredondar(idbl_Ite_Pic(5) / coefTribSIcms, 2)
                        idbl_Bas_Icm(5) = Arredondar(idbl_Bas_Pic(5) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(5) = Arredondar(idbl_Bas_Pic(5) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(5) = Arredondar(idbl_Bas_Pic(5) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(5) = Arredondar(idbl_Bas_Icm(5) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(5) = idbl_Bas_Icm(5)
                        idbl_Ret_Dem(5) = 0
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + ldblParCatVlrkWhFPonta
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010061?" & Replace(CStr(consumo_fp - ldblParCatConsumoFPonta), ",", ".") & "$;") 'Consumo Fora de Ponta
                    End If
                End If
                '
                '-- Azul ou Livre Azul - todo Verde não tem Ponta sempre é considerado tudo como fora de ponta
                If iintTipoTarifa = 2 Then
                    '-- Demanda Ponta
                    Demanda_Lida_P = CDbl(txtDemanda_p.Text)
                    '
                    If Constante_Demanda_P > 0 Then
                        Demanda_Lida_P = Demanda_Lida_P * Constante_Demanda_P
                    End If
                    '
                    'If ldblPerdas > 0 Then
                    'Demanda_Lida_P = Demanda_Lida_P + (Demanda_Lida_P * (ldblPerdas / 100))
                    'End If
                    '
                    qtd_Demanda_Dif_Cont_P = 0
                    '
                    If ldblDemandaContratadaPonta > 0 Then
                        If iblnPeriodoTeste And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) >= VB6.Format(idteIniPeriodoTeste, "yyyyMM") And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) <= VB6.Format(idteFimPeriodoTeste, "yyyyMM") And ldblDemandaAtualContratadaPonta <> ldblDemandaAnteriorContratadaPonta Then
                            '
                            'Quando a unidade consumidora esta em periodo de teste
                            'A ultrapassagem conforme REN 414 Art. 104 precisa que:
                            'a demanda lida seja maior que o somatório:
                            '1) Nova demanda contratada
                            '2) 5% da demanda contratada atual
                            '3) 30% da diferença entra a nova demanda contratada e a demanda contratada anterior
                            If Demanda_Lida_P > (ldblDemandaAtualContratadaPonta + (ldblDemandaContratadaPonta * (ldblPercDemUP / 100)) + ((ldblDemandaAtualContratadaPonta - ldblDemandaContratadaPonta) * (30 / 100))) Then
                                Dem_Ultrapassagem_P = (Demanda_Lida_P - ldblDemandaContratadaForaPonta)
                                Demanda_Faturada_P = Demanda_Lida_P
                                qtd_Demanda_Dif_Cont_P = 0
                            Else
                                Dem_Ultrapassagem_P = 0
                                Demanda_Faturada_P = Demanda_Lida_P
                                qtd_Demanda_Dif_Cont_P = 0
                            End If
                            '
                            If Demanda_Lida_P < ldblDemandaAnteriorContratadaPonta Then
                                Dem_Ultrapassagem_P = 0
                                Demanda_Faturada_P = Demanda_Lida_P
                                qtd_Demanda_Dif_Cont_P = ldblDemandaAnteriorContratadaPonta - Demanda_Lida_P
                            End If
                        ElseIf Demanda_Lida_P > ldblDemandaContratadaPonta Then  'se a demanda lida for maior que a demanda contratada
                            '
                            'se a demanda lida for maior que o contrato e estiver dentro do % aceitavél, não se cobra ultrapassagem
                            If (Demanda_Lida_P <= (ldblDemandaContratadaPonta * ((ldblPercDemUP / 100) + 1))) Then
                                Demanda_Faturada_P = Demanda_Lida_P
                                Dem_Ultrapassagem_P = 0
                                qtd_Demanda_Dif_Cont_P = 0
                            Else
                                Dem_Ultrapassagem_P = (Demanda_Lida_P - ldblDemandaContratadaPonta)
                                '
                                'Com a entrada do art 104 toda demanda faturada é sempre a lida, e cobra-se 1 vez a tarifa da lida e 2 vezes a tarifa da ultrapassagem
                                Demanda_Faturada_P = Demanda_Lida_P
                                qtd_Demanda_Dif_Cont_P = 0
                            End If
                        ElseIf Demanda_Lida_P < ldblDemandaContratadaPonta Then
                            Demanda_Faturada_P = Demanda_Lida_P
                            Dem_Ultrapassagem_P = 0
                            qtd_Demanda_Dif_Cont_P = ldblDemandaContratadaPonta - Demanda_Lida_P
                        Else
                            Demanda_Faturada_P = Demanda_Lida_P
                            Dem_Ultrapassagem_P = 0
                            qtd_Demanda_Dif_Cont_P = 0
                        End If
                    Else
                        Dem_Ultrapassagem_P = 0
                        qtd_Demanda_Dif_Cont_P = 0
                        Demanda_Faturada_P = Demanda_Lida_P
                    End If
                    '
                    'Base_Demanda_Reativa_p = Truncate(Demanda_Lida_P * idblTarDemanda_p, 2)
                    '
                    'Calculo do valor da demanda ponta
                    If Demanda_Faturada_P > ldblDemandaContratadaPonta Then
                        vlrDemanda_P = Truncate(Demanda_Faturada_P * idblTarDemanda_p, 2)
                    Else
                        vlrDemanda_P = Truncate(ldblDemandaContratadaPonta * idblTarDemanda_p, 2)
                    End If

                    '
                    'Nova regra pela diferença da demanda em 28/04/2021 - Ricardo
                    If qtd_Demanda_Dif_Cont_P > 0 Then
                        vlr_Demanda_Dif_Cont_P = Truncate(qtd_Demanda_Dif_Cont_P * idblTarDemanda_p, 2)
                    Else
                        vlr_Demanda_Dif_Cont_P = 0
                    End If
                    '
                    'Demanda Ponta
                    If vlrDemanda_P > 0 Then
                        If Demanda_Faturada_P > ldblDemandaContratadaPonta Then
                            AdicionaGridItem(row_grid, "0302020021", Trim(codTodescri("0302020021")), Demanda_Faturada_P, vlrDemanda_P, "( " & Truncate(Demanda_Faturada_P, 6) & " x " & Arredondar(idblTarDemanda_p, 5) & " )", "S")
                        Else
                            AdicionaGridItem(row_grid, "0302020021", Trim(codTodescri("0302020021")), ldblDemandaContratadaPonta, vlrDemanda_P, "( " & Truncate(ldblDemandaContratadaPonta, 6) & " x " & Arredondar(idblTarDemanda_p, 5) & " )", "S")
                        End If
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                                ldbl_Per_Des_SP = 0.85
                            Else
                                ldbl_Per_Des_SP = 1
                            End If
                            If isento_demanda = "N" Then

                                ldblTotalVrlItens = ldblTotalVrlItens + vlrDemanda_P

                                '
                                'em 01/05/2021
                                idbl_Ite_Pic(6) = Arredondar(vlrDemanda_P * ldbl_Per_Des_SP, 2)
                                idbl_Ite_Icm(6) = idbl_Ite_Pic(6)
                                '
                                idbl_Bas_Pic(6) = Arredondar(idbl_Ite_Pic(6) / coefTribSIcms, 2)
                                idbl_Bas_Icm(6) = Arredondar(idbl_Bas_Pic(6) / (1 - (idblAliqICMS / 100)), 2)
                                idbl_Vlr_Pis(6) = Arredondar(idbl_Bas_Pic(6) * (idblAliqPIS / 100), 2)
                                idbl_Vlr_Cof(6) = Arredondar(idbl_Bas_Pic(6) * (idblAliqCofins / 100), 2)
                                idbl_Vlr_Icm(6) = Arredondar(idbl_Bas_Icm(6) * (idblAliqICMS / 100), 2)
                                '
                                idbl_Ret_Con(6) = 0
                                idbl_Ret_Dem(6) = idbl_Bas_Icm(6)
                            Else

                                ldblTotalVrlItens = ldblTotalVrlItens + vlrDemanda_P

                                '
                                'em 01/05/2021
                                idbl_Ite_Pic(6) = Arredondar(vlrDemanda_P * ldbl_Per_Des_SP, 2)
                                idbl_Ite_Icm(6) = idbl_Ite_Pic(6)
                                '
                                idbl_Bas_Pic(6) = Arredondar(idbl_Ite_Pic(6) / coefTribSIcms, 2)
                                idbl_Bas_Icm(6) = 0
                                idbl_Vlr_Pis(6) = Arredondar(idbl_Bas_Pic(6) * (idblAliqPIS / 100), 2)
                                idbl_Vlr_Cof(6) = Arredondar(idbl_Bas_Pic(6) * (idblAliqCofins / 100), 2)
                                idbl_Vlr_Icm(6) = 0
                                '
                                idbl_Ret_Con(6) = 0
                                idbl_Ret_Dem(6) = idbl_Bas_Pic(6)
                            End If
                            '
                            'Totaliza e coloca os itens de quantidade
                            vlrTotal = vlrTotal + vlrDemanda_P
                        '
                        If Demanda_Faturada_P > ldblDemandaContratadaPonta Then
                            Item_Fatura = Trim(Item_Fatura & "0302010021?" & Replace(CStr(Demanda_Faturada_P), ",", ".") & "$;") 'demanda Ponta
                        Else
                            Item_Fatura = Trim(Item_Fatura & "0302010021?" & Replace(CStr(ldblDemandaAtualContratadaPonta), ",", ".") & "$;") 'demanda Ponta
                        End If

                        Item_Fatura = Trim(Item_Fatura & "0302010019?" & Replace(CStr(Demanda_Lida_P), ",", ".") & "$;") 'Demanda Lida Ponta
                        '
                        'Grava contratos conforme regra do período de teste
                        If iblnPeriodoTeste And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) >= VB6.Format(idteIniPeriodoTeste, "yyyyMM") And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) <= VB6.Format(idteFimPeriodoTeste, "yyyyMM") And ldblDemandaAtualContratadaPonta <> ldblDemandaAnteriorContratadaPonta Then
                            Item_Fatura = Trim(Item_Fatura & "0302010020?" & Replace(CStr(ldblDemandaAtualContratadaPonta), ",", ".") & "$;") 'Demanda Contratada na ponta
                            Item_Fatura = Trim(Item_Fatura & "0302010030?" & Replace(CStr(ldblDemandaAnteriorContratadaPonta), ",", ".") & "$;") 'Demanda Contratada na ponta
                        Else
                            Item_Fatura = Trim(Item_Fatura & "0302010020?" & Replace(CStr(ldblDemandaContratadaPonta), ",", ".") & "$;") 'Demanda Contratada na ponta
                        End If
                        '
                        'Ajuste de demanda - coisa antiga que tem que ser revisto - as regras mudaram para que é tem sazonalidade com contrato de demanda difenciada durante o ano
                        'If nAjuste_Demanda_P > 0 Then
                        '  vlr_ajuste_demanda_p = Truncate(nAjuste_Demanda_P * idblTarDemanda_p, 2)
                        '  If vlr_ajuste_demanda_p > 0 Then
                        '     AdicionaGridItem(row_grid, _
                        ''                          "0302020021", _
                        ''                          codTodescri("0302020021"), _
                        ''                          nAjuste_Demanda_P, _
                        ''                          vlr_ajuste_demanda_p, _
                        ''                          "( " & Truncate(nAjuste_Demanda_P, 6) & " x " & Arredondar(idblTarDemanda_p, 5) & " )", _
                        ''                          "S")
                        '  End If
                        'End If
                    End If 'vlrDemanda_P > 0
                    '
                    'Novo calculo com a diferença da demanda lida contra o contrato - não tributa icms
                    If vlr_Demanda_Dif_Cont_P > 0 Then
                        AdicionaGridItem(row_grid, "0302020121", codTodescri("0302020121"), qtd_Demanda_Dif_Cont_P, vlr_Demanda_Dif_Cont_P, "( " & Truncate(qtd_Demanda_Dif_Cont_P, 6) & " x " & Arredondar(idblTarDemanda_p, 5) & " )", "S")

                        ldblTotalVrlItens = ldblTotalVrlItens + vlr_Demanda_Dif_Cont_P

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(7) = vlr_Demanda_Dif_Cont_P
                        idbl_Ite_Icm(7) = 0
                        '
                        idbl_Bas_Pic(7) = Arredondar(idbl_Ite_Pic(7) / coefTribSIcms, 2)
                        idbl_Bas_Icm(7) = 0
                        idbl_Vlr_Pis(7) = Arredondar(idbl_Bas_Pic(7) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(7) = Arredondar(idbl_Bas_Pic(7) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(7) = 0
                        '
                        idbl_Ret_Con(7) = 0
                        idbl_Ret_Dem(7) = idbl_Bas_Pic(7)
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlr_Demanda_Dif_Cont_P
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010121?" & Replace(CStr(qtd_Demanda_Dif_Cont_P), ",", ".") & "$;") 'demanda Ponta
                    End If
                    '
                    '-- Demanda de Ultrapassagem na Ponta
                    If Dem_Ultrapassagem_P > 0 Then
                        vlrDem_Ultrapassagem_P = Truncate(Dem_Ultrapassagem_P * idblTarDemUltra_p, 2)
                        AdicionaGridItem(row_grid, "0302020022", codTodescri("0302020022"), Dem_Ultrapassagem_P, vlrDem_Ultrapassagem_P, "( " & Truncate(Dem_Ultrapassagem_P, 6) & " x " & Arredondar(idblTarDemUltra_p, 5) & " )", "S")
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If
                        If isento_demanda = "N" Then

                            ldblTotalVrlItens = ldblTotalVrlItens + vlrDem_Ultrapassagem_P

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(8) = Arredondar(vlrDem_Ultrapassagem_P * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(8) = idbl_Ite_Pic(8)
                            '
                            idbl_Bas_Pic(8) = Arredondar(idbl_Ite_Pic(8) / coefTribSIcms, 2)
                            idbl_Bas_Icm(8) = Arredondar(idbl_Bas_Pic(8) / (1 - (idblAliqICMS / 100)), 2)
                            idbl_Vlr_Pis(8) = Arredondar(idbl_Bas_Pic(8) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(8) = Arredondar(idbl_Bas_Pic(8) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(8) = Arredondar(idbl_Bas_Icm(8) * (idblAliqICMS / 100), 2)
                            '
                            idbl_Ret_Con(8) = 0
                            idbl_Ret_Dem(8) = idbl_Bas_Icm(8)
                        Else

                            ldblTotalVrlItens = ldblTotalVrlItens + vlrDem_Ultrapassagem_P

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(8) = Arredondar(vlrDem_Ultrapassagem_P * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(8) = idbl_Ite_Pic(8)
                            '
                            idbl_Bas_Pic(8) = Arredondar(idbl_Ite_Pic(8) / coefTribSIcms, 2)
                            idbl_Bas_Icm(8) = 0
                            idbl_Vlr_Pis(8) = Arredondar(idbl_Bas_Pic(8) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(8) = Arredondar(idbl_Bas_Pic(8) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(8) = 0
                            '
                            idbl_Ret_Con(8) = 0
                            idbl_Ret_Dem(8) = idbl_Bas_Pic(8)
                        End If
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrDem_Ultrapassagem_P
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010022?" & Replace(CStr(Dem_Ultrapassagem_P), ",", ".") & "$;") 'demanda ultrapassagem ponta
                    End If 'Dem_Ultrapassagem_P > 0
                End If 'Fim Azul
                '
                'Demanda Fora de Ponta
                Demanda_Lida_FP = CDbl(txtDemanda_FP.Text)
                If Constante_Demanda_FP > 0 Then
                    Demanda_Lida_FP = Demanda_Lida_FP * Constante_Demanda_FP
                    'Demanda_Lida_FP = Arredondar(Demanda_Lida_FP * Constante_Demanda_FP)
                End If
                If ldblPerdas > 0 Then
                    'Demanda_Lida_FP = Demanda_Lida_FP + (Demanda_Lida_FP * (ldblPerdas / 100))
                    'Demanda_Lida_FP = (Demanda_Lida_FP * ((ldblPerdas / 100) + 1))
                    Demanda_Lida_FP = ((Demanda_Lida_FP * ldblPerdas) + Demanda_Lida_FP)
                End If
                '
                qtd_Demanda_Dif_Cont_FP = 0
                '
                If ldblDemandaContratadaForaPonta > 0 Then
                    If iblnPeriodoTeste And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) >= VB6.Format(idteIniPeriodoTeste, "yyyyMM") And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) <= VB6.Format(idteFimPeriodoTeste, "yyyyMM") And ldblDemandaAtualContratadaForaPonta <> ldblDemandaAnteriorContratadaForaPonta Then
                        '
                        'Quando a unidade consumidora esta em periodo de teste
                        'A ultrapassagem conforme REN 414 Art. 104 precisa que:
                        'a demanda lida seja maior que o somatório:
                        '1) Nova demanda contratada
                        '2) 5% da demanda contratada atual
                        '3) 30% da diferença entra a nova demanda contratada e a demanda contratada anterior
                        If Demanda_Lida_FP > (ldblDemandaAtualContratadaForaPonta + (ldblDemandaContratadaForaPonta * (ldblPercDemUFP / 100)) + ((ldblDemandaAtualContratadaForaPonta - ldblDemandaContratadaForaPonta) * (30 / 100))) Then
                            Dem_Ultrapassagem_FP = (Demanda_Lida_FP - ldblDemandaContratadaForaPonta)
                            Demanda_Faturada_FP = Demanda_Lida_FP
                            qtd_Demanda_Dif_Cont_FP = 0
                        Else
                            Dem_Ultrapassagem_FP = 0
                            Demanda_Faturada_FP = Demanda_Lida_FP
                            qtd_Demanda_Dif_Cont_FP = 0
                        End If
                        '
                        If Demanda_Lida_FP < ldblDemandaAnteriorContratadaForaPonta Then
                            Dem_Ultrapassagem_FP = 0
                            Demanda_Faturada_FP = Demanda_Lida_FP
                            qtd_Demanda_Dif_Cont_FP = ldblDemandaAnteriorContratadaForaPonta - Demanda_Lida_FP
                        End If
                    ElseIf Demanda_Lida_FP > ldblDemandaContratadaForaPonta Then  'se a demanda lida for maior que a demanda contratada
                        '
                        'se a demanda lida for maior que o contrato e estiver dentro do % aceitavél, não se cobra ultrapassagem
                        If (Demanda_Lida_FP <= ((ldblDemandaContratadaForaPonta * ((ldblPercDemUFP / 100) + 1)))) Then
                            Demanda_Faturada_FP = Demanda_Lida_FP
                            Dem_Ultrapassagem_FP = 0
                            qtd_Demanda_Dif_Cont_FP = 0
                        Else
                            Dem_Ultrapassagem_FP = (Demanda_Lida_FP - ldblDemandaContratadaForaPonta)
                            '
                            'Com a entrada do art 104 toda demanda faturada é sempre a lida, e cobra-se 1 vez a tarifa da lida e 2 vezes a tarifa da ultrapassagem
                            Demanda_Faturada_FP = Demanda_Lida_FP
                            qtd_Demanda_Dif_Cont_FP = 0
                        End If
                    ElseIf Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        Demanda_Faturada_FP = Demanda_Lida_FP
                        Dem_Ultrapassagem_FP = 0
                        qtd_Demanda_Dif_Cont_FP = ldblDemandaContratadaForaPonta - Demanda_Lida_FP
                        'qtd_Demanda_Dif_Cont_FP = Demanda_Lida_FP
                    Else
                        Demanda_Faturada_FP = Demanda_Lida_FP
                        Dem_Ultrapassagem_FP = 0
                        qtd_Demanda_Dif_Cont_FP = 0
                    End If
                Else
                    Dem_Ultrapassagem_FP = 0
                    qtd_Demanda_Dif_Cont_FP = 0
                    Demanda_Faturada_FP = Demanda_Lida_FP
                End If
                '
                'Base_Demanda_Reativa_fp = Demanda_Lida_FP * idblTarDemanda_fp
                '
                'Calculo do valor da demanda fora de ponta
                'If Demanda_Faturada_FP > ldblDemandaContratadaForaPonta Then
                vlrDemanda_FP = Truncate(Demanda_Faturada_FP * idblTarDemanda_fp, 2)
                'Else
                'vlrDemanda_FP = Truncate(ldblDemandaContratadaForaPonta * idblTarDemanda_fp, 2)
                'End If
                '
                'Nova regra pela diferença da demanda em 28/04/2021 - Ricardo
                If qtd_Demanda_Dif_Cont_FP > 0 Then
                    vlr_Demanda_Dif_Cont_FP = Truncate(qtd_Demanda_Dif_Cont_FP * idblTarDemanda_fp, 2)
                Else
                    vlr_Demanda_Dif_Cont_FP = 0
                End If
                '
                'Demanda fora de ponta
                If vlrDemanda_FP > 0 Then
                    If iintTipoTarifa = 2 Then
                        lstr_Descricao_Item = codTodescri("0302020023")
                    Else
                        lstr_Descricao_Item = "DEMANDA" 'se for verde tem que aparecer nos itens da fatura apenas como demanda não existe ponta ou fora de ponta
                    End If
                    'If Demanda_Faturada_FP > ldblDemandaContratadaForaPonta Then
                    AdicionaGridItem(row_grid, "0302020023", lstr_Descricao_Item, Demanda_Faturada_FP, vlrDemanda_FP, "( " & Truncate(Demanda_Faturada_FP, 6) & " x " & Arredondar(idblTarDemanda_fp, 5) & " )", "S")
                    'Else
                    'AdicionaGridItem(row_grid, "0302020023", lstr_Descricao_Item, ldblDemandaContratadaForaPonta, vlrDemanda_FP, "( " & Truncate(ldblDemandaContratadaForaPonta, 6) & " x " & Arredondar(idblTarDemanda_fp, 5) & " )", "S")
                    'End If
                    '
                    'Tributação
                    If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                        ldbl_Per_Des_SP = 0.85
                    Else
                        ldbl_Per_Des_SP = 1
                    End If
                    If isento_demanda = "N" Then

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrDemanda_FP

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(9) = Arredondar(vlrDemanda_FP * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(9) = idbl_Ite_Pic(9)
                        '
                        idbl_Bas_Pic(9) = Arredondar(idbl_Ite_Pic(9) / coefTribSIcms, 2)
                        idbl_Bas_Icm(9) = Arredondar(idbl_Bas_Pic(9) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(9) = Arredondar(idbl_Bas_Pic(9) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(9) = Arredondar(idbl_Bas_Pic(9) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(9) = Arredondar(idbl_Bas_Icm(9) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(9) = 0
                        idbl_Ret_Dem(9) = idbl_Bas_Icm(9)
                    Else

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrDemanda_FP

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(9) = Arredondar(vlrDemanda_FP * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(9) = idbl_Ite_Pic(9)
                            '
                            idbl_Bas_Pic(9) = Arredondar(idbl_Ite_Icm(9) / coefTribSIcms, 2)
                            idbl_Bas_Icm(9) = 0
                            idbl_Vlr_Pis(9) = Arredondar(idbl_Bas_Pic(9) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(9) = Arredondar(idbl_Bas_Pic(9) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(9) = 0
                            '
                            idbl_Ret_Con(9) = 0
                            idbl_Ret_Dem(9) = idbl_Bas_Pic(9)
                        End If
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrDemanda_FP
                    '
                    If Demanda_Faturada_FP > ldblDemandaAtualContratadaForaPonta Then
                        Item_Fatura = Trim(Item_Fatura & "0302010025?" & Replace(CStr(Demanda_Faturada_FP), ",", ".") & "$;")  'Demanda faturada Fora Ponta
                        Item_Fatura = Trim(Item_Fatura & "0302010023?" & Replace(CStr(Demanda_Faturada_FP), ",", ".") & "$;")  'Demanda medida Fora Ponta
                    Else
                        Item_Fatura = Trim(Item_Fatura & "0302010025?" & Replace(CStr(ldblDemandaAtualContratadaForaPonta), ",", ".") & "$;")  'Demanda faturada Fora Ponta
                        Item_Fatura = Trim(Item_Fatura & "0302010023?" & Replace(CStr(Demanda_Faturada_FP), ",", ".") & "$;")  'Demanda medida Fora Ponta
                    End If
                    '
                    'Grava contratos conforme regra do período de teste
                    If iblnPeriodoTeste And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) >= VB6.Format(idteIniPeriodoTeste, "yyyyMM") And Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) <= VB6.Format(idteFimPeriodoTeste, "yyyyMM") And ldblDemandaAtualContratadaForaPonta <> ldblDemandaAnteriorContratadaForaPonta Then
                            Item_Fatura = Trim(Item_Fatura & "0302010024?" & Replace(CStr(ldblDemandaAtualContratadaForaPonta), ",", ".") & "$;") 'Demanda Contratada na fora de ponta
                            Item_Fatura = Trim(Item_Fatura & "0302010034?" & Replace(CStr(ldblDemandaAnteriorContratadaForaPonta), ",", ".") & "$;") 'Demanda Contratada na fora de ponta
                        Else
                            Item_Fatura = Trim(Item_Fatura & "0302010024?" & Replace(CStr(ldblDemandaContratadaForaPonta), ",", ".") & "$;") 'Demanda Contratada na fora ponta
                        End If
                        '
                        'Ajuste de demanda - coisa antiga que tem que ser revisto - as regras mudaram para que é tem sazonalidade com contrato de demanda difenciada durante o ano
                        'If nAjuste_Demanda_FP > 0 Then
                        '  vlr_ajuste_demanda_fp = nAjuste_Demanda_FP * idblTarDemanda_fp
                        '  If vlr_ajuste_demanda_fp > 0 Then
                        '     AdicionaGridItem(row_grid, _
                        ''                          "0302020021", _
                        ''                          codTodescri("0302020021"), _
                        ''                          nAjuste_Demanda_FP, _
                        ''                          vlr_ajuste_demanda_fp, _
                        ''                          "( " & Arredondar(nAjuste_Demanda_FP, 6) & " x " & idblTarDemanda_fp & " )", _
                        ''                          "S")
                        '  End If
                        'End If
                    End If 'vlrDemanda_FP > 0
                    '
                    'Novo calculo com a diferença da demanda lida contra o contrato - não tributa icms
                    If vlr_Demanda_Dif_Cont_FP > 0 Then
                    If iintTipoTarifa = 2 Then
                        lstr_Descricao_Item = codTodescri("0302020123")
                    Else
                        lstr_Descricao_Item = "DIF.DEM.CONT." 'se for verde tem que aparecer nos itens da fatura apenas como demanda não existe ponta ou fora de ponta
                    End If
                    AdicionaGridItem(row_grid, "0302020123", lstr_Descricao_Item, qtd_Demanda_Dif_Cont_FP, vlr_Demanda_Dif_Cont_FP, "( " & Arredondar(qtd_Demanda_Dif_Cont_FP, 6) & " x " & idblTarDemanda_fp & " )", "S")

                    ldblTotalVrlItens = ldblTotalVrlItens + 0

                    '
                    'em 01/05/2021
                    idbl_Ite_Pic(10) = vlr_Demanda_Dif_Cont_FP
                    idbl_Ite_Icm(10) = 0
                    '
                    idbl_Bas_Pic(10) = Arredondar(idbl_Ite_Pic(10) / coefTribSIcms, 2)
                    idbl_Bas_Icm(10) = 0
                    idbl_Vlr_Pis(10) = Arredondar(idbl_Bas_Pic(10) * (idblAliqPIS / 100), 2)
                    idbl_Vlr_Cof(10) = Arredondar(idbl_Bas_Pic(10) * (idblAliqCofins / 100), 2)
                    idbl_Vlr_Icm(10) = 0
                    '
                    idbl_Ret_Con(10) = 0
                    idbl_Ret_Dem(10) = idbl_Bas_Pic(10)
                    '
                    'Totaliza e coloca os itens de quantidade
                    vlrTotal = vlrTotal + vlr_Demanda_Dif_Cont_FP
                    '
                    Item_Fatura = Trim(Item_Fatura & "0302010123?" & Replace(CStr(qtd_Demanda_Dif_Cont_FP), ",", ".") & "$;") 'demanda fora Ponta
                End If
                '
                '-- Demanda de Ultrapassagem na Fora de Ponta
                If Dem_Ultrapassagem_FP > 0 Then
                    If iintTipoTarifa <> 1 Then
                        lstr_Descricao_Item = codTodescri("0302020026")
                    Else
                        lstr_Descricao_Item = "DEMANDA ULTRAP." 'se for verde tem que aparecer nos itens da fatura apenas como demanda não existe ponta ou fora de ponta
                    End If
                    vlrDem_Ultrapassagem_FP = Truncate(Dem_Ultrapassagem_FP * idblTarDemUltra_fp, 2)
                    AdicionaGridItem(row_grid, "0302020026", lstr_Descricao_Item, Dem_Ultrapassagem_FP, vlrDem_Ultrapassagem_FP, "( " & Truncate(Dem_Ultrapassagem_FP, 6) & " x " & Arredondar(idblTarDemUltra_fp, 5) & " )", "S")
                    '
                    'Tributação
                    If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                        ldbl_Per_Des_SP = 0.85
                    Else
                        ldbl_Per_Des_SP = 1
                    End If
                    If isento_demanda = "N" Then

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrDem_Ultrapassagem_FP
                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(11) = Arredondar(vlrDem_Ultrapassagem_FP * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(11) = idbl_Ite_Pic(11)
                        '
                        idbl_Bas_Pic(11) = Arredondar(idbl_Ite_Pic(11) / coefTribSIcms, 2)
                        idbl_Bas_Icm(11) = Arredondar(idbl_Bas_Pic(11) / (1 - (idblAliqICMS / 100)), 2)
                        idbl_Vlr_Pis(11) = Arredondar(idbl_Bas_Pic(11) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(11) = Arredondar(idbl_Bas_Pic(11) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(11) = Arredondar(idbl_Bas_Icm(11) * (idblAliqICMS / 100), 2)
                        '
                        idbl_Ret_Con(11) = 0
                        idbl_Ret_Dem(11) = idbl_Bas_Icm(11)
                    Else

                        ldblTotalVrlItens = ldblTotalVrlItens + vlrDem_Ultrapassagem_FP

                        '
                        'em 01/05/2021
                        idbl_Ite_Pic(11) = Arredondar(vlrDem_Ultrapassagem_FP * ldbl_Per_Des_SP, 2)
                        idbl_Ite_Icm(11) = idbl_Ite_Pic(11)
                        '
                        idbl_Bas_Pic(11) = Arredondar(idbl_Ite_Pic(11) / coefTribSIcms, 2)
                        idbl_Bas_Icm(11) = 0
                        idbl_Vlr_Pis(11) = Arredondar(idbl_Bas_Pic(11) * (idblAliqPIS / 100), 2)
                        idbl_Vlr_Cof(11) = Arredondar(idbl_Bas_Pic(11) * (idblAliqCofins / 100), 2)
                        idbl_Vlr_Icm(11) = 0
                        '
                        idbl_Ret_Con(11) = 0
                        idbl_Ret_Dem(11) = idbl_Bas_Pic(11)
                    End If
                    '
                    'Totaliza e coloca os itens de quantidade
                    vlrTotal = vlrTotal + vlrDem_Ultrapassagem_FP
                    '
                    Item_Fatura = Trim(Item_Fatura & "0302010026?" & Replace(CStr(Dem_Ultrapassagem_FP), ",", ".") & "$;") 'Consumo Ponta
                End If 'Dem_Ultrapassagem_FP > 0
                '
                ' CALCULOS DE CONSUMO REATIVO
                If lblnCobrarReativo Then
                    If iintTipoTarifa = 2 Then 'azul
                        If leitura_reativo = 1 Then
                            '
                            'CONSUMO E DEMANDA REATIVOS NA PONTA PELO FATOR DE POTÊNCIA MÉDIO
                            BaseConsumo_Reativo = consumo_p
                            vlrBaseConsumo_Reativo = vlrConsumo_P
                            BaseDemanda_Reativa = vlrDemanda_P 'Truncate(Demanda_Lida_P * idblTarDemanda_p, 2)
                            '
                            'Virada de Medidor - reativo do consumo ponta
                            Kvarh_P = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_P.Text), Me.txtKvarh_P.Text, 0)), ant_kvarh)
                            If Constante_Kvarh_P > 0 Then
                                Kvarh_P = Kvarh_P * Constante_Kvarh_P
                            End If
                            If ldblPerdas > 0 Then
                                Kvarh_P = Kvarh_P + (Kvarh_P * (ldblPerdas / 100))
                            End If
                            If Kvarh_P <> 0 Then
                                vlrqh = ((Kvarh_P * 2) - BaseConsumo_Reativo) / System.Math.Sqrt(3)
                            Else
                                vlrqh = 0
                            End If
                            If istrQH = "S" Then
                                ldbl_Reativo_Aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (vlrqh * vlrqh))
                            Else
                                ldbl_Reativo_Aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (Kvarh_P * Kvarh_P))
                            End If
                            If ldbl_Reativo_Aux = 0 Then ldbl_Reativo_Aux = 1
                            '
                            'Fator de Potencia
                            fator_potencia = Arredondar((1 / ldbl_Reativo_Aux) * BaseConsumo_Reativo, 5)
                            Item_Fatura = Trim(Item_Fatura & "0302030099?" & Replace(CStr(fator_potencia), ",", ".") & ";") ' Fator de Potencia na ponta
                            '
                            If fator_potencia < 0.92 Then
                                If fator_potencia <> 0 Then
                                    '-- Consumo Reativo
                                    ldbl_Reativo_Aux = 0.92 / fator_potencia
                                    ldbl_Reativo_Aux = Arredondar(ldbl_Reativo_Aux - 1, 5)
                                    vlrKvarh_Consumo_p = Truncate(vlrBaseConsumo_Reativo * ldbl_Reativo_Aux, 2)
                                    leitConsumo_aux = ldbl_Reativo_Aux
                                    '-- Demanda Reativa
                                    vlrKvarh_Demanda_p = Truncate(BaseDemanda_Reativa * ldbl_Reativo_Aux, 2)
                                    lstrDescKVarh_demanda_p = " ( " & VB6.Format(BaseDemanda_Reativa, "#,######0.000000") & " x " & VB6.Format(ldbl_Reativo_Aux, "#,##0.00") & " )"
                                End If
                            End If
                            '
                            'CONSUMO E DEMANDA REATIVOS FORA DE PONTA PELO FATOR DE POTÊNCIA MÉDIO
                            BaseConsumo_Reativo = consumo_fp
                            vlrBaseConsumo_Reativo = vlrConsumo_FP
                            BaseDemanda_Reativa = vlrDemanda_FP ' Truncate(Demanda_Lida_FP * idblTarDemanda_fp, 2)
                            '
                            'Virada de Medidor - reativo do consumo fora de ponta
                            Kvarh_fp = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_FP.Text), Me.txtKvarh_FP.Text, 0)), ant_kvarh_fp)
                            If Constante_Kvarh_FP > 0 Then
                                Kvarh_fp = Kvarh_fp * Constante_Kvarh_FP
                            End If
                            If ldblPerdas > 0 Then
                                Kvarh_fp = Kvarh_fp + (Kvarh_fp * (ldblPerdas / 100))
                            End If
                            If Kvarh_fp <> 0 Then
                                vlrqh = ((Kvarh_fp * 2) - BaseConsumo_Reativo) / System.Math.Sqrt(3)
                            Else
                                vlrqh = 0
                            End If
                            If istrQH = "S" Then
                                ldbl_Reativo_Aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (vlrqh * vlrqh))
                            Else
                                ldbl_Reativo_Aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (Kvarh_fp * Kvarh_fp))
                            End If
                            If ldbl_Reativo_Aux = 0 Then ldbl_Reativo_Aux = 1
                            '
                            'Fator de Potencia
                            fator_potencia = Arredondar((1 / ldbl_Reativo_Aux) * BaseConsumo_Reativo, 5)
                            Item_Fatura = Trim(Item_Fatura & "0302030098?" & Replace(CStr(fator_potencia), ",", ".") & ";") ' Fator de Potencia na fora ponta
                            '
                            If fator_potencia < 0.92 Then
                                If fator_potencia <> 0 Then
                                    '-- Consumo Reativo
                                    ldbl_Reativo_Aux = 0.92 / fator_potencia
                                    ldbl_Reativo_Aux = Arredondar(ldbl_Reativo_Aux - 1, 5)
                                    vlrKvarh_Consumo_fp = Truncate(vlrBaseConsumo_Reativo * ldbl_Reativo_Aux, 2)
                                    leitConsumo_aux = ldbl_Reativo_Aux
                                    '-- Demanda Reativa
                                    vlrKvarh_Demanda_fp = Truncate(BaseDemanda_Reativa * ldbl_Reativo_Aux, 2)
                                    lstrDescKVarh_demanda_fp = " ( " & VB6.Format(BaseDemanda_Reativa, "#,######0.000000") & " x " & VB6.Format(ldbl_Reativo_Aux, "#,##0.00") & " )"
                                End If
                            End If
                        Else 'If leitura_reativo = 1
                            '
                            'Virada de Medidor - reativo do consumo ponta
                            Kvarh_P = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_P.Text), Me.txtKvarh_P.Text, 0)), ant_kvarh)
                            If Constante_Kvarh_P > 0 Then
                                Kvarh_P = Kvarh_P * Constante_Kvarh_P
                            End If
                            If ldblPerdas > 0 Then
                                Kvarh_P = Kvarh_P + (Kvarh_P * (ldblPerdas / 100))
                            End If
                            If idblTarTe_B1 > 0 Then
                                vlrKvarh_Consumo_p = Truncate(Kvarh_P * idblTarTe_B1, 2)
                            Else
                                vlrKvarh_Consumo_p = Truncate(Kvarh_P * idblTarConsumo_p, 2)
                            End If
                            'demanda reativa na ponta - DMCR
                            auxdemanda = IIf(ldblDemandaContratadaPonta > Demanda_Lida_P, ldblDemandaContratadaPonta, Demanda_Lida_P)
                            If auxdemanda > Demanda_Faturada_P Then

                                dblDemReatAux = CDbl(IIf(IsNumeric(Me.txtDem_Exc_Ponta.Text), Me.txtDem_Exc_Ponta.Text, 0))
                                dblDemReatAux = (dblDemReatAux * Constante_Kvarh_P) * (1 + (ldblPerdas / 100))
                                If dblDemReatAux > auxdemanda Then
                                    ldblDemaAuxP = dblDemReatAux - auxdemanda
                                    vlrKvarh_Demanda_p = Truncate(ldblDemaAuxP * idblTarDemanda_p, 2)
                                    lstrDescKVarh_demanda_p = " ( " & VB6.Format(ldblDemaAuxP, "#,######0.000000") & " x " & VB6.Format(idblTarDemanda_p, "#,##0.00") & " )"
                                Else
                                    vlrKvarh_Demanda_p = 0
                                    lstrDescKVarh_demanda_p = ""
                                End If

                            End If
                            '
                            'Virada de Medidor - reativo do consumo fora de ponta
                            Kvarh_fp = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_FP.Text), Me.txtKvarh_FP.Text, 0)), ant_kvarh_fp)
                            If Constante_Kvarh_FP > 0 Then
                                Kvarh_fp = Kvarh_fp * Constante_Kvarh_FP
                            End If
                            If ldblPerdas > 0 Then
                                Kvarh_fp = Kvarh_fp + (Kvarh_fp * (ldblPerdas / 100))
                            End If
                            If idblTarTe_B1 > 0 Then
                                vlrKvarh_Consumo_fp = Truncate(Kvarh_fp * idblTarTe_B1, 2)
                            Else
                                vlrKvarh_Consumo_fp = Truncate(Kvarh_fp * idblTarConsumo_fp, 2)
                            End If
                            'demanda reativa fora de ponta
                            auxdemanda = IIf(ldblDemandaContratadaForaPonta > Demanda_Lida_FP, ldblDemandaContratadaForaPonta, Demanda_Lida_FP)
                            If Demanda_Lida_FP > auxdemanda Then

                                dblDemReatAux = CDbl(IIf(IsNumeric(Me.txtDem_Exc_FP.Text), Me.txtDem_Exc_FP.Text, 0))
                                dblDemReatAux = (dblDemReatAux * Constante_Kvarh_FP) * (1 + (ldblPerdas / 100))
                                If dblDemReatAux > auxdemanda Then
                                    ldblDemaAuxFP = dblDemReatAux - auxdemanda
                                    vlrKvarh_Demanda_fp = Truncate(ldblDemaAuxFP * idblTarDemanda_fp, 2)
                                    lstrDescKVarh_demanda_fp = " ( " & VB6.Format(ldblDemaAuxFP, "#,######0.000000") & " x " & VB6.Format(idblTarDemanda_fp, "#,##0.00") & " )"
                                Else
                                    vlrKvarh_Demanda_fp = 0
                                    lstrDescKVarh_demanda_fp = ""
                                End If
                            End If 'If leitura_reativo = 1

                        End If

                    Else 'if iintTipoTarifa = 2
                        If leitura_reativo = 1 Then
                                '
                                'CONSUMO E DEMANDA REATIVOS PELO FATOR DE POTÊNCIA MÉDIO
                                BaseConsumo_Reativo = consumo_p + consumo_fp
                                vlrBaseConsumo_Reativo = vlrConsumo_P + vlrConsumo_FP
                                BaseDemanda_Reativa = vlrDemanda_FP '(Demanda_Lida_FP * idblTarDemanda_fp)
                                '
                                'Virada de Medidor - reativo do consumo ponta
                                Kvarh_P = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_P.Text), Me.txtKvarh_P.Text, 0)), ant_kvarh)
                                If Constante_Kvarh_P > 0 Then
                                    Kvarh_P = Kvarh_P * Constante_Kvarh_P
                                End If
                                If ldblPerdas > 0 Then
                                    Kvarh_P = Kvarh_P + (Kvarh_P * (ldblPerdas / 100))
                                End If
                                '
                                'Virada de Medidor - reativo do consumo fora de ponta
                                Kvarh_fp = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_FP.Text), Me.txtKvarh_FP.Text, 0)), ant_kvarh_fp)
                                If Constante_Kvarh_FP > 0 Then
                                    Kvarh_fp = Kvarh_fp * Constante_Kvarh_FP
                                End If
                                If ldblPerdas > 0 Then
                                    Kvarh_fp = Kvarh_fp + (Kvarh_fp * (ldblPerdas / 100))
                                End If
                                '
                                Kvarh_fp = Kvarh_fp + Kvarh_P
                                '
                                If Kvarh_fp <> 0 Then
                                    vlrqh = ((Kvarh_fp * 2) - BaseConsumo_Reativo) / System.Math.Sqrt(3)
                                Else
                                    vlrqh = 0
                                End If
                                If istrQH = "S" Then
                                    ldbl_Reativo_Aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (vlrqh * vlrqh))
                                Else
                                    ldbl_Reativo_Aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (Kvarh_fp * Kvarh_fp))
                                End If
                                If ldbl_Reativo_Aux = 0 Then ldbl_Reativo_Aux = 1
                                '
                                'Fator de Potencia
                                fator_potencia = Arredondar((1 / ldbl_Reativo_Aux) * BaseConsumo_Reativo, 5)
                                Item_Fatura = Trim(Item_Fatura & "0302030099?" & Replace(CStr(fator_potencia), ",", ".") & ";") ' Fator de Potencia na ponta
                                '
                                If fator_potencia < 0.92 Then
                                    If fator_potencia <> 0 Then
                                        '-- Consumo Reativo
                                        ldbl_Reativo_Aux = 0.92 / fator_potencia
                                        ldbl_Reativo_Aux = Arredondar(ldbl_Reativo_Aux - 1, 5)
                                        vlrKvarh_Consumo_p = Truncate(vlrConsumo_P * ldbl_Reativo_Aux, 2)
                                        vlrKvarh_Consumo_fp = Truncate(vlrConsumo_FP * ldbl_Reativo_Aux, 2)
                                        leitConsumo_aux = ldbl_Reativo_Aux
                                        '-- Demanda Reativa
                                        vlrKvarh_Demanda_fp = Truncate(BaseDemanda_Reativa * ldbl_Reativo_Aux, 2)
                                        If Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                                            auxDemandaReativa = Truncate((ldblDemandaContratadaForaPonta - Demanda_Lida_FP) * idblTarDemanda_fp, 2)
                                            If vlrKvarh_Demanda_fp > auxDemandaReativa Then
                                                vlrKvarh_Demanda_fp = vlrKvarh_Demanda_fp - auxDemandaReativa
                                            Else
                                                vlrKvarh_Demanda_fp = 0
                                            End If
                                        End If
                                    End If
                                End If
                            Else 'If leitura_reativo = 1
                                'consumo reativo na ponta
                                '
                                'Virada de Medidor - reativo do consumo ponta
                                Kvarh_P = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_P.Text), Me.txtKvarh_P.Text, 0)), ant_kvarh)
                                If Constante_Kvarh_P > 0 Then
                                    'Kvarh_P = Math.Round(Kvarh_P * Constante_Kvarh_P * lbdCompensacao_Perda, 0)
                                    'Kvarh_P = Math.Round(Kvarh_P * Constante_Kvarh_P, 0)
                                    Kvarh_P = Kvarh_P * Constante_Kvarh_P
                                End If
                                If ldblPerdas > 0 Then
                                    Kvarh_P = Math.Round(((Kvarh_P * ldblPerdas) + Kvarh_P), 0)
                                    'Kvarh_P = ((Kvarh_P * ldblPerdas) + Kvarh_P)
                                Else
                                    Kvarh_P = Kvarh_P
                                    'Kvarh_P = Math.Round(Kvarh_P * ((ldblPerdas / 100) + 1), 0)
                                End If
                                'If idblTarTe_B1 > 0 Then
                                'vlrKvarh_Consumo_p = Math.Round(Kvarh_P * idblTarTe_B1, 0)
                                'Else
                                vlrKvarh_Consumo_p = Truncate(Kvarh_P * idblTarTe_B1, 2)
                                'End If
                                '
                                'Virada de Medidor - reativo do consumo fora de ponta
                                Kvarh_fp = Virada_Medidor(CDbl(IIf(IsNumeric(Me.txtKvarh_FP.Text), Me.txtKvarh_FP.Text, 0)), ant_kvarh_fp)
                                If Constante_Kvarh_FP > 0 Then
                                    'Kvarh_fp = Math.Round(Kvarh_fp * Constante_Kvarh_FP * lbdCompensacao_Perda, 0)
                                    'Kvarh_fp = Math.Round(Kvarh_fp * Constante_Kvarh_FP, 0)
                                    Kvarh_fp = Kvarh_fp * Constante_Kvarh_FP
                                End If
                                If ldblPerdas > 0 Then
                                    'Kvarh_fp = Kvarh_fp + (Kvarh_fp * (ldblPerdas / 100))
                                    Kvarh_fp = Math.Round(((Kvarh_fp * ldblPerdas) + Kvarh_fp), 0)
                                    'Kvarh_fp = ((Kvarh_fp * ldblPerdas) + Kvarh_fp)
                                Else
                                    'Kvarh_fp = Math.Round(Kvarh_fp, 0)
                                    Kvarh_fp = Kvarh_fp
                                    'Kvarh_fp = Kvarh_fp * ((ldblPerdas / 100) + 1)
                                End If
                                'If idblTarTe_B1 > 0 Then
                                'vlrKvarh_Consumo_fp = Truncate(Kvarh_fp * idblTarTe_B1, 2)
                                'Else
                                vlrKvarh_Consumo_fp = Truncate(Kvarh_fp * idblTarTe_B1, 2)
                            'End If
                            'demanda reativa fora de ponta
                            auxdemanda = IIf(ldblDemandaContratadaForaPonta > Demanda_Lida_FP, ldblDemandaContratadaForaPonta, Demanda_Lida_FP)
                            dblDemReatAux = CDbl(IIf(txtDem_Exc_FP.Text = "", "0", txtDem_Exc_FP.Text))
                            dblDemReatAux = (dblDemReatAux * Constante_Kvarh_FP) * (1 + (ldblPerdas / 100))
                            If dblDemReatAux > auxdemanda Then
                                ldblDemaAuxFP = dblDemReatAux - auxdemanda
                                vlrKvarh_Demanda_fp = Truncate(ldblDemaAuxFP * idblTarDemanda_fp, 2)
                                lstrDescKVarh_demanda_fp = " ( " & VB6.Format(ldblDemaAuxFP, "#,######0.000000") & " x " & VB6.Format(idblTarDemanda_fp, "#,##0.00") & " )"
                            Else
                                vlrKvarh_Demanda_fp = 0
                                lstrDescKVarh_demanda_fp = ""
                            End If
                        End If
                        End If 'iintTipoTarifa
                        'Grava os resultados do reativo
                        lblnReativoNegativo = False
                        If vlrKvarh_Consumo_p < 0 Then lblnReativoNegativo = True
                        If vlrKvarh_Consumo_p > 0 Then
                            AdicionaGridItem(row_grid, "0302020013", codTodescri("0302020013"), Kvarh_P, vlrKvarh_Consumo_p, "( " & Truncate(Kvarh_P, 6) & " x " & Arredondar(idblTarTe_B1, 5) & " )", "S")
                            '
                            'Tributação
                            If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                                ldbl_Per_Des_SP = 0.85
                            Else
                                ldbl_Per_Des_SP = 1
                            End If

                            ldblTotalVrlItens = ldblTotalVrlItens + vlrKvarh_Consumo_p

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(12) = Arredondar(vlrKvarh_Consumo_p * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(12) = idbl_Ite_Pic(12)
                            '
                            idbl_Bas_Pic(12) = Arredondar(idbl_Ite_Pic(12) / coefTribSIcms, 2)
                            idbl_Bas_Icm(12) = Arredondar(idbl_Bas_Pic(12) / (1 - (idblAliqICMS / 100)), 2)
                            idbl_Vlr_Pis(12) = Arredondar(idbl_Bas_Pic(12) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(12) = Arredondar(idbl_Bas_Pic(12) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(12) = Arredondar(idbl_Bas_Icm(12) * (idblAliqICMS / 100), 2)
                            '
                            idbl_Ret_Con(12) = idbl_Bas_Icm(12)
                            idbl_Ret_Dem(12) = 0
                            '
                            'Totaliza e coloca os itens de quantidade
                            vlrTotal = vlrTotal + vlrKvarh_Consumo_p
                            '
                            Item_Fatura = Trim(Item_Fatura & "0302010013?" & Replace(CStr(Kvarh_P), ",", ".") & ";") 'kvarh Ponta
                        End If
                        If vlrKvarh_Consumo_fp < 0 Then lblnReativoNegativo = True
                        If vlrKvarh_Consumo_fp > 0 Then
                            AdicionaGridItem(row_grid, "0302020014", codTodescri("0302020014"), Kvarh_fp, vlrKvarh_Consumo_fp, "( " & Truncate(Kvarh_fp, 6) & " x " & Arredondar(idblTarTe_B1, 5) & " )", "S")
                            '
                            'Tributação
                            If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                                ldbl_Per_Des_SP = 0.85
                            Else
                                ldbl_Per_Des_SP = 1
                            End If

                            ldblTotalVrlItens = ldblTotalVrlItens + vlrKvarh_Consumo_fp

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(13) = Arredondar(vlrKvarh_Consumo_fp * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(13) = idbl_Ite_Pic(13)
                            '
                            idbl_Bas_Pic(13) = Arredondar(idbl_Ite_Pic(13) / coefTribSIcms, 2)
                            idbl_Bas_Icm(13) = Arredondar(idbl_Bas_Pic(13) / (1 - (idblAliqICMS / 100)), 2)
                            idbl_Vlr_Pis(13) = Arredondar(idbl_Bas_Pic(13) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(13) = Arredondar(idbl_Bas_Pic(13) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(13) = Arredondar(idbl_Bas_Icm(13) * (idblAliqICMS / 100), 2)
                            '
                            idbl_Ret_Con(13) = idbl_Bas_Icm(13)
                            idbl_Ret_Dem(13) = 0
                            '
                            'Totaliza e coloca os itens de quantidade
                            vlrTotal = vlrTotal + vlrKvarh_Consumo_fp
                            '
                            Item_Fatura = Trim(Item_Fatura & "0302010014?" & Replace(CStr(Kvarh_fp), ",", ".") & ";") 'kvarh f Ponta
                        End If
                        '
                        consTotal = consTotal + (Kvarh_P + Kvarh_fp)
                        '
                        If vlrKvarh_Demanda_p < 0 Then lblnReativoNegativo = True
                        If vlrKvarh_Demanda_p > 0 Then
                            AdicionaGridItem(row_grid, "0302020027", codTodescri("0302020027"), ldblDemaAuxP, vlrKvarh_Demanda_p, lstrDescKVarh_demanda_p, "S")
                            '
                            'Tributação
                            If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                                ldbl_Per_Des_SP = 0.85
                            Else
                                ldbl_Per_Des_SP = 1
                            End If
                            If isento_demanda = "N" Then

                                ldblTotalVrlItens = ldblTotalVrlItens + vlrKvarh_Demanda_p

                                '
                                'em 01/05/2021
                                idbl_Ite_Pic(14) = Arredondar(vlrKvarh_Demanda_p * ldbl_Per_Des_SP, 2)
                                idbl_Ite_Icm(14) = idbl_Ite_Pic(14)
                                '
                                idbl_Bas_Pic(14) = Arredondar(idbl_Ite_Pic(14) / coefTribSIcms, 2)
                                idbl_Bas_Icm(14) = Arredondar(idbl_Bas_Pic(14) / (1 - (idblAliqICMS / 100)), 2)
                                idbl_Vlr_Pis(14) = Arredondar(idbl_Bas_Pic(14) * (idblAliqPIS / 100), 2)
                                idbl_Vlr_Cof(14) = Arredondar(idbl_Bas_Pic(14) * (idblAliqCofins / 100), 2)
                                idbl_Vlr_Icm(14) = Arredondar(idbl_Bas_Icm(14) * (idblAliqICMS / 100), 2)
                                '
                                idbl_Ret_Con(14) = 0
                                idbl_Ret_Dem(14) = idbl_Bas_Icm(14)
                            Else

                                ldblTotalVrlItens = ldblTotalVrlItens + vlrKvarh_Demanda_p

                                '
                                'em 01/05/2021
                                idbl_Ite_Pic(14) = Arredondar(vlrKvarh_Demanda_p * 0.85, 2)
                                idbl_Ite_Icm(14) = idbl_Ite_Pic(14)
                                '
                                idbl_Bas_Pic(14) = Arredondar(idbl_Ite_Pic(14) / coefTribSIcms, 2)
                                idbl_Bas_Icm(14) = 0
                            idbl_Vlr_Pis(14) = Arredondar(idbl_Bas_Pic(14) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(14) = Arredondar(idbl_Bas_Pic(14) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(14) = 0
                            '
                            idbl_Ret_Con(14) = 0
                            idbl_Ret_Dem(14) = idbl_Bas_Pic(14)
                        End If
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrKvarh_Demanda_p
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010027?" & Replace(CStr(dblDemReatAux - auxdemanda), ",", ".") & ";") 'demanda reativa Ponta
                    End If
                    If vlrKvarh_Demanda_fp < 0 Then lblnReativoNegativo = True
                    If vlrKvarh_Demanda_fp > 0 Then
                        AdicionaGridItem(row_grid, "0302020028", codTodescri("0302020028"), ldblDemaAuxFP, vlrKvarh_Demanda_fp, lstrDescKVarh_demanda_fp, "S")
                        '
                        'Tributação
                        If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                            ldbl_Per_Des_SP = 0.85
                        Else
                            ldbl_Per_Des_SP = 1
                        End If
                        If isento_demanda = "N" Then

                            ldblTotalVrlItens = ldblTotalVrlItens + vlrKvarh_Demanda_fp

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(15) = Arredondar(vlrKvarh_Demanda_fp * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(15) = idbl_Ite_Pic(15)
                            '
                            idbl_Bas_Pic(15) = Arredondar(idbl_Ite_Pic(15) / coefTribSIcms, 2)
                            idbl_Bas_Icm(15) = Arredondar(idbl_Bas_Pic(15) / (1 - (idblAliqICMS / 100)), 2)
                            idbl_Vlr_Pis(15) = Arredondar(idbl_Bas_Pic(15) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(15) = Arredondar(idbl_Bas_Pic(15) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(15) = Arredondar(idbl_Bas_Icm(15) * (idblAliqICMS / 100), 2)
                            '
                            idbl_Ret_Con(15) = 0
                            idbl_Ret_Dem(15) = idbl_Bas_Icm(15)
                        Else

                            ldblTotalVrlItens = ldblTotalVrlItens + vlrKvarh_Demanda_fp

                            '
                            'em 01/05/2021
                            idbl_Ite_Pic(15) = Arredondar(vlrKvarh_Demanda_fp * ldbl_Per_Des_SP, 2)
                            idbl_Ite_Icm(15) = idbl_Ite_Pic(15)
                            '
                            idbl_Bas_Pic(15) = Arredondar(idbl_Ite_Pic(15) / coefTribSIcms, 2)
                            idbl_Bas_Icm(15) = 0
                            idbl_Vlr_Pis(15) = Arredondar(idbl_Bas_Pic(15) * (idblAliqPIS / 100), 2)
                            idbl_Vlr_Cof(15) = Arredondar(idbl_Bas_Pic(15) * (idblAliqCofins / 100), 2)
                            idbl_Vlr_Icm(15) = 0
                            '
                            idbl_Ret_Con(15) = 0
                            idbl_Ret_Dem(15) = idbl_Bas_Pic(15)
                        End If
                        '
                        'Totaliza e coloca os itens de quantidade
                        vlrTotal = vlrTotal + vlrKvarh_Demanda_fp
                        '
                        Item_Fatura = Trim(Item_Fatura & "0302010028?" & Replace(CStr(dblDemReatAux - auxdemanda), ",", ".") & ";") 'demanda reativa Ponta
                    End If
                End If 'lblnCobrarReativo
                '----- desconto consumidor rural -----
                If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                    AdicionaGridItem(row_grid, "9070000002", codTodescri("9070000002"), 0, (vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlr_Demanda_Dif_Cont_P + vlr_Demanda_Dif_Cont_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.1, " (10%)", "S")
                    '
                    vlrTotal = vlrTotal - CDbl(VB6.Format((vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlr_Demanda_Dif_Cont_P + vlr_Demanda_Dif_Cont_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.1, "#,##0.00"))
                End If
                '----- desconto 15% para o serviço público -----
                If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) = 7 Then
                    AdicionaGridItem(row_grid, "9070000001", codTodescri("9070000001"), 0, (vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlr_Demanda_Dif_Cont_P + vlr_Demanda_Dif_Cont_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.15, "(15%)", "S")
                    vlrTotal = vlrTotal - CDbl(VB6.Format((vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlr_Demanda_Dif_Cont_P + vlr_Demanda_Dif_Cont_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.15, "#,##0.00"))
                End If
                '
                If gstrEmpresa_Sigla = "EFLUL" Or gstrEmpresa_Sigla = "CERCI" Then
                    'somente livres
                    If Me.txtTA.Text = "01AL00" Then
                        If lblnIcms_Demada_Lida = False Then
                            'Arlindo 02/03
                            If ccee_titul_anterior = "S" Then
                                CobrarDescontoProvisorio(lstrZona, lstrLivro, lstrConta, 0, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrDemanda_P + vlr_Demanda_Dif_Cont_P, vlrDemanda_FP + vlr_Demanda_Dif_Cont_FP, 0, 0, 0, Truncate(IIf((iblnParCativo And iintLivreVerde = -1), (consumo_p - ldblParCatConsumoPonta), IIf(iintLivreVerde = -1, consumo_p, 0)) * (IIf((iblnParCativo And iintLivreVerde = -1), idblTarConsumoLiv_p, idblTarConsumo_p) - IIf((iblnParCativo And iintLivreVerde = -1), idblTarConsumoLiv_fp, idblTarConsumo_fp)), 2), 0, vlr_Demanda_Dif_Cont_FP, consumo_p, 0, 0)
                            Else
                                'CobrarDescontoProvisorio(lstrZona, lstrLivro, lstrConta, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrDemanda_P + vlr_Demanda_Dif_Cont_P, vlrDemanda_FP + vlr_Demanda_Dif_Cont_FP, 0, 0, 0, Truncate(IIf((iblnParCativo And iintLivreVerde = -1), (consumo_p - ldblParCatConsumoPonta), IIf(iintLivreVerde = -1, consumo_p, 0)) * (IIf((iblnParCativo And iintLivreVerde = -1), idblTarConsumoLiv_p, idblTarConsumo_p) - IIf((iblnParCativo And iintLivreVerde = -1), idblTarConsumoLiv_fp, idblTarConsumo_fp)), 2), 0)
                                CobrarDescontoProvisorio(lstrZona, lstrLivro, lstrConta, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrDemanda_P, vlrDemanda_FP, 0, 0, 0, vlrConsumo_P, vlrConsumo_FP, vlr_Demanda_Dif_Cont_FP, consumo_p, ldblDemandaContratadaForaPonta, idblTarDemanda_fp)
                            End If
                        Else
                            'Arlindo 02/03
                            If ccee_titul_anterior = "S" Then
                                CobrarDescontoProvisorio(lstrZona, lstrLivro, lstrConta, 0, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrDemanda_P + vlr_Demanda_Dif_Cont_P, vlrDemanda_FP + vlr_Demanda_Dif_Cont_FP, Truncate(Demanda_Lida_P * idblTarDemanda_p, 2), Truncate(Demanda_Lida_FP * idblTarDemanda_fp, 2), baseICMSisenta, Truncate(IIf((iblnParCativo And iintLivreVerde = 1), (consumo_p - ldblParCatConsumoPonta), IIf(iintLivreVerde = 1, consumo_p, 0)) * (IIf((iblnParCativo And iintLivreVerde = 1), idblTarConsumoLiv_p, idblTarConsumo_p) - IIf((iblnParCativo And iintLivreVerde = 1), idblTarConsumoLiv_fp, idblTarConsumo_fp)), 2), 0, vlr_Demanda_Dif_Cont_FP, consumo_p, 0, 0)
                            Else
                                'Alterado a chamada da rotina de calculo em 06/05/2020 por Ricardo pois a parte do consumo quando for parc.cativo e livre verde com icms na demanda lida estava desatualizada
                                CobrarDescontoProvisorio(lstrZona, lstrLivro, lstrConta, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrDemanda_P + vlr_Demanda_Dif_Cont_P, vlrDemanda_FP + vlr_Demanda_Dif_Cont_FP, Truncate(Demanda_Lida_P * idblTarDemanda_p, 2), Truncate(Demanda_Lida_FP * idblTarDemanda_fp, 2), baseICMSisenta, Truncate(IIf((iblnParCativo And iintLivreVerde = 1), (consumo_p - ldblParCatConsumoPonta), IIf(iintLivreVerde = 1, consumo_p, 0)) * (IIf((iblnParCativo And iintLivreVerde = 1), idblTarConsumoLiv_p, idblTarConsumo_p) - IIf((iblnParCativo And iintLivreVerde = 1), idblTarConsumoLiv_fp, idblTarConsumo_fp)), 2), 0, vlr_Demanda_Dif_Cont_FP, consumo_p, 0, 0)
                            End If
                            'Comentado em 06/05/2020 por Ricardo pois a parte do consumo quando for parc.cativo e livre verde estava desatualizada
                            ' CobrarDescontoProvisorio(lstrZona, lstrLivro, lstrConta, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrDemanda_P, vlrDemanda_FP, Truncate(Demanda_Lida_P * idblTarDemanda_p, 2), Truncate(Demanda_Lida_FP * idblTarDemanda_fp, 2), baseICMSisenta, Truncate(IIf(iintLivreVerde = 1, consumo_p, 0) * (idblTarConsumo_p - idblTarConsumo_fp), 2), 0)
                        End If
                    End If
                End If
                ' CobraDevoConDemRea(row_grid, vlrTotal, coefTribIcms, lstrUf)
                'basePisCofins = Truncate(BaseICMS + baseICMSisenta, 2)
                '
                'alterado em 28/04/2021 - Ricardo - Novo calculo de tributação
                idblBasePisCofins = 0
                BaseICMS = 0
                baseICMSisenta = 0
                ldbl_Ajuste_Vlr_Trib_P = 0
                ldbl_Ajuste_Vlr_Trib_C = 0
                ldbl_Ajuste_Vlr_Trib = 0
                vlrPis = 0
                vlrCofins = 0
                ICMS = 0
                baseRetCons = 0
                baseRetDem = 0

                'BaseICMS = Arredondar((ldblTotalVrlItens / coefTribSIcms), 2)
                'ICMS = Arredondar((BaseICMS * idblAliqICMS) / 100, 2)

                For lint_Aux_Trib = LBound(idbl_Ite_Pic) To UBound(idbl_Ite_Pic)
                    idblBasePisCofins = idblBasePisCofins + idbl_Bas_Pic(lint_Aux_Trib)

                    If gstrEmpresa_Sigla = "CERIS" Then
                        BaseICMS = Arredondar((ldblTotalVrlItens / coefTribSIcms), 2)
                    Else
                        BaseICMS = BaseICMS + idbl_Bas_Icm(lint_Aux_Trib)
                    End If

                    vlrPis = vlrPis + idbl_Vlr_Pis(lint_Aux_Trib)
                    vlrCofins = vlrCofins + idbl_Vlr_Cof(lint_Aux_Trib)

                    If gstrEmpresa_Sigla = "CERIS" Then
                        ICMS = Arredondar((BaseICMS * idblAliqICMS) / 100, 2)
                    Else
                        ICMS = ICMS + idbl_Vlr_Icm(lint_Aux_Trib)
                    End If

                    ldbl_Ajuste_Vlr_Trib_P = ldbl_Ajuste_Vlr_Trib_P + idbl_Ite_Pic(lint_Aux_Trib)
                    ldbl_Ajuste_Vlr_Trib_C = ldbl_Ajuste_Vlr_Trib_C + idbl_Ite_Pic(lint_Aux_Trib)
                    ldbl_Ajuste_Vlr_Trib = ldbl_Ajuste_Vlr_Trib + idbl_Ite_Icm(lint_Aux_Trib)
                    baseRetCons = baseRetCons + idbl_Ret_Con(lint_Aux_Trib)
                    baseRetDem = baseRetDem + idbl_Ret_Dem(lint_Aux_Trib)
                Next
                'baseICMSisenta = baseICMSisenta + idbl_Vlr_Pis(7) + idbl_Vlr_Cof(7) + idbl_Vlr_Pis(10) + idbl_Vlr_Cof(10)
                BasePis = idblBasePisCofins
                    BaseCofins = idblBasePisCofins
                    Me.txtBaseTributacao.Text = CStr(BaseICMS)
                    If IsNumeric(Me.txtBaseTributacao.Text) Then
                        If CDbl(Me.txtBaseTributacao.Text) < 0 Then
                            Me.txtBaseTributacao.ForeColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                        Else
                            Me.txtBaseTributacao.ForeColor = System.Drawing.ColorTranslator.FromOle(&H80000008)
                        End If
                    End If
                    '
                    '----- Pis ---------------------------------------------------------------------------------------------
                    If vlrPis > 0 Then
                        AdicionaGridItem(row_grid, "0302020029", codTodescri("0302020029") & " ( " & VB6.Format(idblAliqPIS, "#,#####0.00000") & "% )", BasePis, vlrPis, "", "S")
                        '
                        vlrPis = Truncate(vlrPis, 2)

                        vlrTotal = vlrTotal + vlrPis
                        Item_Fatura = Trim(Item_Fatura & "0302020033?" & Replace(CStr(BasePis), ",", ".") & ";") ' Base de Pis
                    End If
                    '----- Cofins ------------------------------------------------------------------------------------------
                    If vlrCofins > 0 Then
                        AdicionaGridItem(row_grid, "0302020030", codTodescri("0302020030") & " ( " & VB6.Format(idblAliqCofins, "#,#####0.00000") & "% )", BaseCofins, vlrCofins, "", "S")
                        '
                        vlrTotal = vlrTotal + vlrCofins
                        Item_Fatura = Trim(Item_Fatura & "0302020034?" & Replace(CStr(BaseCofins), ",", ".") & ";") ' Base de Cofins
                    End If
                    '-- ICMS
                    If ICMS > 0 Then
                        AdicionaGridItem(row_grid, "0302030009", codTodescri("0302030009") & " ( " & VB6.Format(idblAliqICMS, "#,#####0.00000") & "% )", BaseICMS, ICMS, "", "S")
                        '
                        vlrTotal = vlrTotal + ICMS
                    End If
                    Me.txtBaseTributacao.Text = VB6.Format(BaseICMS, "#,##0.00")
                    '
                    CobraDevolveValorDiferencaTributacao(row_grid, vlrTotal)
                    '-----------------------------------------------------------------
                    If gstrEmpresa_Sigla = "CHESP" Then
                        CobrarSobreTaxa(vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
                    End If
                    If gstrEmpresa_Sigla = "EFLUL" Then
                        CobrarSobreTaxaEflul(lstrZona, lstrLivro, lstrConta, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
                    End If
                    CobrarParcelamento(lstrZona, lstrLivro, lstrConta, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
                    CobrarConvenios(vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms, coefTribSIcms)
                    CobrarTaxas(vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
                    '-----------------------------------------------------------------
                    '-- Iluminação
                    If strIsentIlum = "S" Then
                    TpConsumo = GetValorTabela("cip", "tpcons", "cidade = " & llngCodigoCidade, "N") 'lrstAux!tpcons
                    TpFaixaC = GetValorTabela("cip", "tpfaixa", "cidade = " & llngCodigoCidade, "N") 'lrstAux!tpfaixa
                    'lstrSql = "Select * FROM " & "`cip` WHERE (CIDADE)=" & llngCodigoCidade & " "
                    ' Conectar(lstrSql, lrstAux)
                    'If lrstAux.RecordCount > 0 Then
                    '  TpConsumo = lrstAux!tpcons
                    '  TpFaixaC = lrstAux!tpfaixa
                    'Else
                    '  TpConsumo = "N"
                    '  TpFaixaC = "N"
                    'End If
                    ' lrstAux.Close
                    Ilum = Arredondar(Calc_ILUM_Horo(llngCodigoCidade, istrClasse, consumo_p, consumo_fp, Demanda_Faturada_P, Demanda_Faturada_FP, Dem_Ultrapassagem_P, Dem_Ultrapassagem_FP, TpFaixaC, idblTarConsumo_p, idblTarConsumo_fp), 2)
                        If Ilum > 0 Then
                            AdicionaGridItem(row_grid, "0301000003", codTodescri("0301000003"), (consumo_p + consumo_fp), Ilum, "", "S")
                            '
                            vlrTotal = vlrTotal + CDbl(VB6.Format(Ilum, "#,##0.00"))
                        End If
                    End If
                '***********************************************************
                'jogar essas variaveis de base de rentenção para cima
                'Retenção Tributária
                If Mid(istrClasse, 1, 2) = "63" Then
                    'baseRetCons = Truncate(vlrConsumoPT + vlrConsumoPTBan + vlrConsumoFPT + vlrConsumoFPTBan + vlrConsReatPT + vlrConsReatFPT + vlrConsCapFPT, 2)
                    'baseRetDem = Truncate(vlrDemandaPT + vlrDemandaFPT + vlrDemUltraPT + vlrDemUltraFPT + vlrDemReatPT + vlrDemReatFPT, 2)
                    'baseRetCons = Truncate((baseRetCons / (1 - (idblAliqICMS / 100))), 2)
                    'baseRetDem = Truncate((baseRetDem / (1 - (idblAliqICMS / 100))), 2)
                    '     base_retencao = Truncate(baseRetCons + baseRetDem, 2)
                    '      baseRetCons = 0
                    '      baseRetDem = 0
                    vlrLiqui = 0
                    'retencao pis
                    retPis = 0.65 / 100
                    'vlrRetPis = Arredondar(baseRetCons * retPis, 2)
                    vlrRetPis = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retPis, 2)
                    If vlrRetPis > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000001"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO PIS CONSUMO"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "0.65%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetPis, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetPis, "#,##0.00"))
                    End If
                    'retencao cofins
                    retCofins = 3 / 100
                    'vlrRetCofins = Arredondar(baseRetCons * retCofins, 2)
                    vlrRetCofins = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retCofins, 2)
                    If vlrRetCofins > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000002"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO COFINS CONSUMO"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "3%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetCofins, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetCofins, "#,##0.00"))
                    End If
                    'retencao csll
                    retCsll = 1 / 100
                    'vlrRetCsll = Arredondar(baseRetCons * retCsll, 2)
                    vlrRetCsll = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retCsll, 2)
                    If vlrRetCsll > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000003"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO CSLL CONSUMO"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "1%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetCsll, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetCsll, "#,##0.00"))
                    End If
                    'retencao IR consumo
                    retIRCons = 1.2 / 100
                    'vlrRetIRCons = Arredondar(baseRetCons * retIRCons, 2)
                    vlrRetIRCons = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retIRCons, 2)
                    If vlrRetIRCons > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000004"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO IRPJ CONSUMO"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "1,2%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetIRCons, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetIRCons, "#,##0.00"))
                    End If
                    'retencao demanda
                    retIRDem = 4.8 / 100
                    'vlrRetIRDem = Arredondar(baseRetDem * retIRDem, 2)
                    vlrRetIRDem = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retIRDem, 2)
                    If vlrRetIRDem > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000005"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO IRPJ DEMANDA"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "4,8%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetIRDem, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetIRDem, "#,##0.00"))
                    End If
                    'retencao csll
                    retCsll = 1 / 100
                    'vlrRetCsll = Arredondar(baseRetDem * retCsll, 2)
                    vlrRetCsll = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retCsll, 2)
                    If vlrRetCsll > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000006"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO CSLL DEMANDA"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "1%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetCsll, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetCsll, "#,##0.00"))
                    End If
                    'retencao cofins
                    retCofins = 3 / 100
                    'vlrRetCofins = Arredondar(baseRetDem * retCofins, 2)
                    vlrRetCofins = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retCofins, 2)
                    If vlrRetCofins > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000007"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO COFINS DEMANDA"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "3%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetCofins, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetCofins, "#,##0.00"))
                    End If
                    'retencao pis
                    retPis = 0.65 / 100
                    'vlrRetPis = Arredondar(baseRetDem * retPis, 2)
                    vlrRetPis = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retPis, 2)
                    If vlrRetPis > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000008"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO PIS DEMANDA"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "0.65%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetPis, "#,##0.00")
                        vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetPis, "#,##0.00"))
                    End If
                End If

                If Mid(istrClasse, 1, 2) = "61" Or Mid(istrClasse, 1, 2) = "62" Then
                    'retencao IR consumo
                    retIRCons = 1.2 / 100
                    'vlrRetIRCons = Arredondar(baseRetCons * retIRCons, 2)
                    vlrRetIRCons = Arredondar(ldbl_Ajuste_Vlr_Trib_P * retIRCons, 2)
                    If vlrRetIRCons > 0 Then
                        row_grid = 1 + row_grid
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9090000004"
                        grid_fatura.Col = 1
                        grid_fatura.Text = "RETENÇÃO IRPJ CONSUMO"
                        grid_fatura.Col = 2
                        grid_fatura.Text = "1,2%"
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(vlrRetIRCons, "#,##0.00")
                        'vlrLiqui = vlrLiqui - CDbl(VB6.Format(vlrRetIRCons, "#,##0.00"))
                        vlrTotal = vlrTotal - CDbl(VB6.Format(vlrRetIRCons, "#,##0.00"))
                    End If
                End If
                'Fim da retencao
                '***********************************************************
                'MULTA/JUROS/CORRECAO MONETARIA
                'IMPORTANTE: O SISTEMA SÓ DEVE CALCULAR MULTA DO MES
                'ANTERIOR APENAS, OU SEJA, MES FATURAMENTO = 01/2007,
                'SÓ VAI CALCULAR MULTA E JUROS DO MES 12/2006, SE HOUVER.

                'verifa se ja foi calculado alguma multa para o mes em faturamento
                VerDelMultaJuro(lstrZona, lstrLivro, lstrConta)
                    If CShort(Microsoft.VisualBasic.Left(istrClasse, 1)) <> 6 Then
                        dtDataFat = CDate(VB6.Format("01/" & txtMesAno.Text, "dd/mm/yyyy"))
                        dtDataRefMulta = System.DateTime.FromOADate(dtDataFat.ToOADate - 1)
                        strMesRefMulta = VB6.Format(dtDataRefMulta, "mm/yyyy")
                        CalculaMultaJuros(lstrZona, lstrLivro, lstrConta, strMesRefMulta)

                        lstrSql = "Select * " & "  FROM " & "`multajuros` " & " WHERE isento = 0 " & "   And zona = '" & lstrZona & "' " & "   AND livro = '" & lstrLivro & "' " & "   AND conta = '" & lstrConta & "' " & "   AND (cobrado = 'N' OR (cobrado = 'S' and mesano_fatur = '" & strMesRefMulta & "'));"

                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                        dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                        If dt.Rows.Count <> 0 Then

                            For Each row As DataRow In dt.Rows

                                'Multa
                                If row("vlrMulta") > 0 Then
                                    row_grid = 1 + row_grid
                                    grid_fatura.Rows = row_grid + 1
                                    grid_fatura.Row = row_grid
                                    grid_fatura.Col = 0
                                    grid_fatura.Text = "9080000061"
                                    grid_fatura.Col = 1
                                    grid_fatura.Text = codTodescri("9080000061") & " REF. MÊS " & row("mesano")
                                    grid_fatura.Col = 2
                                    grid_fatura.Text = ""
                                    grid_fatura.Col = 3
                                    grid_fatura.Text = VB6.Format(row("vlrMulta"), "#,##0.00")
                                    grid_fatura.Col = 4
                                    grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                                    'grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                                    vlrTotal = vlrTotal + CDbl(VB6.Format(row("vlrMulta"), "#,##0.00"))
                                End If
                                'Juros
                                If row("vlrJuros") > 0 Then
                                    row_grid = 1 + row_grid
                                    grid_fatura.Rows = row_grid + 1
                                    grid_fatura.Row = row_grid
                                    grid_fatura.Col = 0
                                    grid_fatura.Text = "9080000066"
                                    grid_fatura.Col = 1
                                    grid_fatura.Text = codTodescri("9080000066") & " REF. MÊS " & row("mesano")
                                    grid_fatura.Col = 2
                                    grid_fatura.Text = ""
                                    grid_fatura.Col = 3
                                    grid_fatura.Text = VB6.Format(row("vlrJuros"), "#,##0.00")
                                    grid_fatura.Col = 4
                                    grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                                    'grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                                    vlrTotal = vlrTotal + CDbl(VB6.Format(row("vlrJuros"), "#,##0.00"))
                                End If

                            'Correção monetária
                            If row("vlrCM") > 0 Then
                                row_grid = 1 + row_grid
                                grid_fatura.Rows = row_grid + 1
                                grid_fatura.Row = row_grid
                                grid_fatura.Col = 0
                                grid_fatura.Text = "9080000067"
                                grid_fatura.Col = 1
                                grid_fatura.Text = codTodescri("9080000067") & " REF. MÊS " & row("mesano")
                                grid_fatura.Col = 2
                                grid_fatura.Text = ""
                                grid_fatura.Col = 3
                                grid_fatura.Text = VB6.Format(row("vlrCM"), "#,##0.00")
                                grid_fatura.Col = 4
                                grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                                'grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                                vlrTotal = vlrTotal + CDbl(VB6.Format(row("vlrCM"), "#,##0.00"))
                            End If

                        Next

                            'Passa o flag de COBRADO para S.
                            'Depois temos que pensar num jeito de jogar esse cobrado
                            'pra N se a nota for refaturada.
                            lstrSql = "update " & "`multajuros` set cobrado = 'S' where zona = '" & lstrZona & "' and livro = '" & lstrLivro & "' and conta = '" & lstrConta & "';"
                            objAtualizaBancoDados.QUERY_NAME = lstrSql
                            repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                        End If


                    End If
                    '
                    Item_Fatura = Trim(Item_Fatura & "40PIS00001?" & Replace(CStr(idblAliqPIS), ",", ".") & ";")
                    Item_Fatura = Trim(Item_Fatura & "40COF00001?" & Replace(CStr(idblAliqCofins), ",", ".") & ";")
                    Item_Fatura = Trim(Item_Fatura & "0302030001?" & Replace(CStr(BaseICMS), ",", ".") & ";")
                    Item_Fatura = Trim(Item_Fatura & "0302030002?" & Replace(CStr(idblAliqICMS), ",", ".") & ";")
                    '----- Cálculo do arredondamento -----------------------------
                    If GetConfig("arredondar.total.nf") = "S" And vlrTotal > 0 Then
                        Arredondamento(vlrTotal, idblUnidId)
                    End If
                '-------------------------------------------------------------
                If Mid(txtTA.Text, 1, 4) = "01AL" Then
                    CalculaIcmsComercializador(vlrTotal, row_grid)
                End If

                lblTotal.Text = VB6.Format(vlrTotal, "#,##0.00")
                lblTotalLiq.Text = VB6.Format(vlrTotal + vlrLiqui, "#,##0.00")

                '
                grid_fatura.Redraw = True
                If lblnCobrarReativo And lblnReativoNegativo Then
                    MsgBox("Problema no calculo do reativo, favor verificar!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
                End If
            Else
                    If Trim(lstr_Msg_Continua) <> "" Then
            MsgBox(lstr_Msg_Continua, MsgBoxStyle.Critical, "Mensagem do Sistema")
        End If
        End If


        Catch ex As Exception
        Exit Sub
        End Try

    End Sub

    Private Function Valida_Periodo_Teste(ByVal adteIni As Date, ByVal adteFim As Date, ByVal adblDemContr_Antes_P As Double, ByVal adblDemContr_Antes_FP As Double, ByVal adblDemContr_Atual_P As Double, ByVal adblDemContr_Atual_FP As Double) As Boolean

        Dim lbln_Retorno As Boolean


        Try

            lbln_Retorno = True
            Me.txt_Periodo_Teste.Text = "Sim - De: " & VB6.Format(adteIni, "MM/yyyy") & " Até: " & VB6.Format(adteFim, "MM/yyyy")
            If adblDemContr_Atual_P > 0 Then
                If adblDemContr_Antes_P = 0 Then
                    Me.txt_Msg_Periodo_Teste.Text = "Erro Demanda Ponta! Revise."
                    Me.txt_Msg_Periodo_Teste.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    lbln_Retorno = False
                End If
            End If
            If adblDemContr_Atual_FP > 0 Then
                If adblDemContr_Antes_FP = 0 Then
                    Me.txt_Msg_Periodo_Teste.Text = "Erro Demanda Fora Ponta! Revise."
                    Me.txt_Msg_Periodo_Teste.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    lbln_Retorno = False
                End If
            End If

            If CInt(VB6.Format(adteFim, "yyyyMM")) < CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) Then
                Me.txt_Msg_Periodo_Teste.Text = "Teste Vencido!, Revise"
                Me.txt_Msg_Periodo_Teste.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                lbln_Retorno = False
            End If
            Valida_Periodo_Teste = lbln_Retorno


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub FlexCores(ByVal afmeAux As AxMSFlexGridLib.AxMSFlexGrid, ByVal alngCorPar As Integer, ByVal alngCorImpar As Integer)

        Dim llngLinha As Integer


        Try

            With afmeAux
                .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillRepeat
                .Redraw = False
                For llngLinha = 1 To .Rows - 1
                    .Row = llngLinha
                    If EImpar(llngLinha) Then 'Se a linha for impar:
                        'Seleciona a partir da primeira coluna
                        .Col = 0
                        'Seleciona até a última coluna
                        .ColSel = .Cols - 1
                        'Aplica a cor
                        .CellBackColor = System.Drawing.ColorTranslator.FromOle(alngCorImpar)
                    Else 'Se a linha for par:
                        'Seleciona a partir da primeira coluna
                        .Col = 0
                        'Seleciona até a última coluna
                        .ColSel = .Cols - 1
                        'Aplica a cor
                        .CellBackColor = System.Drawing.ColorTranslator.FromOle(alngCorPar)
                    End If
                    '      If Val(IIf(IsNumeric(.TextMatrix(llngLinha, 17)), .TextMatrix(llngLinha, 17), 0)) > 0 Then
                    '        .FillStyle = flexFillSingle
                    '        If .TextMatrix(llngLinha, 16) = 1 Then
                    '          .Row = llngLinha
                    '          .Col = 11
                    '          .CellBackColor = &HFF&
                    '        Else
                    '          .Row = llngLinha
                    '          .Col = 11
                    '          .CellBackColor = &HFF00&
                    '        End If
                    '        .FillStyle = flexFillRepeat
                    '      End If
                Next llngLinha
                .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillSingle
                .Redraw = True
            End With
            System.Windows.Forms.Application.DoEvents()


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub AdicionaGridItem(ByRef row_grid As Short, ByVal astrCodigo As String, ByVal astrDescricao As String, ByVal adlbQuantidade As Double, ByVal adblValor As Double, ByVal astrReferecia As String, ByVal astrTotaliza As String)

        Dim lstrTipo As String


        Try

            If Microsoft.VisualBasic.Left(Trim(astrReferecia), 3) = "PIS" Or Microsoft.VisualBasic.Left(Trim(astrReferecia), 6) = "COFINS" Or Mid(astrCodigo, 3, 1) = "A" Then
                lstrTipo = "#,#####0.00000"
                astrReferecia = ""
            Else
                lstrTipo = "#,##0.00"
            End If
            With Me.grid_fatura
                row_grid = 1 + row_grid
                .Rows = row_grid + 1
                .Row = row_grid
                .Col = 0
                .Text = astrCodigo
                .Col = 1
                .Text = astrDescricao & astrReferecia
                .Col = 2
                If adlbQuantidade <> 0 Then
                    .Text = VB6.Format(adlbQuantidade, lstrTipo) 'Quantidade
                Else
                    .Text = ""
                End If
                '.Text = ""
                .Col = 3
                .Text = VB6.Format(adblValor, "#,##0.00") 'Valor
                .Col = 4
                .Text = astrReferecia
            End With


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub LimpaCamposFatGrupoA()



        Try


            idblNumNf = 0
            idblNsuNr = 0
            idblConsId = 0
            idblUnidId = 0
            istrClasse = ""
            istrQH = "N"
            istrNrBco = ""
            istrNmBco = ""
            istrCpfCnpj = ""
            istrInsEst = ""
            istrUF = ""
            istrTensao = ""
            istrFase = ""
            istrRota = ""
            idblCfop = 5.257
            iblnIcmsDemLida = False
            iblnParCativo = False
            iblnPeriodoTeste = False
            iintLivreEspecial = 0
            iintLivreVerde = 0
            '
            BaseICMS = 0
            BaseICMS2 = 0
            BasePis = 0
            BaseCofins = 0
            ICMS = 0
            ICMS2 = 0
            'Dados
            Me.txtNome.Text = ""
            Me.txtTA.Text = ""
            'Datas
            '  If Me.txtDt_Faturamento.Text = "" Then
            '    Me.txtDt_Faturamento.Text = ""
            '    Me.txtDt_Apresenta.Text = ""
            '    Me.txtDt_Leit_Atual.Text = ""
            '    Me.txtDt_Leit_Anterior.Text = ""
            '    Me.txtDt_Vencto.Text = ""
            '    Me.txtDt_Prox_Leit.Text = ""
            '  End If
            'Convencional
            Me.txtLeit_Consumo.Text = ""
            Me.txtLeit_Demanda.Text = ""
            Me.txtLeit_Kvarh.Text = ""
            'AutoProdutor
            Me.txt_Auto_Consumo.Text = ""
            Me.txt_Auto_Deficit_Dem.Text = ""
            Me.txt_Auto_Deficit_Dem_HI.Text = ""
            Me.txt_Auto_Dem_Supl.Text = ""
            'HoroSazonal
            Me.txtConsumo_p.Text = ""
            Me.txtConsumo_FP.Text = ""
            Me.txtDemanda_p.Text = ""
            Me.txtDemanda_FP.Text = ""
            Me.txtDem_Exc_Ponta.Text = ""
            Me.txtDem_Exc_FP.Text = ""
            Me.txtAjusteDemandaP.Text = ""
            Me.txtAjusteDemandaFP.Text = ""
            Me.txtKvarh_P.Text = ""
            Me.txtKvarh_FP.Text = ""
            'Livre Parcialmente Cativo
            Me.txtParCatHoras.Text = ""
            Me.txtParCatMWhMedio.Text = ""
            'Comercializadora
            Me.txtCCEEPrecoMedio.Text = ""
            Me.txtCCEEConsumoTotal.Text = ""
            Me.txtCCEEEnergiaComprada.Text = ""
            Me.txtCCEEBaseIntermediaria.Text = ""
            Me.txtCCEEIcmsIntermediario.Text = ""
            Me.txtCCEEBaseIcms.Text = ""
            Me.txtCCEEBasePisCof.Text = ""
            Me.txtCCEEAliquotaIcms.Text = ""
            Me.txtCCEEValorIcms.Text = ""
            Me.txtCCEEAliquotaPis.Text = ""
            Me.txtCCEEValorPis.Text = ""
            Me.txtCCEEAliquotaCofins.Text = ""
            Me.txtCCEEValorCofins.Text = ""
            'rever
            Me.txtReverso_p.Text = "0,00"
            Me.txtReverso_fp.Text = "0,00"
            Me.txtReverso_Residuo_p.Text = "0,00"
            Me.txtReverso_Residuo_fp.Text = "0,00"

            CarregaGridFatura()

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function ArrumaBaseIcms(ByVal astrItens As String, ByVal ablnIcmsDemandaLida As Boolean) As String

        Dim lstrItens As String
        Dim lstrAuxOld As String
        Dim lstrAuxNew As String
        Dim lintPosIni As Short
        Dim lintPosFim As Short
        'Convencional
        Dim ldblVCCons As Double
        Dim ldblVCDema As Double
        Dim ldblVCKwUl As Double
        Dim ldblVCUfer As Double
        Dim ldblVCDmcr As Double
        'Horo
        Dim ldblVHKwhP As Double
        Dim ldblVHKwhF As Double
        Dim ldblVHDemP As Double
        Dim ldblVHDemF As Double
        Dim ldblVHKwUP As Double
        Dim ldblVHKwUF As Double
        Dim ldblVHUfrP As Double
        Dim ldblVHUfrF As Double
        Dim ldblVHDmcP As Double
        Dim ldblVHDmcF As Double
        Dim ldblVDevoP As Double
        Dim ldblVDevoF As Double
        Dim ldblVUltrP As Double
        Dim ldblVUltrF As Double
        'Tributos
        Dim ldblVlrIc1 As Double
        Dim ldblVlrIc2 As Double
        Dim ldblVlrPis As Double
        Dim ldblVlrCof As Double
        'Bases
        Dim ldblTotBas As Double
        Dim ldblBasIc1 As Double
        Dim ldblBasIc2 As Double
        Dim ldblBasPis As Double
        Dim ldblBasCof As Double
        Dim ldblBNwIc1 As Double
        Dim ldblBNwIc2 As Double
        Dim ldblBNwPis As Double
        Dim ldblBNwCof As Double
        Dim ldblDifere As Double

        Dim ldblDescProv As Double
        Dim ldblDescReal As Double
        Dim ldblDevoDife As Double
        Dim ldblCobrDife As Double


        Try

            lstrItens = astrItens
            'Convencional(A4) e Suprimento(AS)
            ldblVCCons = BuscaVlrItem(lstrItens, "0302020009") + BuscaVlrItem(lstrItens, "0302120009")
            ldblVCDema = BuscaVlrItem(lstrItens, "0302020015")
            ldblVCKwUl = BuscaVlrItem(lstrItens, "0302020018")
            ldblVCUfer = BuscaVlrItem(lstrItens, "0302020012")
            ldblVCDmcr = BuscaVlrItem(lstrItens, "0302020031")
            'Horo Sazonal (AV,AA,AL)
            ldblVHKwhP = BuscaVlrItem(lstrItens, "0302020010") + BuscaVlrItem(lstrItens, "0302120010") + BuscaVlrItem(lstrItens, "0302020060")
            ldblVHKwhF = BuscaVlrItem(lstrItens, "0302020011") + BuscaVlrItem(lstrItens, "0302120011") + BuscaVlrItem(lstrItens, "0302020061")
            'ldblVHDemP = BuscaVlrItem(lstrItens, "0302020021")
            ldblVHDemP = BuscaVlrItem(lstrItens, "0302020021") '+ BuscaVlrItem(lstrItens, "0302060021")
            ldblVHDemF = BuscaVlrItem(lstrItens, "0302020023") + BuscaVlrItem(lstrItens, "0302020072")
            ldblVHKwUP = BuscaVlrItem(lstrItens, "0302020022")
            ldblVHKwUF = BuscaVlrItem(lstrItens, "0302020026")
            'Reativos
            ldblVHUfrP = BuscaVlrItem(lstrItens, "0302020013")
            ldblVHUfrF = BuscaVlrItem(lstrItens, "0302020014")
            ldblVHDmcP = BuscaVlrItem(lstrItens, "0302020027")
            ldblVHDmcF = BuscaVlrItem(lstrItens, "0302020028")
            'PLD
            ldblVDevoP = BuscaVlrItem(lstrItens, "0302020041")
            ldblVDevoF = BuscaVlrItem(lstrItens, "0302020042")
            ldblVUltrP = BuscaVlrItem(lstrItens, "0302020043")
            ldblVUltrF = BuscaVlrItem(lstrItens, "0302020044")
            'CCEE
            'Alterado pela portaria SEF 344/2019
            If CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) < glngPortaria_Sef_344_2019 Then
                ldblDescProv = (BuscaVlrItem(lstrItens, "0302020051") + BuscaVlrItem(lstrItens, "0302020055")) * (-1)
                ldblDescReal = (BuscaVlrItem(lstrItens, "0302020052") + BuscaVlrItem(lstrItens, "0302020056")) * (-1)
                ldblDevoDife = (BuscaVlrItem(lstrItens, "0302020053") + BuscaVlrItem(lstrItens, "0302020057")) * (-1)
                ldblCobrDife = (BuscaVlrItem(lstrItens, "0302020054") + BuscaVlrItem(lstrItens, "0302020058"))
            End If
            'Tributos
            ldblVlrIc1 = BuscaVlrItem(lstrItens, "0302030009")
            ldblVlrIc2 = BuscaVlrItem(lstrItens, "0302030010")
            ldblVlrPis = BuscaVlrItem(lstrItens, "0302020029")
            ldblVlrCof = BuscaVlrItem(lstrItens, "0302020030")
            'Bases
            ldblTotBas = ldblVCCons + ldblVCDema + ldblVCKwUl + ldblVCUfer + ldblVCDmcr + ldblVHKwhP + ldblVHKwhF + ldblVHDemP + ldblVHDemF + ldblVHKwUP + ldblVHKwUF + ldblVHUfrP + ldblVHUfrF + ldblVHDmcP + ldblVHDmcF + ldblVDevoP + ldblVDevoF + ldblVUltrP + ldblVUltrF + ldblVlrIc1 + ldblVlrIc2 + ldblVlrPis + ldblVlrCof + ldblDescProv + ldblDescReal + ldblDevoDife + ldblCobrDife
            ldblBasIc1 = BuscaVlrItem(lstrItens, "0302030001")
            ldblBasIc2 = BuscaVlrItem(lstrItens, "0302030003")
            ldblBasPis = BuscaVlrItem(lstrItens, "0302020033")
            ldblBasCof = BuscaVlrItem(lstrItens, "0302020034")
            If Not ablnIcmsDemandaLida Then
                ldblBNwIc1 = 0
                ldblBNwIc2 = 0
                ldblBNwPis = 0
                ldblBNwCof = 0
                If ldblBasIc2 > 0 Then
                    ldblDifere = Arredondar(ldblTotBas - (ldblBasIc1 + ldblBasIc2), 2)
                    ldblBNwIc2 = ldblBasIc2 + ldblDifere
                ElseIf ldblBasIc1 > 0 Then
                    ldblDifere = Arredondar(ldblTotBas - ldblBasIc1, 2)
                    ldblBNwIc1 = ldblBasIc1 + ldblDifere
                End If
                If ldblBasPis > 0 Then
                    ldblDifere = Arredondar(ldblTotBas - ldblBasPis, 2)
                    ldblBNwPis = ldblBasPis + ldblDifere
                End If
                If ldblBasCof > 0 Then
                    ldblDifere = Arredondar(ldblTotBas - ldblBasCof, 2)
                    ldblBNwCof = ldblBasCof + ldblDifere
                End If
                If ldblBNwIc1 > 0 Then
                    lintPosIni = InStr(1, lstrItens, "0302030001")
                    lintPosFim = InStr(lintPosIni, lstrItens, ";")
                    lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                    lstrAuxNew = "0302030001?" & Replace(Replace(CStr(ldblBNwIc1), ".", ""), ",", ".") & ";"
                    lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                End If
                If ldblBNwIc2 > 0 Then
                    lintPosIni = InStr(1, lstrItens, "0302030003")
                    lintPosFim = InStr(lintPosIni, lstrItens, ";")
                    lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                    lstrAuxNew = "0302030003?" & Replace(Replace(CStr(ldblBNwIc2), ".", ""), ",", ".") & ";"
                    lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                End If
                If ldblBNwPis > 0 Then
                    lintPosIni = InStr(1, lstrItens, "0302020033")
                    lintPosFim = InStr(lintPosIni, lstrItens, ";")
                    lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                    lstrAuxNew = "0302020033?" & Replace(Replace(CStr(ldblBNwPis), ".", ""), ",", ".") & ";"
                    lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                End If
                If ldblBNwCof > 0 Then
                    lintPosIni = InStr(1, lstrItens, "0302020034")
                    lintPosFim = InStr(lintPosIni, lstrItens, ";")
                    lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                    lstrAuxNew = "0302020034?" & Replace(Replace(CStr(ldblBNwCof), ".", ""), ",", ".") & ";"
                    lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                End If
            Else
                'Essa marreta é provisória somente para depois descobrir com mais calma em que parte do calculo qdo for livre e com demanda lida esta dando essa diferença
                '    If ldblTotBas <> (ldblBasIc1 + ldblBasIc2) Then
                '      If Arredondar((ldblTotBas - (ldblBasIc1 + ldblBasIc2)), 2) = 0.01 Then
                '        If ldblBasIc1 = ldblBasPis And ldblBasIc1 = ldblBasCof And ldblBasIc2 = 0 Then
                '          ldblBasIc1 = ldblBasIc1 + 0.01
                '          ldblBasPis = ldblBasPis + 0.01
                '          ldblBasCof = ldblBasCof + 0.01
                '          'icms
                '          lintPosIni = InStr(1, lstrItens, "0302030001")
                '          lintPosFim = InStr(lintPosIni, lstrItens, ";")
                '          lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                '          lstrAuxNew = "0302030001?" & Replace(Replace(ldblBasIc1, ".", ""), ",", ".") & ";"
                '          lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                '          'Pis
                '          lintPosIni = InStr(1, lstrItens, "0302020033")
                '          lintPosFim = InStr(lintPosIni, lstrItens, ";")
                '          lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                '          lstrAuxNew = "0302020033?" & Replace(Replace(ldblBasPis, ".", ""), ",", ".") & ";"
                '          lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                '          'Cofins
                '          lintPosIni = InStr(1, lstrItens, "0302020034")
                '          lintPosFim = InStr(lintPosIni, lstrItens, ";")
                '          lstrAuxOld = Mid(lstrItens, lintPosIni, (lintPosFim - lintPosIni) + 1)
                '          lstrAuxNew = "0302020034?" & Replace(Replace(ldblBasCof, ".", ""), ",", ".") & ";"
                '          lstrItens = Replace(lstrItens, lstrAuxOld, lstrAuxNew)
                '        End If
                '      End If
                '      If ldblTotBas <> (ldblBasIc1 + ldblBasIc2) Then
                '        '0302030030 VALOR DO DIFERIDO
                '        lstrItens = lstrItens & "0302030030?" & Replace(Arredondar((ldblTotBas - (ldblBasIc1 + ldblBasIc2)), 2), ".", "") & ";"
                '      End If
                '    End If
            End If
            ArrumaBaseIcms = lstrItens


        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Sub CalculaIcmsComercializador(ByRef ldblValorTotal As Double, ByRef aintRowGrid As Short)

        'Usado somente para consumidores livres
        Dim ldblValor As Double
        Dim ldblAIcms As Double
        Dim ldblAPis As Double
        Dim ldblACof As Double


        Try

            ldblAIcms = CDbl(IIf(IsNumeric(Me.txtCCEEAliquotaIcms.Text), Me.txtCCEEAliquotaIcms.Text, 0))
            ldblAPis = CDbl(IIf(IsNumeric(Me.txtCCEEAliquotaPis.Text), Me.txtCCEEAliquotaPis.Text, 0))
            ldblACof = CDbl(IIf(IsNumeric(Me.txtCCEEAliquotaCofins.Text), Me.txtCCEEAliquotaCofins.Text, 0))
            'Passo 1
            ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEEnergiaComprada.Text), Me.txtCCEEEnergiaComprada.Text, 0))
            Me.txtCCEEBaseIntermediaria.Text = VB6.Format(Arredondar(ldblValor / (1 - (ldblAIcms / 100)), 2), "#,##0.00")
            'Passo 2
            ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEBaseIntermediaria.Text), Me.txtCCEEBaseIntermediaria.Text, 0))
            Me.txtCCEEIcmsIntermediario.Text = VB6.Format(Arredondar(ldblValor * (ldblAIcms / 100), 2), "#,##0.00")
            'Passo 3
            ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEIcmsIntermediario.Text), Me.txtCCEEIcmsIntermediario.Text, 0))
            Me.txtCCEEBasePisCof.Text = VB6.Format(Arredondar(ldblValor / (1 - ((ldblAPis + ldblACof) / 100)), 2), "#,##0.00")
            'Passo 4
            ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0))
            Me.txtCCEEValorPis.Text = VB6.Format(Truncate(ldblValor * (ldblAPis / 100), 2), "#,##0.00")
            Me.txtCCEEValorCofins.Text = VB6.Format(Truncate(ldblValor * (ldblACof / 100), 2), "#,##0.00")
            'Passo 5
            ldblValor = 0
            ldblValor = ldblValor + CDbl(IIf(IsNumeric(Me.txtCCEEValorPis.Text), Me.txtCCEEValorPis.Text, 0))
            ldblValor = ldblValor + CDbl(IIf(IsNumeric(Me.txtCCEEValorCofins.Text), Me.txtCCEEValorCofins.Text, 0))
            Me.txtCCEEBaseIcms.Text = VB6.Format(Arredondar(ldblValor / (1 - (ldblAIcms / 100)), 2) + IIf(IsNumeric(Me.txtCCEEBaseIntermediaria.Text), Me.txtCCEEBaseIntermediaria.Text, 0), "#,##0.00")
            'Passo 6
            ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEBaseIcms.Text), Me.txtCCEEBaseIcms.Text, 0))
            Me.txtCCEEValorIcms.Text = VB6.Format(Truncate(ldblValor * (ldblAIcms / 100), 2), "#,##0.00")
            '
            With grid_fatura
                '
                'Valor de Icms - ST
                '06.02.02.0001 = valor icms [ Será mostrado na impressão da fatura]
                ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEValorIcms.Text), Me.txtCCEEValorIcms.Text, 0))
                If ldblValor > 0 Then
                    aintRowGrid = 1 + aintRowGrid
                    .Rows = aintRowGrid + 1
                    .set_TextMatrix(aintRowGrid, 0, "0602020001")
                    .set_TextMatrix(aintRowGrid, 1, codTodescri("0602020001") & " (" & VB6.Format(ldblAIcms, "#,#####0.00000") & "% )")
                    .set_TextMatrix(aintRowGrid, 2, VB6.Format(CDbl(IIf(IsNumeric(Me.txtCCEEBaseIcms.Text), Me.txtCCEEBaseIcms.Text, 0)), "#,##0.00"))
                    .set_TextMatrix(aintRowGrid, 3, VB6.Format(ldblValor, "#,##0.00"))
                    .set_TextMatrix(aintRowGrid, 4, " (" & VB6.Format(ldblAIcms, "#,#####0.00000") & "% )")
                    ldblValorTotal = ldblValorTotal + CDbl(VB6.Format(ldblValor, "#,##0.00"))
                End If
                If Me.txtZona.Text = "001" And Me.txtLivro.Text = "99" And Me.txtConta.Text = "000085" Then
                    If Me.txtMesAno.Text = "01/2017" Then
                        If ldblValor > 0 Then
                            aintRowGrid = 1 + aintRowGrid
                            .Rows = aintRowGrid + 1
                            .set_TextMatrix(aintRowGrid, 0, "0604020001")
                            .set_TextMatrix(aintRowGrid, 1, codTodescri("0604020001") & " (P.01/02 09/16 - " & VB6.Format(ldblAIcms, "#,#####0.00000") & "% )")
                            .set_TextMatrix(aintRowGrid, 2, VB6.Format(CDbl(IIf(IsNumeric(Me.txtCCEEBaseIcms.Text), Me.txtCCEEBaseIcms.Text, 0)) * -1, "#,##0.00"))
                            .set_TextMatrix(aintRowGrid, 3, VB6.Format(ldblValor * -1, "#,##0.00"))
                            .set_TextMatrix(aintRowGrid, 4, " (P.01/02 09/16 - " & VB6.Format(ldblAIcms, "#,#####0.00000") & "% )")
                            ldblValorTotal = ldblValorTotal + CDbl(VB6.Format(ldblValor * -1, "#,##0.00"))
                        End If
                    End If
                    If Me.txtMesAno.Text = "02/2017" Then
                        If ldblValor > 0 Then
                            aintRowGrid = 1 + aintRowGrid
                            .Rows = aintRowGrid + 1
                            .set_TextMatrix(aintRowGrid, 0, "0604020001")
                            .set_TextMatrix(aintRowGrid, 1, codTodescri("0604020001") & " (P.02/02 09/16 - " & VB6.Format(ldblAIcms, "#,#####0.00000") & "% )")
                            .set_TextMatrix(aintRowGrid, 2, VB6.Format(CDbl(27241.38) * -1, "#,##0.00")) 'Format(Conversion.CDbl(IIf(IsNumeric(Me.txtCCEEBaseIcms.Text), Me.txtCCEEBaseIcms.Text, 0)) * -1, "#,##0.00")
                            .set_TextMatrix(aintRowGrid, 3, VB6.Format(6810.34 * -1, "#,##0.00"))
                            .set_TextMatrix(aintRowGrid, 4, " (P.02/02 09/16 - " & VB6.Format(ldblAIcms, "#,#####0.00000") & "% )")
                            ldblValorTotal = ldblValorTotal + CDbl(VB6.Format(6810.34 * -1, "#,##0.00"))
                        End If
                    End If
                End If


                '
                'Valor de Pis - ST
                '06.02.02.0002 = valor pis [ Será mostrado na impressão da fatura]
                ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEValorPis.Text), Me.txtCCEEValorPis.Text, 0))
                If ldblValor > 0 Then
                    aintRowGrid = 1 + aintRowGrid
                    .Rows = aintRowGrid + 1
                    .set_TextMatrix(aintRowGrid, 0, "0602020002")
                    .set_TextMatrix(aintRowGrid, 1, codTodescri("0602020002") & " (" & VB6.Format(ldblAPis, "#,#####0.00000") & "% )")
                    .set_TextMatrix(aintRowGrid, 2, VB6.Format(CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0)), "#,##0.00"))
                    .set_TextMatrix(aintRowGrid, 3, VB6.Format(ldblValor, "#,##0.00"))
                    .set_TextMatrix(aintRowGrid, 4, " (" & VB6.Format(ldblAPis, "#,#####0.00000") & "% )")
                    ldblValorTotal = ldblValorTotal + CDbl(VB6.Format(ldblValor, "#,##0.00"))
                End If
                '
                'Valor de Cofins - ST
                '06.02.02.0003 = valor cofins [ Será mostrado na impressão da fatura]
                ldblValor = CDbl(IIf(IsNumeric(Me.txtCCEEValorCofins.Text), Me.txtCCEEValorCofins.Text, 0))
                If ldblValor > 0 Then
                    aintRowGrid = 1 + aintRowGrid
                    .Rows = aintRowGrid + 1
                    .set_TextMatrix(aintRowGrid, 0, "0602020003")
                    .set_TextMatrix(aintRowGrid, 1, codTodescri("0602020003") & " (" & VB6.Format(ldblACof, "#,#####0.00000") & "% )")
                    .set_TextMatrix(aintRowGrid, 2, VB6.Format(CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0)), "#,##0.00"))
                    .set_TextMatrix(aintRowGrid, 3, VB6.Format(ldblValor, "#,##0.00"))
                    .set_TextMatrix(aintRowGrid, 4, " (" & VB6.Format(ldblACof, "#,#####0.00000") & "% )")
                    ldblValorTotal = ldblValorTotal + CDbl(VB6.Format(ldblValor, "#,##0.00"))
                End If
                '
                'Aliquotas do calculo da comercializadora
                '06.01.02.0001 = aliquota icms [ Será mostrado na impressão da fatura]
                '06.01.02.0002 = aliquota pis [ Será mostrado na impressão da fatura]
                '06.01.02.0003 = aliquota cofins [ Será mostrado na impressão da fatura]
                Item_Fatura = Trim(Item_Fatura & "0601020001?" & Replace(CStr(ldblAIcms), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601020002?" & Replace(CStr(ldblAPis), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601020003?" & Replace(CStr(ldblACof), ",", ".") & ";")
                '
                'Base de cálculo de tributos da comercializadora
                '06.02.01.0001 = base icms [ Será mostrado na impressão da fatura]
                '06.02.01.0002 = base pis [ Será mostrado na impressão da fatura]
                '06.02.01.0003 = base cofins [ Será mostrado na impressão da fatura]
                Item_Fatura = Trim(Item_Fatura & "0602010001?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBaseIcms.Text), Me.txtCCEEBaseIcms.Text, 0))), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0602010002?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0))), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0602010003?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0))), ",", ".") & ";")

                If Me.txtZona.Text = "001" And Me.txtLivro.Text = "99" And Me.txtConta.Text = "000085" Then
                    If Me.txtMesAno.Text = "01/2017" Then
                        Item_Fatura = Trim(Item_Fatura & "0604010001?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBaseIcms.Text), Me.txtCCEEBaseIcms.Text, 0)) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0604010002?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0)) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0604010003?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBasePisCof.Text), Me.txtCCEEBasePisCof.Text, 0)) * -1), ",", ".") & ";")
                    End If
                    If Me.txtMesAno.Text = "02/2017" Then
                        Item_Fatura = Trim(Item_Fatura & "0604010001?" & Replace(CStr(CDbl(20431.03) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0604010002?" & Replace(CStr(CDbl(0) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0604010003?" & Replace(CStr(CDbl(0) * -1), ",", ".") & ";")
                    End If
                End If

                '
                'Valores auxiliares para calculo dos tributos da comercializadora
                '06.01.01.0001 = Valor em (R$) de energia cobrada pela comercializadora. [ Será mostrado na impressão da fatura]
                '06.01.01.0002 = base icms intermediaria [ Controle interno ]
                '06.01.01.0003 = valor icms intermediario [Controle interno ]
                '06.01.01.0004 = mês e ano de referência do compra
                '06.01.01.0005 = Preço Médio
                '06.01.01.0006 = Energia total consumida
                Item_Fatura = Trim(Item_Fatura & "0601010001?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEEnergiaComprada.Text), Me.txtCCEEEnergiaComprada.Text, 0))), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601010002?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBaseIntermediaria.Text), Me.txtCCEEBaseIntermediaria.Text, 0))), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601010003?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEIcmsIntermediario.Text), Me.txtCCEEIcmsIntermediario.Text, 0))), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601010004?0$" & VB6.Format(Me.dtpMesAnoConsumo.Value, "MM/YYYY") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601010005?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEPrecoMedio.Text), Me.txtCCEEPrecoMedio.Text, 0))), ",", ".") & ";")
                Item_Fatura = Trim(Item_Fatura & "0601010006?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEConsumoTotal.Text), Me.txtCCEEConsumoTotal.Text, 0))), ",", ".") & ";")

                If Me.txtZona.Text = "001" And Me.txtLivro.Text = "99" And Me.txtConta.Text = "000085" Then
                    If Me.txtMesAno.Text = "01/2017" Then
                        Item_Fatura = Trim(Item_Fatura & "0603010001?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEEnergiaComprada.Text), Me.txtCCEEEnergiaComprada.Text, 0)) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0603010002?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEBaseIntermediaria.Text), Me.txtCCEEBaseIntermediaria.Text, 0)) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0603010003?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEIcmsIntermediario.Text), Me.txtCCEEIcmsIntermediario.Text, 0)) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0603010004?0$09/2016;")
                        Item_Fatura = Trim(Item_Fatura & "0603010005?0.21104;")
                        Item_Fatura = Trim(Item_Fatura & "0603010006?" & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtCCEEConsumoTotal.Text), Me.txtCCEEConsumoTotal.Text, 0)) * -1), ",", ".") & ";")
                    End If
                    If Me.txtMesAno.Text = "02/2017" Then
                        Item_Fatura = Trim(Item_Fatura & "0603010001?" & Replace(CStr(CDbl(66855.12) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0603010002?" & Replace(CStr(CDbl(89140.16) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0603010003?" & Replace(CStr(CDbl(22285.04) * -1), ",", ".") & ";")
                        Item_Fatura = Trim(Item_Fatura & "0603010004?0$09/2016;")
                        Item_Fatura = Trim(Item_Fatura & "0603010005?0.21104;")
                        Item_Fatura = Trim(Item_Fatura & "0603010006?" & Replace(CStr(CDbl(324350.46) * -1), ",", ".") & ";")
                    End If


                End If


            End With


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Function BuscaDtVcto(ByVal adteApresentacao As Date) As Date

        Dim dteAuxiliar As Date
        Dim intQtde As Short
        Dim intSemana As Short
        Dim blnFeriado As Boolean
        Dim intDias As Short


        Try

            intDias = IIf(CDbl(Microsoft.VisualBasic.Left(Trim(istrClasse), 1)) = 6, 10, 5)

            dteAuxiliar = adteApresentacao
            intQtde = 0
            While intQtde < intDias
                dteAuxiliar = System.DateTime.FromOADate(dteAuxiliar.ToOADate + 1)
                blnFeriado = VerificaFeriado(dteAuxiliar)
                intSemana = Weekday(dteAuxiliar, FirstDayOfWeek.Sunday)
                If (intSemana > 1 And intSemana < 7) Then
                    If blnFeriado = False Then intQtde = intQtde + 1
                End If
            End While
            BuscaDtVcto = dteAuxiliar


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub Calc_Convencional()



        Dim dias As Short
        Dim row_grid As Short

        Dim vlrConsumo As Double
        Dim vlrConsumoBan As Double
        Dim Cons_Reativo As Double
        Dim Demanda_Faturada As Double
        Dim vlrDemanda As Double
        Dim Demanda_Lida As Double
        Dim auxDemandaReativa As Double
        Dim Dem_Reativa As Double
        Dim Dem_Ultrapassagem As Double
        Dim vlrDem_ultrapassagem As Double

        Dim dblDemReatAux As Double

        Dim kvqh As Double
        Dim vlrPis As Double
        Dim vlrIcmsPisCofins As Double
        Dim vlrCofins As Double
        Dim vlrEncargo As Double
        Dim vlrICMSEce As Double

        Dim vlrqh As Double
        Dim coefTribIcms As Double
        Dim coefTribIcms2 As Double
        Dim coefTribSIcms As Double
        Dim vlrConsumoT As Double
        Dim vlrConsReatT As Double
        Dim vlrDemandaT As Double
        Dim vlrDemaReatT As Double
        Dim vlrDemUltraT As Double
        Dim vlrConsumoT2 As Double
        Dim vlrConsReatT2 As Double
        Dim vlrDemandaT2 As Double
        Dim vlrDemaReatT2 As Double
        Dim vlrDemUltraT2 As Double
        Dim baseIcmsAux As Double
        Dim baseICMSisenta As Double

        Dim ldblLimRural As Double
        Dim vlrTotal As Double
        Dim vlrIsentoIcms As Double
        Dim kVArh As Double
        Dim vlrKvarh_consumo As Double
        Dim vlrKvarh_demanda As Double
        Dim aux As Double
        Dim fator_potencia As Double
        Dim leitDemanda_aux As Double
        Dim leitConsumo_aux As Double
        Dim base_demanda_reativa As Double
        Dim leitura_maxima As Double

        Dim lblnCalcReativo As Boolean
        Dim lblnReativoNegativo As Boolean


        Dim retencao As Double
        Dim base_retencao As Double
        Dim vlr_retencao As Double
        Dim leitAtual As Double

        Dim strMesRefMulta As String
        Dim dtDataRefMulta As Date
        Dim dtDataFat As Date
        Dim FatorAjuste As Double
        Dim casas As Short
        Dim lstrSql As String

        Dim lstrCidade As String
        Dim lstrClasse As String
        Dim lstrZona As String
        Dim lstrLivro As String
        Dim lstrConta As String
        Dim lstrInscricaoEstadual As String
        Dim lstrUFUnidade As String
        '***  Fatores de Multiplicação *****
        Dim ldblConstanteConsumo As Double
        Dim ldblConstanteDemanda As Double
        Dim ldblConstanteReativo As Double
        Dim ldblPerdas As Double
        '***********************************
        Dim ldblContratoDemanda As Double
        'Tem medidor eletromagnético
        Dim lblnLeitDema As Boolean
        '***********************************
        'COntrole de Reativo
        Dim lblnLeituraReativo As Boolean 'Se é pela leitura ou pelo DMCR E UFER
        Dim lblnQh As Boolean
        '**************************************
        Dim lblnIsentoDemanda As Boolean
        Dim lblnIcmsDemandaLida As Boolean
        Dim lblnIcmsIsento As Boolean
        '----- Variaveis da Iluminação Publica -----
        Dim lblnIsentoIluminacao As Boolean
        Dim llngCodigoCidade As Integer
        Dim Ilum As Double
        Dim TpConsumo As String
        Dim TpFaixaC As String
        '-------------------------------------------
        'Controle de casas decimais no kwh, kw e kVarh
        Dim lintDecimalKwh As Short
        Dim lintDecimalKw As Short
        Dim lintDecimalKVarh As Short

        'Controle de Consumo
        Dim ldblQtdConsumo As Double

        Dim lstrPercDemU As String
        Dim ldblPercDemU As Double

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            lstrPercDemU = Trim(GetConfig("grupoa.percentual.kw.ultrap"))

            If lstrPercDemU = "-1" Then
                ldblPercDemU = 10
                SetConfig("grupoa.percentual.kw.ultrap", "String", CStr(ldblPercDemU), CStr(ldblPercDemU), "Percentual de Demanda Ultrapassagem")
            ElseIf Len(lstrPercDemU) = 0 Then
                ldblPercDemU = 10
                SetConfig("grupoa.percentual.kw.ultrap", "String", CStr(ldblPercDemU), CStr(ldblPercDemU), "Percentual de Demanda Ultrapassagem")
            Else
                ldblPercDemU = CDbl(lstrPercDemU)
            End If

            If gstrEmpresa_Sigla = "COORSEL" Then
                lintDecimalKwh = 0
                lintDecimalKw = 3
                lintDecimalKVarh = 3
            Else
                lintDecimalKwh = 0
                lintDecimalKw = 0
                lintDecimalKVarh = 0
            End If

            grid_fatura.Redraw = False
            ' MontaGradeFatura
            Me.lblTotal.Text = "0,00"
            BaseICMS = 0
            row_grid = 0
            Item_Fatura = ""
            dias = CDate(txtDt_Leit_Atual.Text).ToOADate - CDate(txtDt_Leit_Anterior.Text).ToOADate
            retencao = CDbl(GetConfig("percentual.retencao.consumo"))
            ldblLimRural = CDbl(GetConfig("limite.rural"))
            casas = 9

            vResp = MessageBox.Show("Deseja calcular consumo e a demanda reativo?", "Informação", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

            If vResp = DialogResult.Yes Then
                lblnCalcReativo = True
            Else
                lblnCalcReativo = False
            End If


            lstrSql = ""
            lstrSql = lstrSql & "SELECT "
            lstrSql = lstrSql & "     `uc_faturamento`.`zona`,"
            lstrSql = lstrSql & "     `uc_faturamento`.`livro`,"
            lstrSql = lstrSql & "     `uc_faturamento`.`conta`, "

            lstrSql = lstrSql & "     `uc_faturamento`.`cidade`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`clas`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`insc`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`uf`, "

            lstrSql = lstrSql & "     `uc_faturamento`.`const_consumo`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`const_demanda`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`const_kvarh`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`final`, "

            lstrSql = lstrSql & "     `uc_faturamento`.`demanda_contr`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`data_contrato_demanda`, "

            lstrSql = lstrSql & "     `uc_faturamento`.`leitdema`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`leitreativo`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`qh`, "

            lstrSql = lstrSql & "     `uc_faturamento`.`ilum`, "
            lstrSql = lstrSql & "     `uc_faturamento`.`isento`,"
            lstrSql = lstrSql & "     `uc_faturamento`.`icms_isento_demanda`,"
            lstrSql = lstrSql & "     `uc_faturamento`.`icms_demanda_lida`"
            lstrSql = lstrSql & "  FROM `uc_faturamento` "
            lstrSql = lstrSql & " WHERE `uc_faturamento`.`cons_id` = " & idblConsId
            lstrSql = lstrSql & "   AND `uc_faturamento`.`id` = " & idblUnidId

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    lstrZona = Trim(IIf(IsDBNull(row("zona")), "", row("zona")))

                    lstrLivro = Trim(IIf(IsDBNull(row("livro")), "", row("livro")))

                    lstrConta = Trim(IIf(IsDBNull(row("conta")), "", row("conta")))

                    lstrCidade = Trim(IIf(IsDBNull(row("cidade")), "", row("cidade")))

                    lstrClasse = VB6.Format(Trim(IIf(IsDBNull(row("clas")), "0", row("clas"))), "0000")

                    lstrInscricaoEstadual = Trim(IIf(IsDBNull(row("insc")), "", row("insc")))

                    lstrUFUnidade = Trim(IIf(IsDBNull(row("uf")), "", row("uf")))

                    ldblConstanteConsumo = CDbl(IIf(IsDBNull(row("const_consumo")), 0, row("const_consumo")))

                    ldblConstanteDemanda = CDbl(IIf(IsDBNull(row("const_demanda")), 0, row("const_demanda")))

                    ldblConstanteReativo = CDbl(IIf(IsDBNull(row("const_kvarh")), 0, row("const_kvarh")))

                    ldblPerdas = CDbl(IIf(IsDBNull(row("final")), 0, row("final")))

                    ldblContratoDemanda = CDbl(IIf(IsDBNull(row("demanda_contr")), 0, row("demanda_contr")))

                    idteContratoDemanda = IIf(IsDBNull(row("data_contrato_demanda")), "1951-01-01", row("data_contrato_demanda"))

                    lblnLeitDema = IIf(IsDBNull(row("leitdema")), "N", row("leitdema")) = "S"

                    lblnLeituraReativo = IIf(IsDBNull(row("leitreativo")), "0", row("leitreativo")) = "1"

                    lblnQh = IIf(IsDBNull(row("qh")), "N", row("qh")) = "S"

                    lblnIsentoIluminacao = IIf(IsDBNull(row("ilum")), "N", row("ilum")) = "S"

                    lblnIcmsIsento = IIf(IsDBNull(row("isento")), "N", row("isento")) = "S"

                    lblnIsentoDemanda = IIf(IsDBNull(row("icms_isento_demanda")), "N", row("icms_isento_demanda")) = "S"

                    lblnIcmsDemandaLida = IIf(IsDBNull(row("icms_demanda_lida")), "N", row("icms_demanda_lida")) = "S"


                Next

            End If


            If Len(lstrUFUnidade) < 1 Then
                MessageBox.Show("O consumidor " & lstrZona & "." & lstrLivro & "." & lstrConta & ", não possui Unidade Federativa!" & Chr(10) & Chr(13) & "*** Não será faturado! ***", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            'Municipio
            lstrSql = "SELECT * " & "  FROM `munic` " & " WHERE nome LIKE ""%" & lstrCidade & "%"" " & " LIMIT 1 "
            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    llngCodigoCidade = IIf(IsDBNull(row("cod")), 0, row("cod"))
                Next
            Else
                MessageBox.Show("Atenção! O município " & lstrCidade & " não está cadastrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If



            Carr_Leit_Anterior(idteContratoDemanda, ldblContratoDemanda, 0)
            TarifaConvencional()

            If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) <> "01AS" Then
                '-- Aplica desconto de 10% para tarifas rurais
                tarConsumo = Arredondar(tarConsumo * 0.9, 5)
                tarDemanda = Arredondar(tarDemanda * 0.9, 5)
                tarDemUltra = Arredondar(tarDemUltra * 0.9, 5)
                '  ElseIf left(lstrclasse,1) = 7 Then
                '    '-- Aplica desconto de 15% para tarifas servico publico
                '    tarConsumo = Arredondar(tarConsumo * 0.85, 5)
                '    tarDemanda = Arredondar(tarDemanda * 0.85, 5)
                '    tarDemUltra = Arredondar(tarDemUltra * 0.85, 5)
            End If

            'leituras anteriores e atuais
            Item_Fatura = Trim(Item_Fatura & "0302040007?" & Replace(CStr(ant_consumo_p), ",", ".") & ";") 'consumo anterior
            Item_Fatura = Trim(Item_Fatura & "0302040008?" & Replace(Replace(txtLeit_Consumo.Text, ".", ""), ",", ".") & ";") 'consumo atual
            If lblnLeitDema Then
                Item_Fatura = Trim(Item_Fatura & "0302040011?" & Replace(CStr(ant_demanda_p), ",", ".") & ";") 'demanda anterior
            Else
                Item_Fatura = Trim(Item_Fatura & "0302040011?" & Replace(CStr(0), ",", ".") & ";") 'demanda anterior
            End If
            Item_Fatura = Trim(Item_Fatura & "0302040012?" & Replace(Replace(txtLeit_Demanda.Text, ".", ""), ",", ".") & ";") 'demanda atual
            Item_Fatura = Trim(Item_Fatura & "0302040015?" & Replace(CStr(ant_kvarh), ",", ".") & ";") 'reativo anterior
            Item_Fatura = Trim(Item_Fatura & "0302040016?" & Replace(Replace(txtLeit_Kvarh.Text, ".", ""), ",", ".") & ";") 'reativo atual

            If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01A4" Then
                'tarifas aplicadas
                Item_Fatura = Trim(Item_Fatura & "01A4011101?" & Replace(CStr(tarConsumo), ",", ".") & ";") 'Tarifa do Consumo
                Item_Fatura = Trim(Item_Fatura & "01A40111" & iintBanderiaVigente & "1?" & Replace(CStr(tarConsumoBan), ",", ".") & ";") 'Tarifa do Consumo Bandeira
                Item_Fatura = Trim(Item_Fatura & "01A4012101?" & Replace(CStr(tarDemanda), ",", ".") & ";") 'Tarifa Demanda
                Item_Fatura = Trim(Item_Fatura & "01A4012102?" & Replace(CStr(tarDemUltra), ",", ".") & ";") 'Tarifa Demanda Ultra
            ElseIf Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01AS" Then
                Item_Fatura = Trim(Item_Fatura & "01AS011101?" & Replace(CStr(tarConsumo), ",", ".") & ";") 'Tarifa do Consumo
                Item_Fatura = Trim(Item_Fatura & "01AS0111" & iintBanderiaVigente & "1?" & Replace(CStr(tarConsumoBan), ",", ".") & ";") 'Tarifa do Consumo Bandeira
                Item_Fatura = Trim(Item_Fatura & "01AS012101?" & Replace(CStr(tarDemanda), ",", ".") & ";") 'Tarifa Demanda
                Item_Fatura = Trim(Item_Fatura & "01AS012102?" & Replace(CStr(tarDemUltra), ",", ".") & ";") 'Tarifa Demanda Ultra
            End If

            vlrPis = 0
            vlrCofins = 0
            vlrTotal = 0
            BaseICMS = 0
            BaseICMS2 = 0
            baseIcmsAux = 0
            baseICMSisenta = 0

            '[ CONSUMO ]
            leitAtual = txtLeit_Consumo.Text
            If (leitAtual - ant_consumo_p) < 0 Then
                Select Case Len(ant_consumo_p)
                    Case 4
                        leitAtual = 9999 + leitAtual + 1
                    Case 5
                        leitAtual = 99999 + leitAtual + 1
                    Case 6
                        leitAtual = 999999 + leitAtual + 1
                    Case 7
                        leitAtual = 9999999 + leitAtual + 1
                    Case 8
                        leitAtual = 99999999 + leitAtual + 1
                End Select
            End If

            'Refazer os calculo de consumo para apurar consumo real
            ldblQtdConsumo = (leitAtual - ant_consumo_p)
            If ldblConstanteConsumo > 0 Then
                ldblQtdConsumo = ldblQtdConsumo * ldblConstanteConsumo
            End If
            If ldblPerdas > 0 Then
                ldblQtdConsumo = ldblQtdConsumo + (ldblQtdConsumo * (ldblPerdas / 100))
            End If
            'ldblQtdConsumo = Arredondar(ldblQtdConsumo, lintDecimalKwh)
            coefTribSIcms = 1 - ((idblAliqPIS / 100) + (idblAliqCofins / 100))
            idblAliqICMS = Busca_Aliquota_ICMS(lstrUFUnidade, ldblQtdConsumo, lstrClasse)
            coefTribIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCofins / 100)) / (1 - (idblAliqICMS / 100))), 11)
            If Me.txtTA.Text = "01AS00" Then
                idblAliqICMS2 = Busca_Aliquota_ICMS(lstrUFUnidade, ldblLimRural, lstrClasse)
                coefTribIcms2 = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCofins / 100)) / (1 - (idblAliqICMS2 / 100))), 11)
            End If
            'vlrConsumo = Arredondar(ldblQtdConsumo * tarConsumo, 2)
            vlrConsumo = Truncate(ldblQtdConsumo * tarConsumo, 2)
            If vlrConsumo > 0 Then
                row_grid = 1 + row_grid
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302020008"
                grid_fatura.Col = 1
                grid_fatura.Text = Trim(codTodescri("0302020008")) & " ( " & Arredondar(ldblQtdConsumo, 2) & " x " & tarConsumo & " )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(ldblQtdConsumo, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(vlrConsumo, "#,##0.00")
                grid_fatura.Col = 4
                grid_fatura.Text = "( " & Truncate(ldblQtdConsumo, 5) & " x " & tarConsumo & " )"

                If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                    vlrConsumoT = Arredondar((vlrConsumo * 0.9) / coefTribIcms, 2)
                ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                    'vlrConsumoT = Arredondar((vlrConsumo * 0.85) / coefTribIcms, 2)
                    vlrConsumoT = Truncate((vlrConsumo * 0.85) / coefTribIcms, 2)
                Else
                    If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01AS" Then
                        'vlrConsumoT = Arredondar(Arredondar((ldblQtdConsumo - ldblLimRural) * tarConsumo, 2) / coefTribIcms, 2)
                        'vlrConsumoT2 = Arredondar(Arredondar(ldblLimRural * tarConsumo, 2) / coefTribIcms2, 2)
                        vlrConsumoT = Truncate(Truncate((ldblQtdConsumo - ldblLimRural) * tarConsumo, 2) / coefTribIcms, 2)
                        vlrConsumoT2 = Truncate(Truncate(ldblLimRural * tarConsumo, 2) / coefTribIcms2, 2)
                    Else
                        'vlrConsumoT = Arredondar(vlrConsumo / coefTribIcms, 2)
                        vlrConsumoT = Truncate(vlrConsumo / coefTribIcms, 2)
                    End If
                End If

                If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01AS" Then
                    baseIcmsAux = Calc_ICMS(vlrConsumoT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseIcmsAux = Calc_ICMS(vlrConsumoT2, lstrUFUnidade, idblAliqICMS2, 5)
                    BaseICMS2 = BaseICMS2 + baseIcmsAux
                Else
                    baseIcmsAux = Calc_ICMS(vlrConsumoT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(VB6.Format(vlrConsumo, "#,##0.00"))
                Item_Fatura = Trim(Item_Fatura & "0302010008?" & Replace(CStr(ldblQtdConsumo), ",", ".") & ";") 'Consumo Lido
                Item_Fatura = Trim(Item_Fatura & "0302010009?" & Replace(CStr(ldblQtdConsumo), ",", ".") & ";") 'Consumo Faturado
                Item_Fatura = Trim(Item_Fatura & "0302020009?" & Replace(CStr(vlrConsumo), ",", ".") & ";") 'Consumo Faturado
            End If

            'Bandeira
            vlrConsumoBan = Truncate(ldblQtdConsumo * (tarConsumoBan - tarConsumoSemDesconto), 2)
            If vlrConsumoBan > 0 Then
                row_grid = 1 + row_grid
                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302120008"
                grid_fatura.Col = 1
                grid_fatura.Text = Trim(codTodescri("0302120008")) & " ( " & Arredondar(ldblQtdConsumo, 2) & " x " & (tarConsumoBan - tarConsumoSemDesconto) & " )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(ldblQtdConsumo, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(vlrConsumoBan, "#,##0.00")
                grid_fatura.Col = 4
                grid_fatura.Text = ""
                'grid_fatura.Text = "( " & Truncate(ldblQtdConsumo, 5) & " x " & (tarConsumoBan - tarConsumoSemDesconto) & " )"

                If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                    'vlrConsumoT = Arredondar((vlrConsumoBan * 0.9) / coefTribIcms, 2)
                    vlrConsumoT = Arredondar((vlrConsumoBan) / coefTribIcms, 2)
                ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                    'vlrConsumoT = Truncate((vlrConsumoBan * 0.85) / coefTribIcms, 2)
                    vlrConsumoT = Truncate((vlrConsumoBan) / coefTribIcms, 2)
                Else
                    If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01AS" Then
                        'vlrConsumoT = Arredondar(Arredondar((ldblQtdConsumo - ldblLimRural) * tarConsumo, 2) / coefTribIcms, 2)
                        'vlrConsumoT2 = Arredondar(Arredondar(ldblLimRural * tarConsumo, 2) / coefTribIcms2, 2)
                        vlrConsumoT = Truncate(Truncate((ldblQtdConsumo - ldblLimRural) * (tarConsumoBan - tarConsumoSemDesconto), 2) / coefTribIcms, 2)
                        vlrConsumoT2 = Truncate(Truncate(ldblLimRural * (tarConsumoBan - tarConsumoSemDesconto), 2) / coefTribIcms2, 2)
                    Else
                        'vlrConsumoT = Arredondar(vlrConsumoBan / coefTribIcms, 2)
                        vlrConsumoT = Truncate(vlrConsumoBan / coefTribIcms, 2)
                    End If
                End If

                If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01AS" Then
                    baseIcmsAux = Calc_ICMS(vlrConsumoT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseIcmsAux = Calc_ICMS(vlrConsumoT2, lstrUFUnidade, idblAliqICMS2, 5)
                    BaseICMS2 = BaseICMS2 + baseIcmsAux
                Else
                    baseIcmsAux = Calc_ICMS(vlrConsumoT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(VB6.Format(vlrConsumoBan, "#,##0.00"))
                Item_Fatura = Trim(Item_Fatura & "0302110008?" & Replace(CStr(ldblQtdConsumo), ",", ".") & ";") 'Consumo Lido
                Item_Fatura = Trim(Item_Fatura & "0302110009?" & Replace(CStr(ldblQtdConsumo), ",", ".") & ";") 'Consumo Faturado
                Item_Fatura = Trim(Item_Fatura & "0302120009?" & Replace(CStr(vlrConsumoBan), ",", ".") & ";") 'Consumo Faturado
            End If

            '-- Demanda
            If lblnLeitDema Then
                Demanda_Lida = CDbl(txtLeit_Demanda.Text) - ant_demanda_p
            Else
                Demanda_Lida = CDbl(txtLeit_Demanda.Text)
            End If

            If ldblConstanteDemanda > 0 Then
                Demanda_Lida = Demanda_Lida * ldblConstanteDemanda
            End If

            If ldblPerdas > 0 Then
                Demanda_Lida = Demanda_Lida + (Demanda_Lida * (ldblPerdas / 100))
            End If
            'Demanda_Lida = Arredondar(Demanda_Lida, lintDecimalKw)
            If ldblContratoDemanda > 0 Then
                If Demanda_Lida > ldblContratoDemanda Then
                    '-- Determina se existe demanda de ultrapassagem na ponta
                    If Demanda_Lida <= (ldblContratoDemanda * ((ldblPercDemU / 100) + 1)) Then
                        Demanda_Faturada = Demanda_Lida
                    Else
                        'Dem_Ultrapassagem = Arredondar(Demanda_Lida - ldblContratoDemanda, lintDecimalKw)
                        Dem_Ultrapassagem = (Demanda_Lida - ldblContratoDemanda)
                        If istrRes414_Art104 = "S" Then
                            Demanda_Faturada = Demanda_Lida
                        Else
                            Demanda_Faturada = ldblContratoDemanda
                        End If
                    End If
                ElseIf Demanda_Lida < ldblContratoDemanda Then
                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 Then
                        If Demanda_Lida <= (ldblContratoDemanda * (ldblPercDemU / 100)) Then
                            Demanda_Faturada = (ldblContratoDemanda * (ldblPercDemU / 100))
                        Else
                            Demanda_Faturada = Demanda_Lida
                        End If
                    Else
                        Demanda_Faturada = ldblContratoDemanda
                    End If
                Else
                    Demanda_Faturada = Demanda_Lida
                End If
            Else
                Dem_Ultrapassagem = 0
                Demanda_Faturada = Demanda_Lida
            End If

            'base_demanda_reativa = Arredondar(Demanda_Lida, lintDecimalKVarh) * tarDemanda
            base_demanda_reativa = Truncate(Demanda_Lida * tarDemanda, 2)
            'Demanda_Faturada = Arredondar(Demanda_Faturada, lintDecimalKw)
            'vlrDemanda = Arredondar(Demanda_Faturada * tarDemanda, 2)
            vlrDemanda = Truncate(Demanda_Faturada * tarDemanda, 2)

            If vlrDemanda > 0 Then
                row_grid = 1 + row_grid

                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302020015"
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("0302020015") & " ( " & Arredondar(Demanda_Faturada, 2) & " x " & tarDemanda & " )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(Demanda_Faturada, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(vlrDemanda, "#,##0.00")
                grid_fatura.Col = 4
                grid_fatura.Text = "( " & Truncate(Demanda_Faturada, 5) & " x " & tarDemanda & " )"

                If Not lblnIsentoDemanda Then
                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                        vlrDemandaT = (vlrDemanda * 0.9) / coefTribIcms
                    ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                        vlrDemandaT = (vlrDemanda * 0.85) / coefTribIcms
                    Else
                        'vlrDemandaT = Arredondar(vlrDemanda / coefTribIcms, 2)
                        vlrDemandaT = Truncate(vlrDemanda / coefTribIcms, 2)
                    End If

                    baseIcmsAux = Calc_ICMS(vlrDemandaT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                        vlrDemandaT = (vlrDemanda * 0.9) / coefTribSIcms
                    ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                        vlrDemandaT = (vlrDemanda * 0.85) / coefTribSIcms
                    Else
                        vlrDemandaT = vlrDemanda / coefTribSIcms
                    End If

                    baseICMSisenta = baseICMSisenta + vlrDemandaT
                End If

                vlrTotal = vlrTotal + CDbl(VB6.Format(vlrDemanda, "#,##0.00"))

                Item_Fatura = Trim(Item_Fatura & "0302010015?" & Replace(CStr(Demanda_Lida), ",", ".") & ";") ' Demanda Lida
                Item_Fatura = Trim(Item_Fatura & "0302010016?" & Replace(CStr(ldblContratoDemanda), ",", ".") & ";") 'Demanda Contratada
                Item_Fatura = Trim(Item_Fatura & "0302010017?" & Replace(CStr(Demanda_Faturada), ",", ".") & ";") 'Demanda Faturada
            End If

            '-- Demanda de Ultrapassagem
            If Dem_Ultrapassagem > 0 Then
                'vlrDem_ultrapassagem = Arredondar(Dem_Ultrapassagem * tarDemUltra, 2)
                vlrDem_ultrapassagem = Truncate(Dem_Ultrapassagem * tarDemUltra, 2)
                row_grid = 1 + row_grid
                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302020018"
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("0302020018") & " ( " & Arredondar(Dem_Ultrapassagem, 2) & " x " & tarDemUltra & " )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(Dem_Ultrapassagem, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(vlrDem_ultrapassagem, "#,##0.00")
                grid_fatura.Col = 4
                grid_fatura.Text = "( " & Truncate(Dem_Ultrapassagem, 5) & " x " & tarDemUltra & " )"

                If Not lblnIsentoDemanda Then
                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                        vlrDemUltraT = (vlrDem_ultrapassagem * 0.9) / coefTribIcms
                    ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                        vlrDemUltraT = (vlrDem_ultrapassagem * 0.85) / coefTribIcms
                    Else
                        vlrDemUltraT = vlrDem_ultrapassagem / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(vlrDemUltraT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                        vlrDemUltraT = (vlrDem_ultrapassagem * 0.9) / coefTribSIcms
                    ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                        vlrDemUltraT = (vlrDem_ultrapassagem * 0.85) / coefTribSIcms
                    Else
                        vlrDemUltraT = vlrDem_ultrapassagem / coefTribSIcms
                    End If

                    baseICMSisenta = baseICMSisenta + vlrDemandaT
                End If

                vlrTotal = vlrTotal + CDbl(VB6.Format(vlrDem_ultrapassagem, "#,##0.00"))

                Item_Fatura = Trim(Item_Fatura & "0302010018?" & Replace(CStr(Dem_Ultrapassagem), ",", ".") & ";") 'Demanda de Ultrapassagem
            End If

            If lblnCalcReativo Then
                If lblnLeituraReativo Then
                    '-- Consumo e Demanda Reativo
                    '-- Cálculo do Fator de Potência
                    'kVArh = Arredondar(CDbl(txtLeit_Kvarh.Text) - ant_kvarh, 2)
                    kVArh = (CDbl(txtLeit_Kvarh.Text) - ant_kvarh)

                    If ldblConstanteReativo > 0 Then
                        kVArh = kVArh * ldblConstanteReativo
                    End If

                    If ldblPerdas > 0 Then
                        kVArh = kVArh + (kVArh * (ldblPerdas / 100))
                    End If

                    'kVArh = Arredondar(kVArh, 2)
                    If kVArh <> 0 Then
                        vlrqh = ((kVArh * 2) - ldblQtdConsumo) / System.Math.Sqrt(3)
                        'vlrqh = Arredondar(((kVArh * 2) - ldblQtdConsumo) / Sqr(3))
                    Else
                        vlrqh = 0
                    End If

                    If lblnQh Then
                        aux = System.Math.Sqrt((ldblQtdConsumo * ldblQtdConsumo) + (vlrqh * vlrqh))
                    Else
                        aux = System.Math.Sqrt((ldblQtdConsumo * ldblQtdConsumo) + (kVArh * kVArh))
                    End If

                    If aux = 0 Then aux = 1

                    'fator_potencia = Arredondar(((1 / aux) * ldblQtdConsumo), 4)
                    fator_potencia = Arredondar((1 / aux) * ldblQtdConsumo, 5)
                    'FP = Arredondar(100 * ((1 / aux) * ldblQtdConsumo), 4)
                    FP = CStr(Arredondar(100 * fator_potencia, 5))

                    Item_Fatura = Trim(Item_Fatura & "0302030099?" & Replace(CStr(fator_potencia), ",", ".") & ";") ' Fator de Potencia

                    If fator_potencia < 0.92 Then
                        If fator_potencia <> 0 Then
                            '-- Consumo Reativo
                            aux = 0.92 / fator_potencia
                            aux = aux - 1
                            vlrKvarh_consumo = aux * vlrConsumo
                            leitConsumo_aux = aux

                            '-- Demanda Reativa
                            'vlrKvarh_demanda = Arredondar(base_demanda_reativa * ((0.92 / fator_potencia) - 1), 2)
                            vlrKvarh_demanda = Truncate(base_demanda_reativa * ((0.92 / fator_potencia) - 1), 2)

                            If Demanda_Lida < ldblContratoDemanda Then
                                auxDemandaReativa = (ldblContratoDemanda - Demanda_Lida) * tarDemanda

                                If vlrKvarh_demanda > auxDemandaReativa Then
                                    vlrKvarh_demanda = vlrKvarh_demanda - auxDemandaReativa
                                Else
                                    vlrKvarh_demanda = 0
                                End If
                            End If

                            leitDemanda_aux = tarDemanda
                        End If
                    End If
                Else
                    'aqui é sem Fator de Potencia
                    If gstrEmpresa_Sigla = "EFLUL" Then
                        kVArh = CDbl(txtLeit_Kvarh.Text) - ant_kvarh
                        If ldblConstanteReativo > 0 Then
                            kVArh = kVArh * ldblConstanteReativo
                        End If
                        If ldblPerdas > 0 Then
                            kVArh = kVArh + (kVArh * (ldblPerdas / 100))
                        End If
                    Else
                        kVArh = CDbl(txtLeit_Kvarh.Text)
                    End If
                    'kVArh = Arredondar(kVArh, 2)
                    'vlrKvarh_consumo = Arredondar(kVArh * tarConsumo, 2)
                    If idblTarTe_B1 > 0 Then
                        vlrKvarh_consumo = Truncate(kVArh * idblTarTe_B1, 2)
                    Else
                        vlrKvarh_consumo = Truncate(kVArh * tarConsumo, 2)
                    End If
                    'demanda reativa na ponta
                    auxDemandaReativa = IIf(ldblContratoDemanda > Demanda_Lida, ldblContratoDemanda, Demanda_Lida)
                    dblDemReatAux = CDbl(IIf(txtDem_Exc_Ponta.Text = "", "0", txtDem_Exc_Ponta.Text))
                    dblDemReatAux = (dblDemReatAux * ldblConstanteReativo) * (1 + (ldblPerdas / 100))
                    'dblDemReatAux = Arredondar(dblDemReatAux)
                    If dblDemReatAux > auxDemandaReativa Then
                        vlrKvarh_demanda = (dblDemReatAux - auxDemandaReativa) * tarDemanda
                    Else
                        vlrKvarh_demanda = 0
                    End If
                End If
                lblnReativoNegativo = False
                If vlrKvarh_consumo < 0 Then lblnReativoNegativo = True
                If vlrKvarh_consumo > 0 Then
                    row_grid = 1 + row_grid
                    grid_fatura.Rows = row_grid + 1
                    grid_fatura.Row = row_grid
                    grid_fatura.Col = 0
                    grid_fatura.Text = "0302020012"
                    grid_fatura.Col = 1
                    grid_fatura.Text = codTodescri("0302020012") & " ( " & Arredondar(kVArh, 2) & " x " & idblTarTe_B1 & " )"
                    grid_fatura.Col = 2
                    grid_fatura.Text = VB6.Format(Truncate(vlrConsumo, 2), "#,##0.00")
                    grid_fatura.Col = 3
                    grid_fatura.Text = VB6.Format(vlrKvarh_consumo, "#,##0.00")
                    grid_fatura.Col = 4
                    grid_fatura.Text = " ( " & Arredondar(kVArh, 2) & " x " & idblTarTe_B1 & " )"

                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                        vlrConsReatT = (vlrKvarh_consumo * 0.9) / coefTribIcms
                    ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                        vlrConsReatT = (vlrKvarh_consumo * 0.85) / coefTribIcms
                    Else
                        vlrConsReatT = vlrKvarh_consumo / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(vlrConsReatT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux

                    vlrTotal = vlrTotal + CDbl(VB6.Format(vlrKvarh_consumo, "#,##0.00"))

                End If
                Item_Fatura = Trim(Item_Fatura & "0302010012?" & Replace(CStr(kVArh), ",", ".") & ";") ' Consumo Reativo
                If vlrKvarh_demanda < 0 Then lblnReativoNegativo = True
                If vlrKvarh_demanda > 0 Then
                    row_grid = 1 + row_grid

                    grid_fatura.Rows = row_grid + 1
                    grid_fatura.Row = row_grid
                    grid_fatura.Col = 0
                    grid_fatura.Text = "0302020031"
                    grid_fatura.Col = 1
                    grid_fatura.Text = codTodescri("0302020031")
                    grid_fatura.Col = 2
                    grid_fatura.Text = VB6.Format(Arredondar(leitDemanda_aux), "#,##0.00")
                    grid_fatura.Col = 3
                    grid_fatura.Text = VB6.Format(vlrKvarh_demanda, "#,##0.00")

                    If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                        vlrDemaReatT = (vlrKvarh_demanda * 0.9) / coefTribIcms
                    ElseIf CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                        vlrDemaReatT = (vlrKvarh_demanda * 0.85) / coefTribIcms
                    Else
                        vlrDemaReatT = vlrKvarh_demanda / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(vlrDemaReatT, lstrUFUnidade, idblAliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux

                    vlrTotal = vlrTotal + CDbl(VB6.Format(vlrKvarh_demanda, "#,##0.00"))
                End If
            End If

            '----- desconto consumidor rural -----
            If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 5 And (lstrUFUnidade = "RS" Or lstrUFUnidade = "GO") Then
                row_grid = 1 + row_grid
                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "9070000002"
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("9070000002") & "(10%)"
                grid_fatura.Col = 2
                grid_fatura.Text = ""
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format((vlrConsumo + vlrDemanda + vlrDem_ultrapassagem + vlrKvarh_consumo + vlrKvarh_demanda) * 0.1, "#,##0.00")

                vlrTotal = vlrTotal - CDbl(VB6.Format((vlrConsumo + vlrDemanda + vlrDem_ultrapassagem + vlrKvarh_consumo + vlrKvarh_demanda) * 0.1, "#,##0.00"))
                grid_fatura.Col = 4
                grid_fatura.Text = "(10%)"
            End If

            '----- desconto para o poder público -----
            If CDbl(Microsoft.VisualBasic.Left(lstrClasse, 1)) = 7 Then
                row_grid = 1 + row_grid

                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "9070000001"
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("9070000001") & " (15%)"
                grid_fatura.Col = 2
                grid_fatura.Text = ""
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format((vlrConsumo + vlrDemanda + vlrDem_ultrapassagem + vlrKvarh_consumo + vlrKvarh_demanda) * 0.15, "#,##0.00")

                vlrTotal = vlrTotal - CDbl(VB6.Format((vlrConsumo + vlrDemanda + vlrDem_ultrapassagem + vlrKvarh_consumo + vlrKvarh_demanda) * 0.15, "#,##0.00"))
                grid_fatura.Col = 4
                grid_fatura.Text = "(15%)"
            End If

            '-- Retenção Tributária
            If Microsoft.VisualBasic.Left(lstrClasse, 2) = "63" Then
                'vlr_retencao = Arredondar(vlrTotal * (retencao / 100), 2)
                vlr_retencao = Truncate(vlrTotal * (retencao / 100), 2)

                If vlr_retencao > 0 Then
                    row_grid = 1 + row_grid

                    grid_fatura.Rows = row_grid + 1
                    grid_fatura.Row = row_grid
                    grid_fatura.Col = 0
                    grid_fatura.Text = "9080000088"
                    grid_fatura.Col = 1
                    grid_fatura.Text = "RETENÇÃO TRIBUTÁRIA" 'codToDescri("9080000088")
                    grid_fatura.Col = 2
                    grid_fatura.Text = ""
                    grid_fatura.Col = 3
                    grid_fatura.Text = "-" & VB6.Format(vlr_retencao, "#,##0.00")
                End If
            End If

            'vlrPis = Arredondar((BaseICMS + BaseICMS2) * (idblAliqPIS / 100), 2) + Arredondar(baseICMSisenta * (idblAliqPIS / 100), 2)
            vlrPis = Truncate((BaseICMS + BaseICMS2) * (idblAliqPIS / 100), 2) + Truncate(baseICMSisenta * (idblAliqPIS / 100), 2)

            '-- Pis
            If vlrPis > 0 Then
                row_grid = 1 + row_grid

                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302020029" 'Valor de Pis
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("0302020029") & " ( " & VB6.Format(idblAliqPIS, "#,#####0.00000") & "% )"
                '& " ( " & BaseICMS & " )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(BaseICMS + BaseICMS2, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(vlrPis, "#,##0.00")

                vlrTotal = vlrTotal + CDbl(VB6.Format(vlrPis, "#,##0.00"))

                Item_Fatura = Trim(Item_Fatura & "40PIS00001?" & Replace(CStr(idblAliqPIS), ",", ".") & ";") ' Aliq de Pis
                Item_Fatura = Trim(Item_Fatura & "0302020033?" & Replace(CStr(BaseICMS + BaseICMS2), ",", ".") & ";") ' Base de Pis
            End If

            'vlrCofins = Arredondar((BaseICMS + BaseICMS2) * (idblAliqCofins / 100), 2) + Arredondar(baseICMSisenta * (idblAliqCofins / 100), 2)
            vlrCofins = Truncate((BaseICMS + BaseICMS2) * (idblAliqCofins / 100), 2) + Truncate(baseICMSisenta * (idblAliqCofins / 100), 2)

            '-- Cofins
            If vlrCofins > 0 Then
                row_grid = 1 + row_grid

                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302020030"
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("0302020030") & " ( " & VB6.Format(idblAliqCofins, "#,#####0.00000") & "% )"
                '& " ( " & BaseICMS & " )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(BaseICMS + BaseICMS2, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(vlrCofins, "#,##0.00")

                vlrTotal = vlrTotal + CDbl(VB6.Format(vlrCofins, "#,##0.00"))

                Item_Fatura = Trim(Item_Fatura & "40COF00001?" & Replace(CStr(idblAliqCofins), ",", ".") & ";") ' Aliq Cofins
                Item_Fatura = Trim(Item_Fatura & "0302020034?" & Replace(CStr(BaseICMS + BaseICMS2), ",", ".") & ";") ' Base de Cofins
            End If

            'ICMS = Arredondar(BaseICMS * (idblAliqICMS / 100), 2)
            ICMS = Truncate(BaseICMS * (idblAliqICMS / 100), 2)

            '-- ICMS 25%
            If ICMS > 0 Then
                row_grid = 1 + row_grid

                grid_fatura.Rows = row_grid + 1
                grid_fatura.Row = row_grid
                grid_fatura.Col = 0
                grid_fatura.Text = "0302030009"
                grid_fatura.Col = 1
                grid_fatura.Text = codTodescri("0302030009") & " ( " & VB6.Format(idblAliqICMS, "#,#####0.00000") & "% )"
                '& " ( " & BaseICMS & " x " & Format(idblAliqICMS, "#,##0.00") & "% )"
                grid_fatura.Col = 2
                grid_fatura.Text = VB6.Format(BaseICMS, "#,##0.00")
                grid_fatura.Col = 3
                grid_fatura.Text = VB6.Format(ICMS, "#,##0.00")
                grid_fatura.Col = 4
                grid_fatura.Text = ""
                'grid_fatura.Text = "( " & BaseICMS & " x " & Format(idblAliqICMS, "#,##0.00") & "% )"

                vlrTotal = vlrTotal + CDbl(VB6.Format(ICMS, "#,##0.00"))

                Item_Fatura = Trim(Item_Fatura & "0302030001?" & Replace(CStr(BaseICMS), ",", ".") & ";") ' Base ICMS
                Item_Fatura = Trim(Item_Fatura & "0302030002?" & Replace(CStr(idblAliqICMS), ",", ".") & ";") ' Aliq ICMS
            End If

            If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) = "01AS" Then
                'ICMS2 = Arredondar(BaseICMS2 * (idblAliqICMS2 / 100), 2)
                ICMS2 = Truncate(BaseICMS2 * (idblAliqICMS2 / 100), 2)
                '-- ICMS 12%
                If ICMS2 > 0 Then
                    row_grid = 1 + row_grid

                    grid_fatura.Rows = row_grid + 1
                    grid_fatura.Row = row_grid
                    grid_fatura.Col = 0
                    grid_fatura.Text = "0302030010"
                    grid_fatura.Col = 1
                    grid_fatura.Text = codTodescri("0302030010") & " ( " & VB6.Format(idblAliqICMS2, "#,#####0.00000") & "% )"
                    grid_fatura.Col = 2
                    grid_fatura.Text = VB6.Format(BaseICMS2, "#,##0.00")
                    grid_fatura.Col = 3
                    grid_fatura.Text = VB6.Format(ICMS2, "#,##0.00")
                    grid_fatura.Col = 4
                    grid_fatura.Text = ""

                    vlrTotal = vlrTotal + CDbl(VB6.Format(ICMS2, "#,##0.00"))

                    Item_Fatura = Trim(Item_Fatura & "0302030003?" & Replace(CStr(BaseICMS2), ",", ".") & ";") ' Base ICMS
                    Item_Fatura = Trim(Item_Fatura & "0302030013?" & Replace(CStr(idblAliqICMS2), ",", ".") & ";") ' Aliq ICMS
                End If
            End If
            Item_Fatura = Trim(Item_Fatura & "0302030014?" & Replace(CStr(ICMS2 + ICMS), ",", ".") & ";") ' Base ICMS
            BaseICMS = (BaseICMS + BaseICMS2)
            'FatorAjuste = Arredondar((BaseICMS - vlrTotal) - vlrIsentoIcms, 2)
            FatorAjuste = Truncate((BaseICMS - vlrTotal) - IIf(vlrIsentoIcms < 0, vlrIsentoIcms * -1, vlrIsentoIcms), 2)

            If FatorAjuste <> 0 Then
                BaseICMS = BaseICMS + (FatorAjuste * -1)

                grid_fatura.Col = 2
                grid_fatura.set_TextMatrix(grid_fatura.Row - 0, grid_fatura.Col, VB6.Format(BaseICMS - BaseICMS2, "#,##0.00"))
                grid_fatura.set_TextMatrix(grid_fatura.Row - 1, grid_fatura.Col, VB6.Format(BaseICMS, "#,##0.00"))
                grid_fatura.set_TextMatrix(grid_fatura.Row - 2, grid_fatura.Col, VB6.Format(BaseICMS, "#,##0.00"))
            End If

            '-----------------------------------------------------------------
            If gstrEmpresa_Sigla = "CHESP" Then
                CobrarSobreTaxa(vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
            End If
            If gstrEmpresa_Sigla = "EFLUL" Then
                CobrarSobreTaxaEflul(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
            End If
            CobrarParcelamento(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, idblConsId, idblUnidId, vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
            CobrarConvenios(vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms, coefTribSIcms)
            CobrarTaxas(vlrTotal, row_grid, idblAliqICMS, coefTribIcms, vlrIsentoIcms)
            '-----------------------------------------------------------------


            'MULTA/JUROS/CORRECAO MONETARIA
            'IMPORTANTE: O SISTEMA SÓ DEVE CALCULAR MULTA DO MES
            'ANTERIOR APENAS, OU SEJA, MES FATURAMENTO = 01/2007,
            'SÓ VAI CALCULAR MULTA E JUROS DO MES 12/2006, SE HOUVER.

            'verifa se ja foi calculado alguma multa para o mes em faturamento
            VerDelMultaJuro(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text)

            dtDataFat = CDate(VB6.Format("01/" & txtMesAno.Text, "dd/mm/yyyy"))
            dtDataRefMulta = System.DateTime.FromOADate(dtDataFat.ToOADate - 1)
            strMesRefMulta = VB6.Format(dtDataRefMulta, "mm/yyyy")

            CalculaMultaJuros(lstrZona, lstrLivro, lstrConta, strMesRefMulta)

            lstrSql = "SELECT * FROM `multajuros` WHERE isento = 0 and zona = '" & lstrZona & "' AND livro = '" & lstrLivro & "' AND conta = '" & lstrConta & "' AND cobrado = 'N';"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    'Multa
                    If row("vlrMulta") > 0 Then
                        row_grid = row_grid + 1
                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9080000061"
                        grid_fatura.Col = 1
                        grid_fatura.Text = codTodescri("9080000061") & " REF. MÊS " & row("mesano")
                        grid_fatura.Col = 2
                        grid_fatura.Text = ""
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(row("vlrMulta"), "#,##0.00")
                        grid_fatura.Col = 4
                        grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                        vlrTotal = vlrTotal + CDbl(VB6.Format(row("vlrMulta"), "#,##0.00"))
                    End If

                    'Juros
                    If row("vlrJuros") > 0 Then
                        row_grid = 1 + row_grid

                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9080000066"
                        grid_fatura.Col = 1
                        grid_fatura.Text = codTodescri("9080000066") & " REF. MÊS " & row("mesano")
                        grid_fatura.Col = 2
                        grid_fatura.Text = ""
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(row("vlrJuros"), "#,##0.00")
                        grid_fatura.Col = 4
                        grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                        'grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                        vlrTotal = vlrTotal + CDbl(VB6.Format(row("vlrJuros"), "#,##0.00"))
                    End If

                    'Correção monetária
                    If row("vlrCM") > 0 Then
                        row_grid = 1 + row_grid

                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "9080000067"
                        grid_fatura.Col = 1
                        grid_fatura.Text = codTodescri("9080000067") & " REF. MÊS " & row("mesano")
                        grid_fatura.Col = 2
                        grid_fatura.Text = ""
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(row("vlrCM"), "#,##0.00")
                        grid_fatura.Col = 4
                        grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                        'grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                        vlrTotal = vlrTotal + CDbl(VB6.Format(row("vlrCM"), "#,##0.00"))
                    End If

                Next

            End If



            'Passa o flag de COBRADO para S.
            'Depois temos que pensar num jeito de jogar esse cobrado
            'pra N se a nota for refaturada.

            lstrSql = "UPDATE `multajuros` SET cobrado = 'S' WHERE zona = '" & lstrZona & "' AND livro = '" & lstrLivro & "' AND conta = '" & lstrConta & "';"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            If Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) <> "01AS" Then
                '-- Iluminação Publica
                If Not lblnIsentoIluminacao Then

                    lstrSql = "SELECT * FROM `cip` WHERE cidade = " & llngCodigoCidade & " "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            TpConsumo = row("tpcons")
                            TpFaixaC = row("tpfaixa")
                        Next

                    Else
                        TpConsumo = "N"
                        TpFaixaC = "N"
                    End If


                    If TpConsumo = "A" Then
                        Ilum = Arredondar(Calc_ILUM(llngCodigoCidade, lstrClasse, ldblQtdConsumo, Demanda_Faturada, Dem_Ultrapassagem, TpFaixaC), 2)
                    Else
                        Ilum = Arredondar(Calc_ILUM(llngCodigoCidade, lstrClasse, ldblQtdConsumo, Demanda_Faturada, Dem_Ultrapassagem, TpFaixaC), 2)
                    End If

                    If Ilum > 0 Then
                        row_grid = 1 + row_grid

                        grid_fatura.Rows = row_grid + 1
                        grid_fatura.Row = row_grid
                        grid_fatura.Col = 0
                        grid_fatura.Text = "0301000003"
                        grid_fatura.Col = 1
                        grid_fatura.Text = codTodescri("0301000003")
                        grid_fatura.Col = 2
                        grid_fatura.Text = VB6.Format(Ilum, "#,##0.00")
                        grid_fatura.Col = 3
                        grid_fatura.Text = VB6.Format(Ilum, "#,##0.00")

                        vlrTotal = vlrTotal + CDbl(VB6.Format(Ilum, "#,##0.00"))
                    End If
                End If
            End If
            '----- Cálculo do arredondamento -----------------------------
            If GetConfig("arredondar.total.nf") = "S" And vlrTotal > 0 Then
                Arredondamento(vlrTotal, idblUnidId)
            End If
            '-------------------------------------------------------------

            grid_fatura.Redraw = True

            lblTotal.Text = VB6.Format(vlrTotal, "#,##0.00")
            lblTotalLiq.Text = lblTotal.Text

            System.Windows.Forms.Application.DoEvents()

            If lblnCalcReativo And lblnReativoNegativo Then

                MessageBox.Show("Problema no calculo do reativo, favor verificar!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Function Calc_ILUM(ByVal aintIdCidade As Short, ByVal astrClasse As String, ByVal adblConsumo As Double, ByVal adblDemanda As Double, ByVal adblUltrap As Double, ByVal astrTpFaixa As String) As Double

        Dim lstrSql As String
        Dim strTipo As String
        Dim dblIlum As Double
        Dim dblAuxIlum As Double
        Dim strAuxClass As String
        Dim lngFxIni As Integer
        Dim lngFxFim As Integer


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            dblAuxIlum = 0

            lstrSql = ""
            lstrSql = lstrSql & "SELECT * "
            lstrSql = lstrSql & "  FROM `cip` "
            lstrSql = lstrSql & " WHERE cidade = " & aintIdCidade & " "
            lstrSql = lstrSql & "   AND classe = " & Mid(Trim(astrClasse), 1, IIf(CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 6, 2, 1)) & " "
            lstrSql = lstrSql & "   AND " & Replace(CStr(adblConsumo), ",", ".") & " BETWEEN faixa_ini AND faixa_fim "
            lstrSql = lstrSql & "   AND data <= '" & VB6.Format(CDate(Me.txtDt_Leit_Atual.Text), "yyyy-MM-dd") & "' "
            lstrSql = lstrSql & " ORDER BY data DESC "
            lstrSql = lstrSql & " LIMIT 0, 1 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strTipo = IIf(IsDBNull(row("tipo")), "N", row("tipo"))
                    dblIlum = IIf(IsDBNull(row("valor")), 0, row("valor"))
                    lngFxIni = IIf(IsDBNull(row("faixa_ini")), 0, row("faixa_ini"))
                    lngFxFim = IIf(IsDBNull(row("faixa_fim")), 0, row("faixa_fim"))

                    If UCase(strTipo) = "P" And astrTpFaixa = "T" Then
                        If adblConsumo > lngFxFim Then
                            dblAuxIlum = lngFxFim * (dblIlum / 100)
                        Else
                            dblAuxIlum = adblConsumo * (dblIlum / 100)
                        End If
                    ElseIf UCase(strTipo) = "P" Then  'caso for percentual
                        dblAuxIlum = adblConsumo * (dblIlum / 100)
                    ElseIf UCase(strTipo) = "F" Then  'caso for valor fixo
                        dblAuxIlum = dblIlum
                    End If

                Next

            End If

            'Calc_ILUM = Arredondar(dblAuxIlum, 2)
            Calc_ILUM = Arredondar(dblAuxIlum, 2)

        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Function Calc_ILUM_Horo(ByVal aintIdCidade As Short, ByVal astrClasse As String, ByVal adblConsumoPonta As Double, ByVal adblConsumoFponta As Double, ByVal adblDemandaPonta As Double, ByVal adblDemandaFponta As Double, ByVal adblUltrapPonta As Double, ByVal adblUltrapFponta As Double, ByVal astrTpFaixa As String, ByVal adblTarConsumo_p As Double, ByVal adblTarConsumo_fp As Double) As Double

        Dim lstrSql As String
        Dim strTipo As String
        Dim dblIlum As Double
        Dim dblAuxIlum As Double
        Dim dblConsumo As Double
        Dim strAuxClass As String
        Dim lngFxIni As Integer
        Dim lngFxFim As Integer
        Dim Cod As Short
        Dim lintCidade As Integer
        Dim ldblCalcIlum As Double


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            dblConsumo = (adblConsumoPonta + adblConsumoFponta)

            If gstrEmpresa_Sigla = "CERCI" Then
                lstrSql = ""
                lstrSql = lstrSql & "SELECT * "
                lstrSql = lstrSql & "  FROM `cip` "
                lstrSql = lstrSql & " WHERE cidade = " & aintIdCidade & " "
                If aintIdCidade = 6891 Then
                    lstrSql = lstrSql & "   AND classe = " & Mid(Trim(astrClasse), 1, IIf(CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 6, 1, 1)) & " "
                End If
                lstrSql = lstrSql & " ORDER BY data DESC "
                lstrSql = lstrSql & " LIMIT 0, 1 "
            Else
                lstrSql = ""
                lstrSql = lstrSql & "SELECT * "
                lstrSql = lstrSql & "  FROM `cip` "
                lstrSql = lstrSql & " WHERE cidade = " & aintIdCidade & " "
                lstrSql = lstrSql & "   AND classe = " & Mid(Trim(astrClasse), 1, IIf(CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 6, 2, 1)) & " "
                lstrSql = lstrSql & "   AND " & Replace(CStr(dblConsumo), ",", ".") & " BETWEEN faixa_ini AND faixa_fim "
                lstrSql = lstrSql & "   AND data <= '" & VB6.Format(CDate(Me.txtDt_Leit_Atual.Text), "yyyy-MM-dd") & "' "
                lstrSql = lstrSql & " ORDER BY data DESC "
                lstrSql = lstrSql & " LIMIT 0, 1 "
            End If

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strTipo = IIf(IsDBNull(row("tipo")), "N", row("tipo"))
                    dblIlum = IIf(IsDBNull(row("valor")), 0, row("valor"))
                    lngFxIni = IIf(IsDBNull(row("faixa_ini")), 0, row("faixa_ini"))
                    lngFxFim = IIf(IsDBNull(row("faixa_fim")), 0, row("faixa_fim"))
                    If UCase(strTipo) = "P" And astrTpFaixa = "T" Then
                        If dblConsumo > lngFxFim Then
                            dblAuxIlum = lngFxFim * (dblIlum / 100)
                        Else
                            'dblAuxIlum = dblConsumo * (dblIlum / 100)
                            dblAuxIlum = (adblConsumoPonta * adblTarConsumo_p * dblIlum) / 100
                            dblAuxIlum += (adblConsumoFponta * adblTarConsumo_fp * dblIlum) / 100
                        End If
                    ElseIf UCase(strTipo) = "P" Then  'caso for percentual

                        dblAuxIlum = (adblConsumoPonta * adblTarConsumo_p * dblIlum) / 100
                        dblAuxIlum += (adblConsumoFponta * adblTarConsumo_fp * dblIlum) / 100

                    ElseIf UCase(strTipo) = "F" Then  'caso for valor fixo
                        If gstrEmpresa_Sigla = "CERCI" Then
                            If aintIdCidade = 6957 Then
                                dblAuxIlum = dblIlum * gdblUfita
                            ElseIf aintIdCidade = 6891 Then
                                dblAuxIlum = dblIlum * gdblUfir
                            End If
                        Else
                            dblAuxIlum = dblIlum 'caso for valor
                        End If

                    End If

                Next

            End If

            'Calc_ILUM_Horo = Arredondar(dblAuxIlum, 2)
            Calc_ILUM_Horo = Arredondar(dblAuxIlum, 2)


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function Calc_ICMS(ByRef base As Double, ByRef estado As String, ByRef aliq1 As Double, ByRef aliq2 As Double) As Double

        Dim localBase As Double


        Try

            localBase = base

            '    If estado = "GO" Then
            '        LocalBase = (LocalBase * aliq1) / (100 - aliq1)
            '    ElseIf estado = "RS" Then
            '        LocalBase = (LocalBase * aliq1) / (100 - aliq1)
            '    ElseIf estado = "SC" Then
            '        LocalBase = (LocalBase * aliq1) / (100 - aliq1)
            '    End If

            If estado = "GO" Then
                localBase = localBase / (1 - (aliq1 / 100))
            ElseIf estado = "RS" Then
                localBase = localBase / (1 - (aliq1 / 100))
            ElseIf estado = "SC" Then
                localBase = localBase / (1 - (aliq1 / 100))
            End If

            'Calc_ICMS = Arredondar(localBase, 2)
            Calc_ICMS = Truncate(localBase, 2)


        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Sub Grava_Fatura()

        Dim lblnFat As Boolean
        Dim ldteBase As Date
        Dim llngAux As Integer
        Dim lstrItensserv As String
        Dim lstrAuxHash As String
        Dim lstrCodHash As String
        Dim llngDias As Integer
        Dim lstrCodBarra As String
        Dim lstrDvCBarra As String
        Dim lstrSql As String
        Dim lstrSql_1 As String
        Dim lstrCodImagem As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            lblnFat = False

            ldteBase = Date.Now

            ''Recalculo
            If Val(lblTotal.Text) < 1 Then
                cmdCalcular_Click(cmdCalcular, New System.EventArgs())
            End If

            Me.lblStatus.Text = " Gravando leituras..."
            Me.lblStatus.Refresh()

            Grava_Leitura(False)

            System.Windows.Forms.Application.DoEvents()

            PegaIndContinuidade(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, "A", Me.txtMesAno.Text, Item_Fatura)

            ' Carrega item de serviço
            lstrItensserv = ""
            With Me.grid_fatura
                For llngAux = 1 To .Rows - 1
                    lstrItensserv = Trim(lstrItensserv) & Trim(.get_TextMatrix(llngAux, 0)) 'Código
                    lstrItensserv = Trim(lstrItensserv) & "?" & Trim(Replace(Replace(.get_TextMatrix(llngAux, 3), ".", ""), ",", ".")) 'Valor
                    lstrItensserv = Trim(lstrItensserv) & "$" & Trim(.get_TextMatrix(llngAux, 4)) & ";" 'referencia
                Next llngAux
            End With

            lstrItensserv = Trim(lstrItensserv)
            '
            Me.lblStatus.Text = " Gerando fatura..."
            Me.lblStatus.Refresh()
            Me.lblStatus.Text = " Gerando fatura - Validando se existe na arrecadação"
            Me.lblStatus.Refresh()
            If VerificaExisteArrecad(idblUnidId) Then
                MessageBox.Show("Já existe fatura em arrecadação para o mês " & Me.txtMesAno.Text & ".", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else

                Me.lblStatus.Text = " Gerando fatura - Gravando cabeçalho da fatura"
                Me.lblStatus.Refresh()

                idblNumNf = BuscaNumeroFaturaTransicao(idblUnidId, idblNsuNr)

                If idblNumNf = 0 Then

                    lblnFat = False
                    lstrSql = "INSERT INTO `nftransicao` SET "

                    If gstrEmpresa_Sigla.ToUpper() = "CERCI" Then
                        idblNumNf = CDbl(GetConfig("ultimo.nr.fiscal.rj")) + 1
                    ElseIf gstrEmpresa_Sigla.ToUpper() = "CERES" Then

                        If gstrEmpresa_UF.ToUpper() = "RJ" Then
                            idblNumNf = CDbl(GetConfig("ultimo.nr.fiscal.rj")) + 1
                        ElseIf gstrEmpresa_UF.ToUpper() = "MG" Then
                            idblNumNf = CDbl(GetConfig("ultimo.nr.fiscal.mg")) + 1
                        End If

                    Else
                        idblNumNf = CDbl(GetConfig("ultimo.nr.fiscal")) + 1
                    End If

                    If gstrEmpresa_UF = "SC" Then
                        idblNsuNr = CDbl(GetConfig("ultimo.nr.nsu")) + 1
                    End If

                Else
                    lblnFat = True
                    lstrSql = "UPDATE `nftransicao` SET "
                End If

                '------- INCIO CODIGO HASH -----------------
                lstrAuxHash = ""
                lstrAuxHash = lstrAuxHash & PreparaCampo(istrCpfCnpj, NUMERICO, 14, "0")
                lstrAuxHash = lstrAuxHash & PreparaCampo(CStr(idblNumNf), NUMERICO, 9, "0")
                lstrAuxHash = lstrAuxHash & PreparaCampo(Str(CDbl(Replace(Replace(VB6.Format(CDbl(Me.lblTotal.Text), "#,##0.00"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                lstrAuxHash = lstrAuxHash & PreparaCampo(Str(CDbl(Replace(Replace(VB6.Format(BaseICMS, "#,##0.00"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                lstrAuxHash = lstrAuxHash & PreparaCampo(Str(CDbl(Replace(Replace(VB6.Format(ICMS, "#,##0.00"), ",", ""), ".", ""))), NUMERICO, 12, "0")

                lstrSql_1 = "SELECT CONVERT(MD5('" & lstrAuxHash & "') USING latin1) `hash`"

                objAtualizaBancoDados.QUERY_NAME = lstrSql_1
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                If dt.Rows.Count <> 0 Then

                    For Each row As DataRow In dt.Rows
                        lstrCodHash = Trim(IIf(IsDBNull(row("hash")), "", row("hash")))
                    Next
                Else
                    lstrCodHash = ""
                End If

                Dim sBanco As String = fRetornaBancoImpFat(istrNrBco)

                '------- FIM CODIGO HASH -------------------
                MontaCodBarras(idblNumNf, Me.txtMesAno.Text, CDbl(Replace(Me.lblTotalLiq.Text, ".", "")), Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, lstrCodBarra, lstrDvCBarra, txtDt_Vencto.Text, lstrCodImagem, sBanco)
                If ilngAnoMes_Fat <= 202011 Then
                    llngDias = DateDiff(Microsoft.VisualBasic.DateInterval.Day, CDate(Me.txtDt_Leit_Anterior.Text), CDate(Me.txtDt_Leit_Atual.Text)) + 1
                Else
                    llngDias = DateDiff(Microsoft.VisualBasic.DateInterval.Day, CDate(Me.txtDt_Leit_Anterior.Text), CDate(Me.txtDt_Leit_Atual.Text))
                End If
                '
                lstrItensserv = lstrItensserv & Item_Fatura

                'essa marreta abaixo tem que melhorar vou desabilitar em 03/05/2021
                'depois que arrumar para ajustar base de icms para tirar diferença de centavos
                'If iintMicroGeracao = 1 Then
                '  If iblnMicroGeracaoConvenioSefaz Then
                '    lstrItensserv = ArrumaBaseIcms(lstrItensserv, iblnIcmsDemLida)
                '  End If
                'Else
                '  lstrItensserv = ArrumaBaseIcms(lstrItensserv, iblnIcmsDemLida)
                'End If
                '
                lstrSql = lstrSql & "`numnf`      =  " & idblNumNf & ", " & vbCrLf
                lstrSql = lstrSql & "`nsu`        =  " & idblNsuNr & ", " & vbCrLf
                lstrSql = lstrSql & "`codclas`    = '" & istrClasse & "', " & vbCrLf
                lstrSql = lstrSql & "`mesano`     = '" & Me.txtMesAno.Text & "', " & vbCrLf
                lstrSql = lstrSql & "`mesano_ref` = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & ", " & vbCrLf
                lstrSql = lstrSql & "`anomes_fat` = " & ilngAnoMes_Fat & ", " & vbCrLf
                lstrSql = lstrSql & "`cfop`       = " & Replace(CStr(idblCfop), ",", ".") & ", " & vbCrLf
                lstrSql = lstrSql & "`ta`         = '" & Me.txtTA.Text & "', " & vbCrLf
                lstrSql = lstrSql & "`grupo`      = 'A', " & vbCrLf
                lstrSql = lstrSql & "`flgst`      = '', " & vbCrLf
                lstrSql = lstrSql & "`valortot`   = " & Replace(Replace(Me.lblTotal.Text, ".", ""), ",", ".") & ", " & vbCrLf
                lstrSql = lstrSql & "`valorliq`   = " & Replace(Replace(Me.lblTotalLiq.Text, ".", ""), ",", ".") & ", " & vbCrLf
                lstrSql = lstrSql & "`codhash`    = '" & UCase(lstrCodHash) & "', " & vbCrLf

                lstrSql = lstrSql & "`datavenc`     = '" & VB6.Format(Me.txtDt_Vencto.Text, "yyyy-MM-dd") & "', " & vbCrLf
                lstrSql = lstrSql & "`dataapr`      = '" & VB6.Format(Me.txtDt_Apresenta.Text, "yyyy-MM-dd") & "', " & vbCrLf
                lstrSql = lstrSql & "`dataleit`     = '" & VB6.Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & "', " & vbCrLf
                lstrSql = lstrSql & "`dataem`       = '" & VB6.Format(ldteBase, "yyyy-MM-dd") & "', " & vbCrLf
                lstrSql = lstrSql & "`dataleitant`  = '" & VB6.Format(Me.txtDt_Leit_Anterior.Text, "yyyy-MM-dd") & "', " & vbCrLf
                lstrSql = lstrSql & "`dataproxleit` = '" & VB6.Format(Me.txtDt_Prox_Leit.Text, "yyyy-MM-dd") & "', " & vbCrLf
                lstrSql = lstrSql & "`datapag`      = '0000-00-00', " & vbCrLf

                lstrSql = lstrSql & "`cpf_cnpj` = '" & istrCpfCnpj & "', " & vbCrLf
                lstrSql = lstrSql & "`cons_id`  = " & idblConsId & ", " & vbCrLf
                lstrSql = lstrSql & "`unid_id`  = " & idblUnidId & ", " & vbCrLf
                lstrSql = lstrSql & "`zona`     = '" & Me.txtZona.Text & "', " & vbCrLf
                lstrSql = lstrSql & "`livro`    = '" & Me.txtLivro.Text & "', " & vbCrLf
                lstrSql = lstrSql & "`conta`    = '" & Me.txtConta.Text & "', " & vbCrLf
                lstrSql = lstrSql & "`rota`     = '" & istrcaderno & "', " & vbCrLf
                lstrSql = lstrSql & "`caderno`           = '" & istrcaderno & "', " & vbCrLf
                lstrSql = lstrSql & "`caderno_sequencia` =  " & Microsoft.VisualBasic.Right(IIf(istrRota <> "", istrRota, "0000"), 4) & ", " & vbCrLf
                lstrSql = lstrSql & "`rota_quatro`       = '" & Microsoft.VisualBasic.Left(IIf(istrRota <> "", istrRota, "0000"), 4) & "', " & vbCrLf

                lstrSql = lstrSql & "`itensserv` = '" & lstrItensserv & "', " & vbCrLf
                lstrSql = lstrSql & "`dias`   = " & llngDias & ", " & vbCrLf
                lstrSql = lstrSql & "`fase`   = '" & istrFase & "', " & vbCrLf
                lstrSql = lstrSql & "`tensao` = '" & istrTensao & "', " & vbCrLf
                lstrSql = lstrSql & "`banarrec`    = " & CInt(IIf(IsNumeric(istrNrBco), istrNrBco, 0)) & ", " & vbCrLf
                lstrSql = lstrSql & "`banco_fatur` = '" & VB6.Format(istrNrBco, "000") & "', " & vbCrLf
                lstrSql = lstrSql & "`banident`    = '" & istrNmBco & "', " & vbCrLf
                lstrSql = lstrSql & "`agencia`           = '" & istrAgencia & "', " & vbCrLf
                lstrSql = lstrSql & "`conta_corrente`    = '" & istrContaCorrente & "', " & vbCrLf

                lstrSql = lstrSql & "`parcialmente_cativo` = " & IIf(iblnParCativo, 1, 0) & ", " & vbCrLf
                lstrSql = lstrSql & "`periodo_teste`       = " & IIf(iblnPeriodoTeste, 1, 0) & ", " & vbCrLf
                lstrSql = lstrSql & "`livreespecial`       = " & iintLivreEspecial & ", " & vbCrLf
                lstrSql = lstrSql & "`livre_verde`         = " & iintLivreVerde & ", " & vbCrLf
                lstrSql = lstrSql & "`micro_geracao`       = " & iintMicroGeracao & ", " & vbCrLf
                lstrSql = lstrSql & "`micro_geracao_convenio_sefaz`       = " & IIf(iblnMicroGeracaoConvenioSefaz, 1, 0) & ", " & vbCrLf
                lstrSql = lstrSql & "`fatura_complementar`=0, "
                lstrSql = lstrSql & "`codbarra`   = '" & lstrCodBarra & "', " & vbCrLf
                'lstrSql = lstrSql & "`dvcodbarra` = '" & lstrDvCBarra & "' " & vbCrLf
                lstrSql = lstrSql & "`dvcodbarra` = '" & lstrDvCBarra & "', " & vbCrLf
                lstrSql = lstrSql & "`codbarra_imagem`   = '" & lstrCodImagem & "', " & vbCrLf
                lstrSql = lstrSql & "`uf`   = '" & iUF & "', " & vbCrLf
                lstrSql = lstrSql & "`ibge`   = '" & iIBGE & "' " & vbCrLf

                If lblnFat Then
                    lstrSql = lstrSql & "WHERE `numnf`   = " & idblNumNf & " " & vbCrLf
                    lstrSql = lstrSql & "  AND `mesano`  = '" & Me.txtMesAno.Text & "' " & vbCrLf
                Else

                    If gstrEmpresa_Sigla.ToUpper() = "CERCI" Then
                        SetConfig("ultimo.nr.fiscal.rj", "String", Trim(Str(idblNumNf)), Trim(Str(idblNumNf)), "")
                    ElseIf gstrEmpresa_Sigla.ToUpper() = "CERES" Then

                        If gstrEmpresa_UF.ToUpper() = "RJ" Then
                            SetConfig("ultimo.nr.fiscal.rj", "String", Trim(Str(idblNumNf)), Trim(Str(idblNumNf)), "")
                        ElseIf gstrEmpresa_UF.ToUpper() = "MG" Then
                            SetConfig("ultimo.nr.fiscal.mg", "String", Trim(Str(idblNumNf)), Trim(Str(idblNumNf)), "")
                        End If

                    Else
                        SetConfig("ultimo.nr.fiscal", "String", Trim(Str(idblNumNf)), Trim(Str(idblNumNf)), "")
                        End If

                        If gstrEmpresa_UF = "SC" Then
                            SetConfig("ultimo.nr.nsu", "String", Trim(Str(idblNsuNr)), Trim(Str(idblNsuNr)), "")
                        End If

                    End If

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                Me.lblStatus.Text = " Gerando fatura - Gravando Componentes da Fatura"
                Me.lblStatus.Refresh()
                ComponentesFatura()
                '
                Me.lblStatus.Text = " Gerando fatura - Criando itens de impressão da fatura"
                Me.lblStatus.Refresh()

                'Deleta o itens da temp_item_fatura de acordo com o numero da nf e o mesano do faturamento
                'Executar("DELETE FROM `temp_item_fatura` WHERE `numnf` = " & idblNumNf & " AND `mesano` = '" & Me.txtMesAno.Text & "' AND `anomes_fat` = " & ilngAnoMes_Fat, True)
                'Executar("ALTER TABLE `temp_item_fatura`AUTO_INCREMENT = 1")
                'Cria os itens da NFtransicao na temp_item_fatura de acordo com o numero da nftransicao e o mesano do faturamento
                lstrSql = ""
                ' lstrSql = lstrSql & " CREATE EVENT job_nf_temp_itens" & ilngAnoMes_Fat & "_" & idblNumNf & " ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 2 SECOND "
                ' lstrSql = lstrSql & " DO BEGIN "
                lstrSql = lstrSql & "  DELETE FROM `temp_item_fatura` WHERE `numnf` = " & idblNumNf & " AND `mesano` = '" & Me.txtMesAno.Text & "' AND `anomes_fat` = " & ilngAnoMes_Fat & "; "
                lstrSql = lstrSql & "  ALTER TABLE `temp_item_fatura`AUTO_INCREMENT = 1; "
                lstrSql = lstrSql & "  CALL criaitensfaturatrans2(" & idblNumNf & ",'" & Me.txtMesAno.Text & "'," & ilngAnoMes_Fat & "); "
                'lstrSql = lstrSql & " END; "

                objAtualizaBancoDados.QUERY_NAME = lstrSql
                repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                ' Executar(" criaitensfaturatrans2(" & idblNumNf & ",'" & Me.txtMesAno.Text & "'," & ilngAnoMes_Fat & ")", True)
                'Grava os itens tributados invidualmente
                Me.lblStatus.Text = " Gravando itens individuais de tributação."
                Me.lblStatus.Refresh()
                Grava_Itens_Tributados(idblNumNf, Me.txtMesAno.Text, CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)), ilngAnoMes_Fat)
                '
                Me.lblStatus.Text = " Gravação concluída da fatura de número: " & idblNumNf & "."
                Me.lblStatus.Refresh()

                SetLogNF(gFormularioParaLog, txtZona.Text, txtLivro.Text, txtConta.Text, vUsuario.LOGIN, idblNumNf, Me.lblTotalLiq.Text, ilngAnoMes_Fat, "A", "Calculo Grupo A", "N", DateTime.Now)

                MessageBox.Show("Gravação da fatura concluída com sucesso!" & vbCrLf & "Fatura:  " & idblNumNf & ".", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub Grava_Itens_Tributados(ByVal adbl_Id_NumNf As Double, ByVal astr_Id_MesAno As String, ByVal alng_Id_MesAnoRef As Integer, ByVal alng_Id_AnoMes_Fat As Integer)

        Dim lint_Aux_Trib As Short
        Dim lstr_Sql As String
        Dim lstr_Aux As String
        Dim lstr_Fix As String
        Dim lstr_Job As String
        Dim lstr_Dad As String


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            '
            lstr_Sql = "INSERT INTO `nf_itens_tributados` (`id_numnf`, `id_mesano`,`id_mesano_ref`,`id_anomes_fat`,`id_item`,`ds_item`,`rf_item`,`vl_item`) VALUES"
            '
            lstr_Fix = "("
            lstr_Fix = lstr_Fix & Replace(CStr(adbl_Id_NumNf), ",", ".") & ","
            lstr_Fix = lstr_Fix & "'" & astr_Id_MesAno & "',"
            lstr_Fix = lstr_Fix & alng_Id_MesAnoRef & ","
            lstr_Fix = lstr_Fix & alng_Id_AnoMes_Fat & ","
            '
            lstr_Dad = ""
            For lint_Aux_Trib = LBound(istr_Vlr_Icm) To UBound(istr_Vlr_Icm)
                'Item do icms
                lstr_Aux = "'" & istr_Ite_Icm(lint_Aux_Trib) & "'," 'código do item icms
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Ite_Icm(lint_Aux_Trib)) & "',''," 'descricao do item icms
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Ite_Icm(lint_Aux_Trib)), ",", ".") 'Valor do item do icms
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                'Base do icms
                lstr_Aux = "'" & istr_Bas_Icm(lint_Aux_Trib) & "'," 'código do base icms
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Bas_Icm(lint_Aux_Trib)) & "',''," 'descricao da base icms
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Bas_Icm(lint_Aux_Trib)), ",", ".") 'Valor da base do icms
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                'Valor do icms
                lstr_Aux = "'" & istr_Vlr_Icm(lint_Aux_Trib) & "'," 'código do valor icms
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Vlr_Icm(lint_Aux_Trib)) & "',''," 'descricao da valor icms
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Vlr_Icm(lint_Aux_Trib)), ",", ".") 'Valor da valor do icms
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                '
                'Item do pis
                lstr_Aux = "'" & istr_Ite_Pis(lint_Aux_Trib) & "'," 'código do item pis
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Ite_Pis(lint_Aux_Trib)) & "',''," 'descricao do item pis
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Ite_Pic(lint_Aux_Trib)), ",", ".") 'Valor do item do pis
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                'Base do pis
                lstr_Aux = "'" & istr_Bas_Pis(lint_Aux_Trib) & "'," 'código do base pis
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Bas_Pis(lint_Aux_Trib)) & "',''," 'descricao da base pis
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Bas_Pic(lint_Aux_Trib)), ",", ".") 'Valor da base do pis
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                'Valor do pis
                lstr_Aux = "'" & istr_Vlr_Pis(lint_Aux_Trib) & "'," 'código do valor pis
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Vlr_Pis(lint_Aux_Trib)) & "',''," 'descricao da valor pis
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Vlr_Pis(lint_Aux_Trib)), ",", ".") 'Valor da valor do pis
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                '
                'Item do cof
                lstr_Aux = "'" & istr_Ite_Cof(lint_Aux_Trib) & "'," 'código do item cof
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Ite_Cof(lint_Aux_Trib)) & "',''," 'descricao do item cof
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Ite_Pic(lint_Aux_Trib)), ",", ".") 'Valor do item do cof
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                'Base do cof
                lstr_Aux = "'" & istr_Bas_Cof(lint_Aux_Trib) & "'," 'código do base cof
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Bas_Cof(lint_Aux_Trib)) & "',''," 'descricao da base cof
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Bas_Pic(lint_Aux_Trib)), ",", ".") 'Valor da base do cof
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
                'Valor do cof
                lstr_Aux = "'" & istr_Vlr_Cof(lint_Aux_Trib) & "'," 'código do valor cof
                lstr_Aux = lstr_Aux & "'" & codTodescri(istr_Vlr_Cof(lint_Aux_Trib)) & "',''," 'descricao da valor cof
                lstr_Aux = lstr_Aux & Replace(CStr(idbl_Vlr_Cof(lint_Aux_Trib)), ",", ".") 'Valor da valor do cof
                lstr_Aux = lstr_Aux & ")"
                lstr_Dad = lstr_Dad & lstr_Fix & lstr_Aux & ","
            Next

            lstr_Job = ""
            lstr_Job = lstr_Job & "CREATE EVENT job_nf_itens_tributados" & alng_Id_AnoMes_Fat & "_" & adbl_Id_NumNf & " ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 2 SECOND "
            lstr_Job = lstr_Job & "DO BEGIN "
            lstr_Job = lstr_Job & " DELETE FROM `nf_itens_tributados` WHERE `id_numnf` = " & Replace(CStr(adbl_Id_NumNf), ",", ".") & " AND `id_mesano_ref` = " & alng_Id_MesAnoRef & " AND `id_anomes_fat` = " & alng_Id_AnoMes_Fat & ";"
            lstr_Job = lstr_Job & " ALTER TABLE `nf_itens_tributados` AUTO_INCREMENT = 1; "
            lstr_Job = lstr_Job & lstr_Sql & Microsoft.VisualBasic.Left(lstr_Dad, Len(lstr_Dad) - 1) & ";"
            lstr_Job = lstr_Job & "END;"


            objAtualizaBancoDados.QUERY_NAME = lstr_Job
            repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub ComponentesFatura()

        Dim ldblNumNF As Double
        Dim lstrGruTar As String
        Dim lstrItens As String
        Dim lstrCodigo As String
        Dim llngMesano As Integer
        Dim lstrAux As String
        Dim lstrMesAnoAux As String
        Dim lstrMesAnoOld As String
        '
        Dim ldblPerEnergia As Double 'Percentual
        Dim ldblPerTransmissao As Double 'Percentual
        Dim ldblPerDistribuicao As Double 'Percentual
        Dim ldblPerEncSetoriais As Double 'Percentual
        Dim ldblPerPerdas As Double 'Percentual
        Dim ldblPerTributosIcms As Double 'Percentual
        Dim ldblPerTributosPisCof As Double 'Percentual
        '
        Dim ldblVlrEnergia As Double 'valor
        Dim ldblVlrTransmissao As Double 'valor
        Dim ldblVlrDistribuicao As Double 'valor
        Dim ldblVlrEncSetoriais As Double 'valor
        Dim ldblVlrPerdas As Double 'valor
        Dim ldblVlrTributosIcms As Double 'valor
        Dim ldblVlrTributosPisCof As Double 'valor
        '
        Dim ldblItenValor As Double
        Dim lstrSql As String



        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try



            llngMesano = CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2))
            ldblVlrEnergia = 0
            ldblVlrTransmissao = 0
            ldblVlrDistribuicao = 0
            ldblVlrEncSetoriais = 0
            ldblVlrPerdas = 0
            ldblVlrTributosIcms = 0
            ldblVlrTributosPisCof = 0
            '
            GetTarifasComposicao(CDate(Me.txtDt_Leit_Atual.Text), ldblPerEnergia, ldblPerTransmissao, ldblPerDistribuicao, ldblPerEncSetoriais, ldblPerPerdas, ldblPerTributosIcms, ldblPerTributosPisCof)
            '
            lstrSql = "SELECT * FROM `nftransicao` WHERE cons_id = " & idblConsId & " and unid_id = " & idblUnidId & " AND mesano='" & Me.txtMesAno.Text & "' AND fatura_complementar =0"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    ldblNumNF = IIf(IsDBNull(row("numnf")), 0, row("numnf"))
                    lstrGruTar = IIf(IsDBNull(row("ta")), "", row("ta"))
                    lstrItens = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))

                    lstrMesAnoAux = ""
                    lstrMesAnoOld = ""
                    lstrSql = ""
                    lstrSql = lstrSql & "  SELECT * "
                    lstrSql = lstrSql & "    FROM `composicao` "
                    lstrSql = lstrSql & "   WHERE `referencia` <= " & llngMesano & " "
                    lstrSql = lstrSql & "     AND `ta` = '" & lstrGruTar & "' "
                    lstrSql = lstrSql & "ORDER BY `referencia` DESC, `codigo` ASC "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                    If dt.Rows.Count <> 0 Then

                        For Each row_1 As DataRow In dt.Rows

                            lstrMesAnoAux = IIf(IsDBNull(row_1("mesano")), "", row_1("mesano"))

                            If Len(Trim(lstrMesAnoOld)) = 0 Then
                                lstrMesAnoOld = lstrMesAnoAux
                            End If

                            If lstrMesAnoAux = lstrMesAnoOld Then

                                lstrCodigo = Trim(IIf(IsDBNull(row_1("codigo")), "", row_1("codigo")))
                                ldblItenValor = BuscaVlrItem(lstrItens, lstrCodigo)

                                If ldblItenValor <> 0 Then
                                    ldblVlrEnergia = ldblVlrEnergia + (ldblItenValor * (ldblPerEnergia / 100))
                                    ldblVlrTransmissao = ldblVlrTransmissao + (ldblItenValor * (ldblPerTransmissao / 100))
                                    ldblVlrDistribuicao = ldblVlrDistribuicao + (ldblItenValor * (ldblPerDistribuicao / 100))
                                    ldblVlrEncSetoriais = ldblVlrEncSetoriais + (ldblItenValor * (ldblPerEncSetoriais / 100))
                                    ldblVlrPerdas = ldblVlrPerdas + (ldblItenValor * (ldblPerPerdas / 100))
                                    ldblVlrTributosIcms = ldblVlrTributosIcms + (ldblItenValor * (ldblPerTributosIcms / 100))
                                    ldblVlrTributosPisCof = ldblVlrTributosPisCof + (ldblItenValor * (ldblPerTributosPisCof / 100))
                                End If
                            End If

                        Next

                    End If



                Next

            End If


            If (ldblVlrEnergia + ldblVlrTransmissao + ldblVlrDistribuicao + ldblVlrEncSetoriais + ldblVlrPerdas + ldblVlrTributosIcms + ldblVlrTributosPisCof) <> 0 Then
                lstrAux = ""
                lstrAux = lstrAux & "0302090001?" & Replace(CStr(Truncate(ldblVlrEnergia, 2)), ",", ".") & ";"
                lstrAux = lstrAux & "0302090002?" & Replace(CStr(Truncate(ldblVlrTransmissao, 2)), ",", ".") & ";"
                lstrAux = lstrAux & "0302090003?" & Replace(CStr(Truncate(ldblVlrDistribuicao, 2)), ",", ".") & ";"
                lstrAux = lstrAux & "0302090004?" & Replace(CStr(Truncate(ldblVlrEncSetoriais, 2)), ",", ".") & ";"
                lstrAux = lstrAux & "0302090006?" & Replace(CStr(Truncate(ldblVlrPerdas, 2)), ",", ".") & ";"
                lstrAux = lstrAux & "0302090007?" & Replace(CStr(Truncate(ldblVlrTributosIcms, 2)), ",", ".") & ";"
                lstrAux = lstrAux & "0302090008?" & Replace(CStr(Truncate(ldblVlrTributosPisCof, 2)), ",", ".") & ";"
                '
                lstrSql = "UPDATE `nftransicao` SET `itensserv` = CONCAT(`itensserv`,'" & lstrAux & "') "
                lstrSql = lstrSql & " WHERE `numnf` = " & ldblNumNF & " AND `mesano` = '" & Me.txtMesAno.Text & "' "

                objAtualizaBancoDados.QUERY_NAME = lstrSql
                repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub TarifaConvencional()

        Dim lstrCod As String
        Dim ldteAnt As Date
        Dim ldteAtu As Date


        Try

            ldteAnt = CDate(Me.txtDt_Leit_Anterior.Text)
            ldteAtu = CDate(Me.txtDt_Leit_Atual.Text)
            idblTarTe_B1 = TarifaProporcional(ldteAnt, ldteAtu, "01B1011301", 3, "") / 1000
            '[ Consumo ]
            lstrCod = Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) & "011101"
            tarConsumo = TarifaProporcional(ldteAnt, ldteAtu, lstrCod, 3) / 1000
            tarConsumoSemDesconto = 0 'tarConsumo
            'tarConsumoBan = TarifaProporcional(ldteAnt, ldteAtu, lstrCod, iintBanderiaVigente) / 1000
            tarConsumoBan = TarifaProporcionalBandeira(ldteAnt, ldteAtu, iintBanderiaVigente, idteBandeira) / 1000
            '[ Demanda ]
            lstrCod = Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) & "012101"
            tarDemanda = TarifaProporcional(ldteAnt, ldteAtu, lstrCod, 3)
            '[ Demanda Ultrapassagem ]
            lstrCod = Microsoft.VisualBasic.Left(Me.txtTA.Text, 4) & "012102"
            tarDemUltra = TarifaProporcional(ldteAnt, ldteAtu, lstrCod, 3)
            If istrRes414_Art93 = "S" Then
                tarDemUltra = Arredondar(tarDemanda * 2, 5)
            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub TarifaHorosazonal(Optional ByVal ablnParCat As Boolean = False)

        'Monta as tarifas do HoroSazonal
        Dim lintMesLeitAtual As Short
        Dim lstrCodigo As String
        Dim lstrGrTar As String
        Dim ldteLeitAnt As Date
        Dim ldteleitAtual As Date
        Dim ldblTarifa As Double
        Dim lblnPeriodo As Boolean

        Try

            ldteLeitAnt = CDate(Me.txtDt_Leit_Anterior.Text)
            ldteleitAtual = CDate(Me.txtDt_Leit_Atual.Text)
            lstrGrTar = Microsoft.VisualBasic.Left(Trim(Me.txtTA.Text), 4)

            lintMesLeitAtual = CShort(Month(ldteleitAtual))
            'Periodo seco / úmido
            lblnPeriodo = (lintMesLeitAtual >= iintMesIniPerSeco And lintMesLeitAtual <= iintMesFimPerSeco)
            '                      01                 6                  01                      12

            idblTarTe_B1 = TarifaProporcional(ldteLeitAnt, ldteleitAtual, "01B1011301", 3, "") / 1000

            '************************************************************
            '* Consumo na ponta                                         *
            '*               Período      Seco  ou  Úmido               *
            '************************************************************
            If ablnParCat Then 'Parc Cativo 'Implementando em 04/06/2014
                lstrCodigo = "01" & IIf(iintLivreVerde = 1, "AV", "AA") & IIf(lblnPeriodo, "011101", "011105")
                idblTarConsumo_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                idblTarConsumoSemDesconto_p = 0 'idblTarConsumo_p
                If Microsoft.VisualBasic.Left(lstrCodigo, 4) = "01AX" Then
                    idblTarConsumoBan_p = 0
                Else
                    idblTarConsumoBan_p = TarifaProporcionalBandeira(ldteLeitAnt, ldteleitAtual, iintBanderiaVigente, idteBandeira, "", istrClasse) / 1000
                End If
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_p), ",", ".") & "$;")
                'Bandeira
                lstrCodigo = "01" & IIf(iintLivreVerde = 1, "AV", "AA") & "0111" & iintBanderiaVigente & IIf(lblnPeriodo, "1", "5")
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumoBan_p), ",", ".") & "$;")
                '
                lstrCodigo = lstrGrTar & IIf(lblnPeriodo, "011101", "011105")
                If iintLivreVerde = 1 Then
                    idblTarConsumoLiv_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, Replace(Replace(Replace(lstrCodigo, "01AL", "01AV"), "011101", "011201"), "011105", "011205"), 3) / 1000
                Else
                    idblTarConsumoLiv_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                End If
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumoLiv_p), ",", ".") & "$;")
            Else
                lstrCodigo = lstrGrTar & IIf(lblnPeriodo, "011101", "011105")
                idblTarConsumo_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                If iintLivreVerde = 1 And lstrGrTar = "01AL" Then
                    idblTarConsumo_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, Replace(Replace(Replace(lstrCodigo, "01AL", "01AV"), "011101", "011201"), "011105", "011205"), 3) / 1000
                End If
                idblTarConsumoSemDesconto_p = 0 'idblTarConsumo_p
                If Microsoft.VisualBasic.Left(lstrCodigo, 4) = "01AX" Or Microsoft.VisualBasic.Left(lstrCodigo, 4) = "01AL" Then
                    idblTarConsumoBan_p = 0
                Else
                    idblTarConsumoBan_p = TarifaProporcionalBandeira(ldteLeitAnt, ldteleitAtual, iintBanderiaVigente, idteBandeira, "", istrClasse) / 1000
                End If
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_p), ",", ".") & "$;")
                'Bandeira
                lstrCodigo = lstrGrTar & "0111" & iintBanderiaVigente & IIf(lblnPeriodo, "1", "5")
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumoBan_p), ",", ".") & "$;")

                'TUSD PONTA
                lstrCodigo = lstrGrTar & "011205"
                idblTarConsumo_p_tusd = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_p_tusd), ",", ".") & "$;")

                'TE PONTA
                lstrCodigo = lstrGrTar & "011305"
                idblTarConsumo_p_te = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_p_te), ",", ".") & "$;")

            End If
            '************************************************************
            '* Consumo fora da ponta                                    *
            '*               Período      Seco  ou  Úmido               *
            '************************************************************
            If ablnParCat Then 'Parc Cativo 'Implementando em 04/06/2014
                lstrCodigo = "01" & IIf(iintLivreVerde = 1, "AV", "AA") & IIf(lblnPeriodo, "011102", "011106")
                idblTarConsumo_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                idblTarConsumoSemDesconto_fp = 0 'idblTarConsumo_fp
                If Microsoft.VisualBasic.Left(lstrCodigo, 4) = "01AX" Then
                    idblTarConsumoBan_fp = 0
                Else
                    idblTarConsumoBan_fp = TarifaProporcionalBandeira(ldteLeitAnt, ldteleitAtual, iintBanderiaVigente, idteBandeira, "", istrClasse) / 1000
                End If
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_fp), ",", ".") & "$;")
                'Bandeira
                lstrCodigo = "01" & IIf(iintLivreVerde = 1, "AV", "AA") & "0111" & iintBanderiaVigente & IIf(lblnPeriodo, "2", "6")
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumoBan_fp), ",", ".") & "$;")
                '
                lstrCodigo = lstrGrTar & IIf(lblnPeriodo, "011102", "011106")

                If iintLivreVerde = 1 Then
                    idblTarConsumoLiv_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, Replace(Replace(Replace(lstrCodigo, "01AL", "01AV"), "011102", "011202"), "011106", "011206"), 3) / 1000
                Else
                    idblTarConsumoLiv_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                End If
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumoLiv_fp), ",", ".") & "$;")
            Else
                lstrCodigo = lstrGrTar & IIf(lblnPeriodo, "011102", "011106")
                idblTarConsumo_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                If iintLivreVerde = 1 And lstrGrTar = "01AL" Then
                    idblTarConsumo_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, Replace(Replace(Replace(lstrCodigo, "01AL", "01AV"), "011102", "011202"), "011106", "011206"), 3) / 1000
                End If
                idblTarConsumoSemDesconto_fp = 0 'idblTarConsumo_fp
                If Microsoft.VisualBasic.Left(lstrCodigo, 4) = "01AX" Or Microsoft.VisualBasic.Left(lstrCodigo, 4) = "01AL" Then
                    idblTarConsumoBan_fp = 0
                Else
                    idblTarConsumoBan_fp = TarifaProporcionalBandeira(ldteLeitAnt, ldteleitAtual, iintBanderiaVigente, idteBandeira, "", istrClasse) / 1000
                End If
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_fp), ",", ".") & "$;")
                'Bandeira
                lstrCodigo = lstrGrTar & "0111" & iintBanderiaVigente & IIf(lblnPeriodo, "2", "6")
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumoBan_fp), ",", ".") & "$;")

                'TUSD FORA PONTA
                lstrCodigo = lstrGrTar & "011206"
                idblTarConsumo_fp_tusd = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_fp_tusd), ",", ".") & "$;")

                'TE FORA PONTA
                lstrCodigo = lstrGrTar & "011306"
                idblTarConsumo_fp_te = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
                Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarConsumo_fp_te), ",", ".") & "$;")

            End If
            '************************************************************
            '* Demanda na ponta                                         *
            '************************************************************
            lstrCodigo = lstrGrTar & "012101"
            idblTarDemanda_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
            Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarDemanda_p), ",", ".") & "$;")

            '************************************************************
            '* Demanda fora da ponta                                    *
            '************************************************************
            lstrCodigo = lstrGrTar & "012102"
            idblTarDemanda_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
            Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarDemanda_fp), ",", ".") & "$;")

            '************************************************************
            '* Demanda de ultrapassagem na ponta                        *
            '************************************************************
            lstrCodigo = lstrGrTar & "012103"
            'Se o art 93 da 414 estiver valendo entao o valor da tarifa da ultrapassagem é o valor da tarifa da demanda VEZES 2
            If istrRes414_Art93 = "S" Then
                idblTarDemUltra_p = Arredondar(idblTarDemanda_p * 2, 5)
            Else
                idblTarDemUltra_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
            End If
            Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarDemUltra_p), ",", ".") & "$;")
            '************************************************************
            '* Demanda de ultrapassagem fora da ponta                   *
            '************************************************************
            lstrCodigo = lstrGrTar & "012104"
            If istrRes414_Art93 = "S" Then
                idblTarDemUltra_fp = Arredondar(idblTarDemanda_fp * 2, 5)
            Else
                idblTarDemUltra_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
            End If
            Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(idblTarDemUltra_fp), ",", ".") & "$;")

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub HabilitaGuias()


        Try

            With Me.sstLeituras
                Me.sstLeituras.TabPages.Item(0).Visible = (iintTipoTarifa = 0) 'Convencional
                Me.sstLeituras.TabPages.Item(1).Visible = (iintTipoTarifa = 3) 'Autoprodutor
                Me.sstLeituras.TabPages.Item(2).Visible = (iintTipoTarifa = 1 Or iintTipoTarifa = 2) 'Horosazonal
                Me.sstLeituras.TabPages.Item(3).Visible = (Mid(Me.txtTA.Text, 3, 2) = "AL") 'CCEE

                'Convencional
                Me.txtLeit_Consumo.Enabled = (.TabPages.Item(0).Visible And iintTipoTarifa = 0)
                Me.txtLeit_Demanda.Enabled = (.TabPages.Item(0).Visible And iintTipoTarifa = 0)
                Me.txtLeit_Kvarh.Enabled = (.TabPages.Item(0).Visible And iintTipoTarifa = 0)
                'Horosazonal
                Me.txtConsumo_p.Enabled = (.TabPages.Item(2).Visible)
                Me.txtConsumo_FP.Enabled = (.TabPages.Item(2).Visible)

                Me.txtDemanda_p.Enabled = (.TabPages.Item(2).Visible And iintTipoTarifa = 2)
                Me.txtDemanda_FP.Enabled = (.TabPages.Item(2).Visible)
                Me.txtKvarh_P.Enabled = (.TabPages.Item(2).Visible)
                Me.txtKvarh_FP.Enabled = (.TabPages.Item(2).Visible)
                Me.txtDem_Exc_Ponta.Enabled = (.TabPages.Item(2).Visible And iintTipoTarifa = 2)


                Me.txt_Auto_Consumo.Enabled = (.TabPages.Item(1).Visible And iintTipoTarifa = 3)
                Me.txt_Auto_Dem_Supl.Enabled = (.TabPages.Item(1).Visible And iintTipoTarifa = 3)
                Me.txt_Auto_Deficit_Dem.Enabled = (.TabPages.Item(1).Visible And iintTipoTarifa = 3)
                Me.txt_Auto_Deficit_Dem_HI.Enabled = (.TabPages.Item(1).Visible And iintTipoTarifa = 3)
            End With


        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Private Sub Grava_Leitura(Optional ByVal ablnRegrava As Boolean = False)

        'Revisando em 15/05/2015

        Dim lstrSql As String
        Dim ldblRegAfetados As Double

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            If ablnRegrava And iblnExisteLeitura Then
                lstrSql = ""
                lstrSql = lstrSql & "DELETE FROM `leitura` "
                lstrSql = lstrSql & "      WHERE `id_consumidor` = " & idblConsId & " "
                lstrSql = lstrSql & "        AND `id_unid` = " & idblUnidId & " "
                lstrSql = lstrSql & "        AND `dt_faturamento` = '" & VB6.Format(Me.txtDt_Faturamento.Text, "yyyy-MM-dd") & "' "
                lstrSql = lstrSql & "        AND `mesano` = '" & Me.txtMesAno.Text & "' "

                objAtualizaBancoDados.QUERY_NAME = lstrSql
                repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                lstrSql = "INSERT INTO "
                iblnExisteLeitura = False

            Else

                If iblnExisteLeitura Then
                    lstrSql = "UPDATE "
                Else
                    lstrSql = "INSERT INTO "
                End If

            End If

            lstrSql = lstrSql & " `leitura` SET "
            ' datas
            lstrSql = lstrSql & "mesano           = '" & Me.txtMesAno.Text & "', "
            lstrSql = lstrSql & "anomes           =  " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & ", "
            lstrSql = lstrSql & "dt_leit_atual    = '" & VB6.Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & "', "
            lstrSql = lstrSql & "dt_leit_anterior = '" & VB6.Format(Me.txtDt_Leit_Anterior.Text, "yyyy-MM-dd") & "', "
            lstrSql = lstrSql & "dt_faturamento   = '" & VB6.Format(Me.txtDt_Faturamento.Text, "yyyy-MM-dd") & "', "
            lstrSql = lstrSql & "dt_vencto        = '" & VB6.Format(Me.txtDt_Vencto.Text, "yyyy-MM-dd") & "', "
            lstrSql = lstrSql & "dt_cadastro      = '" & VB6.Format(idteBase, "yyyy-MM-dd") & "', "
            lstrSql = lstrSql & "dt_apresenta     = '" & VB6.Format(Me.txtDt_Apresenta.Text, "yyyy-MM-dd") & "', "
            lstrSql = lstrSql & "dt_prox_leit     = '" & VB6.Format(Me.txtDt_Prox_Leit.Text, "yyyy-MM-dd") & "', "
            '
            If iintTipoTarifa = 0 Then
                lstrSql = lstrSql & "consumo_p        = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtLeit_Consumo.Text), Me.txtLeit_Consumo.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "consumo_fp       = 0, "
                lstrSql = lstrSql & "demanda_p        = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtLeit_Demanda.Text), Me.txtLeit_Demanda.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "demanda_fp       = 0, "
                lstrSql = lstrSql & "kvarh            = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtLeit_Kvarh.Text), Me.txtLeit_Kvarh.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "kvarh_fp         = 0, "
                lstrSql = lstrSql & "dem_exc_ponta    = 0, "
                lstrSql = lstrSql & "dem_exc_fp       = 0, "
                lstrSql = lstrSql & "par_cat_mwh_medio = 0, "
                lstrSql = lstrSql & "par_cat_horas     = 0, "
            Else
                lstrSql = lstrSql & "consumo_p        = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtConsumo_p.Text), Me.txtConsumo_p.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "consumo_fp       = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtConsumo_FP.Text), Me.txtConsumo_FP.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "demanda_p        = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtDemanda_p.Text), Me.txtDemanda_p.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "demanda_fp       = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtDemanda_FP.Text), Me.txtDemanda_FP.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "kvarh            = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtKvarh_P.Text), Me.txtKvarh_P.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "kvarh_fp         = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtKvarh_FP.Text), Me.txtKvarh_FP.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "dem_exc_ponta    = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtDem_Exc_Ponta.Text), Me.txtDem_Exc_Ponta.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "dem_exc_fp       = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtDem_Exc_FP.Text), Me.txtDem_Exc_FP.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "par_cat_mwh_medio = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtParCatMWhMedio.Text), Me.txtParCatMWhMedio.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "par_cat_horas     = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtParCatHoras.Text), Me.txtParCatHoras.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "reverso_p        = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtReverso_p.Text), Me.txtReverso_p.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "reverso_fp       = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtReverso_fp.Text), Me.txtReverso_fp.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "reverso_res_p        = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtReverso_Residuo_p.Text), Me.txtReverso_Residuo_p.Text, 0))), ",", ".") & ", "
                lstrSql = lstrSql & "reverso_res_fp       = " & Replace(CStr(CDbl(IIf(IsNumeric(Me.txtReverso_Residuo_fp.Text), Me.txtReverso_Residuo_fp.Text, 0))), ",", ".") & ", "

            End If

            lstrSql = lstrSql & "id_consumidor    = " & idblConsId & ", "
            lstrSql = lstrSql & "id_unid          = " & idblUnidId & ", "
            lstrSql = lstrSql & "zlc              = '" & Me.txtZona.Text & Me.txtLivro.Text & Me.txtConta.Text & "' "

            If iblnExisteLeitura Then
                lstrSql = lstrSql & "WHERE id_consumidor  = " & idblConsId & " "
                lstrSql = lstrSql & "  AND id_unid        = " & idblUnidId & " "
                lstrSql = lstrSql & "  AND dt_faturamento = '" & VB6.Format(Me.txtDt_Faturamento.Text, "yyyy-MM-dd") & "' "
            End If

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            iblnExisteLeitura = True


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub Carr_Leit_Anterior(Optional ByVal adteContratoDemanda As Date = #12:00:00 AM#, Optional ByVal adblDemandaContratadaPonta As Double = 0, Optional ByVal adblDemandaContratadaForaPonta As Double = 0)

        Dim lstrSql As String


        Dim llngMesano As Integer
        Dim ldblDemandaP(3) As Double
        Dim ldblDemandaFP(3) As Double
        Dim ldblAuxiliar As Double
        Dim llngConta As Integer

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try



            llngMesano = CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2))

            lstrSql = "SELECT * " & "  FROM `leitura` " & " WHERE id_consumidor = " & idblConsId & " " & "   AND id_unid = " & idblUnidId & " " & "   AND anomes < " & llngMesano & " ORDER BY anomes DESC " & " LIMIT 0, 1 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    ant_consumo_p = IIf(IsDBNull(row("consumo_p")), 0, row("consumo_p"))

                    ant_consumo_fp = IIf(IsDBNull(row("consumo_fp")), 0, row("consumo_fp"))

                    ant_demanda_p = IIf(IsDBNull(row("demanda_p")), 0, row("demanda_p"))

                    ant_demanda_fp = IIf(IsDBNull(row("demanda_fp")), 0, row("demanda_fp"))

                    ant_kvarh = IIf(IsDBNull(row("kvarh")), 0, row("kvarh"))

                    ant_kvarh_fp = IIf(IsDBNull(row("kvarh_fp")), 0, row("kvarh_fp"))

                    ant_demanda_ultra_p = IIf(IsDBNull(row("demanda_ultra_p")), 0, row("demanda_ultra_p"))

                    ant_demanda_ultra_fp = IIf(IsDBNull(row("demanda_ultra_fp")), 0, row("demanda_ultra_fp"))


                    ant_reverso_p = IIf(IsDBNull(row("reverso_p")), 0, row("reverso_p"))

                    ant_reverso_fp = IIf(IsDBNull(row("reverso_fp")), 0, row("reverso_fp"))

                    Me.lblStatus.Text = "Última leitura encontrada " & row("mesano")
                    Me.lblStatus.Refresh()

                Next
            Else

                lstrSql = "SELECT ult_leit_kwh_p, ult_leit_kwh_fp,ultleit_reverso_p,ultleit_reverso_p " & "  FROM `uc_faturamento` " & " WHERE cons_id = " & idblConsId & " " & "   AND unid_id = " & idblUnidId & " "

                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                If dt.Rows.Count <> 0 Then

                    For Each row As DataRow In dt.Rows

                        ant_consumo_p = IIf(IsDBNull(row("ult_leit_kwh_p")), 0, row("ult_leit_kwh_p"))

                        ant_consumo_fp = IIf(IsDBNull(row("ult_leit_kwh_fp")), 0, row("ult_leit_kwh_fp"))
                        ant_demanda_p = 0
                        ant_demanda_fp = 0
                        ant_kvarh = 0
                        ant_demanda_ultra_p = 0
                        ant_demanda_ultra_fp = 0
                        ant_kvarh_fp = 0

                        ant_reverso_p = IIf(IsDBNull(row("ultleit_reverso_p")), 0, row("ultleit_reverso_p"))

                        ant_reverso_fp = IIf(IsDBNull(row("ultleit_reverso_p")), 0, row("ultleit_reverso_p"))


                    Next

                End If


            End If



            System.Windows.Forms.Application.DoEvents()
            If gstrEmpresa_Sigla <> "EFLUL" Then
                ' Busca ultimos doze consumos para atender art.49 paragr.2. Menor dif. entre demandas 0302010015
                If iintTipoTarifa > 0 Then
                    lstrSql = "SELECT buscavlritem(itensserv,""0302010019"")+0 kwp, " & "       buscavlritem(itensserv,""0302010023"")+0 kwfp " & "  FROM `nf` USE INDEX (keycons, keyunid) " & " WHERE cons_id = " & idblConsId & "   AND unid_id = " & idblUnidId & "   AND CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) <= " & llngMesano & "   AND (dataleit <= """ & VB6.Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & """ AND " & "        dataleit >= """ & VB6.Format(adteContratoDemanda, "yyyy-MM-dd") & """) " & "   AND `fatura_complementar` = 0" & " ORDER BY dataleit DESC " & " LIMIT 0, 12 "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            ldblAuxiliar = IIf(IsDBNull(row("kwp")), 0, row("kwp"))
                            If ldblAuxiliar > ldblDemandaP(1) Then
                                ldblDemandaP(1) = ldblAuxiliar
                            Else
                                If ldblAuxiliar > ldblDemandaP(2) Then
                                    ldblDemandaP(2) = ldblAuxiliar
                                Else
                                    If ldblAuxiliar > ldblDemandaP(3) Then
                                        ldblDemandaP(3) = ldblAuxiliar
                                    End If
                                End If
                            End If


                            ldblAuxiliar = IIf(IsDBNull(row("kwfp")), 0, row("kwfp"))
                            If ldblAuxiliar > ldblDemandaFP(1) Then
                                ldblDemandaFP(1) = ldblAuxiliar
                            Else
                                If ldblAuxiliar > ldblDemandaFP(2) Then
                                    ldblDemandaFP(2) = ldblAuxiliar
                                Else
                                    If ldblAuxiliar > ldblDemandaFP(3) Then
                                        ldblDemandaFP(3) = ldblAuxiliar
                                    End If
                                End If
                            End If


                        Next

                    End If


                    For llngConta = 1 To 3
                        If ldblDemandaP(llngConta) <> 0 Then
                            If adblDemandaContratadaPonta > ldblDemandaP(llngConta) Then
                                nAjuste_Demanda_P = nAjuste_Demanda_P + (adblDemandaContratadaPonta - ldblDemandaP(llngConta))
                            End If
                        End If
                        If ldblDemandaFP(llngConta) <> 0 Then
                            If adblDemandaContratadaPonta > ldblDemandaFP(llngConta) Then
                                nAjuste_Demanda_FP = nAjuste_Demanda_FP + (adblDemandaContratadaForaPonta - ldblDemandaFP(llngConta))
                            End If
                        End If
                    Next llngConta
                    Me.txtAjusteDemandaP.Text = CStr(nAjuste_Demanda_P)
                    Me.txtAjusteDemandaFP.Text = CStr(nAjuste_Demanda_FP)
                End If
            End If




        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Private Function Busca_Aliquota_ICMS(ByRef astrUf As String, ByRef adblConsumo As Double, ByRef astrClasse As String) As Double

        Dim lstrCod As String
        Dim ldblLim As Double
        Dim ldblVlr As Double
        Dim lstrSql As String



        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            lstrSql = ""
            lstrSql = lstrSql & "  SELECT `codigos`.`num`, "
            lstrSql = lstrSql & "         `codigos`.`limitkwh`, "
            lstrSql = lstrSql & "         `codigos`.`valor` "
            lstrSql = lstrSql & "    FROM `codigos` "
            lstrSql = lstrSql & "   WHERE `codigos`.`datanova` <= """ & VB6.Format(Me.txtDt_Faturamento.Text, "yyyy-MM-dd") & """ "
            lstrSql = lstrSql & "     AND LEFT(`codigos`.`num`, 5)=""40" & astrUf & "A"""
            lstrSql = lstrSql & "ORDER BY `codigos`.`datanova` DESC, `codigos`.`num` ASC"

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows


                    lstrCod = IIf(IsDBNull(row("num")), "", row("num"))
                    ldblLim = CDbl(IIf(IsDBNull(row("limitkwh")), 9999999, row("limitkwh")))
                    ldblVlr = CDbl(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))

                    'Rural Classe 5 Codigo A00001
                    If lstrCod = "40" & astrUf & "A00001" Or lstrCod = "40" & astrUf & "A00012" Then
                        If Mid(Trim(astrClasse), 1, 1) = "5" Then
                            If astrUf = "RS" Then
                                Busca_Aliquota_ICMS = ldblVlr

                            Else
                                If adblConsumo <= ldblLim Then
                                    Busca_Aliquota_ICMS = ldblVlr

                                End If
                            End If
                        End If
                        'Rural Classe 5 Codigo A00009 Com Inscrição Estadual
                    ElseIf lstrCod = "40" & astrUf & "A00009" Then
                        If Mid(Trim(astrClasse), 1, 1) = "5" Then
                            If Len(Trim(istrInsEst)) > 0 Then
                                Busca_Aliquota_ICMS = ldblVlr

                            End If
                        End If
                        'Rural Classe 5 Codigo A00010 Sem Inscrição Estadual
                    ElseIf lstrCod = "40" & astrUf & "A00010" Then
                        If Mid(Trim(astrClasse), 1, 1) = "5" Then
                            If Len(Trim(istrInsEst)) < 1 Then
                                Busca_Aliquota_ICMS = ldblVlr

                            End If
                        End If
                        'Industrial e outros
                    ElseIf lstrCod = "40" & astrUf & "A00002" Then
                        If Val(Mid(Trim(astrClasse), 1, 1)) < 4 Or Mid(Trim(astrClasse), 1, 1) = "8" Or Mid(Trim(astrClasse), 1, 1) = "7" Then
                            Busca_Aliquota_ICMS = ldblVlr

                        End If
                        'Comercial Classe 4, P.P.M Classe 61, P.P.F Classe 63 Codigo A00003
                    ElseIf lstrCod = "40" & astrUf & "A00003" Then
                        If (Mid(Trim(astrClasse), 1, 1) = "4" Or Mid(Trim(astrClasse), 1, 2) = "61" Or Mid(Trim(astrClasse), 1, 2) = "63") Then
                            Busca_Aliquota_ICMS = ldblVlr

                        End If
                        'Poder Publico Estadual Classe 62 Codigo A00004 - Isento
                    ElseIf lstrCod = "40" & astrUf & "A00004" Then
                        If Mid(Trim(astrClasse), 1, 2) = "62" Then
                            Busca_Aliquota_ICMS = ldblVlr

                        End If
                        'Iluminação Publica Classe 64 Codigo A00007
                    ElseIf lstrCod = "40" & astrUf & "A00007" Then
                        If Mid(Trim(astrClasse), 1, 2) = "64" Then
                            Busca_Aliquota_ICMS = ldblVlr

                        End If
                        'Para Resindencial e Baixa Renda
                    ElseIf (lstrCod = "40" & astrUf & "A00005") Or (lstrCod = "40" & astrUf & "A00006") Or (lstrCod = "40" & astrUf & "A00008") Then
                        If Mid(Trim(astrClasse), 1, 1) = "9" Then
                            If adblConsumo <= ldblLim Then
                                Busca_Aliquota_ICMS = ldblVlr

                            End If
                        End If
                        'SERVICO PUBLICO
                    ElseIf lstrCod = "40" & astrUf & "A00011" Then
                        If Mid(Trim(astrClasse), 1, 1) = "7" Then
                            Busca_Aliquota_ICMS = ldblVlr

                        End If
                    End If



                Next

            End If

        Catch ex As Exception
            Exit Function
        End Try



    End Function

    Private Function RetNmBanco(ByRef alngBco As Integer) As String

        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            lstrSql = "SELECT * FROM  `bancos` where ban_id = " & alngBco & " "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    RetNmBanco = row("nmbco")
                Next

            Else
                RetNmBanco = ""
            End If


        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Sub Arredondamento(ByRef valorTotal As Double, ByVal unid_id As Double)

        Dim lstrSql As String


        Dim valorArredondado As Double
        Dim Arredondamento As Double
        Dim saldo As Double
        Dim casasDecimais As Double


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            casasDecimais = CDbl(Microsoft.VisualBasic.Right(VB6.Format(valorTotal, "#,##0.00"), 2)) / 100

            lstrSql = "SELECT arredonda FROM `uc_faturamento` WHERE unid_id = " & unid_id & " "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    If IsDBNull(row("arredonda")) Or Trim(row("arredonda")) = "" Then
                        saldo = 0#
                    Else
                        saldo = row("arredonda")
                    End If

                Next

            End If



            If casasDecimais <> 0.5 And casasDecimais <> 0# Then
                If casasDecimais > 0# And casasDecimais < 0.5 Then
                    If saldo = 0# Then
                        valorArredondado = valorTotal - casasDecimais
                        Arredondamento = casasDecimais * -1
                        saldo = (saldo + Arredondamento) * -1
                    Else
                        If CDbl(VB6.Format(0.5 - casasDecimais, "#,##0.00")) <= saldo Then
                            valorArredondado = valorTotal + (0.5 - casasDecimais)
                            Arredondamento = 0.5 - casasDecimais
                            saldo = saldo - Arredondamento
                        Else
                            valorArredondado = valorTotal - casasDecimais
                            Arredondamento = casasDecimais * -1
                            saldo = saldo + (Arredondamento * -1)
                        End If
                    End If
                ElseIf casasDecimais > 0.5 Then
                    If saldo = 0# Then
                        valorArredondado = valorTotal - casasDecimais + 0.5
                        Arredondamento = (casasDecimais - 0.5) * -1
                        saldo = (saldo + Arredondamento) * -1
                    Else
                        If CDbl(VB6.Format(1 - casasDecimais, "#,##0.00")) <= saldo Then
                            valorArredondado = valorTotal + (1 - casasDecimais)
                            Arredondamento = 1 - casasDecimais
                            saldo = saldo - Arredondamento
                        Else
                            valorArredondado = valorTotal - casasDecimais + 0.5
                            Arredondamento = (casasDecimais - 0.5) * -1
                            saldo = saldo + (Arredondamento * -1)
                        End If
                    End If
                End If
            Else
                valorArredondado = valorTotal
                Arredondamento = 0
            End If

            '----- Adiciona o item "Arredondamento" à nota fiscal ------------------------------------------
            grid_fatura.Rows = grid_fatura.Rows + 1
            grid_fatura.Row = grid_fatura.Rows - 1

            grid_fatura.Col = 0
            grid_fatura.Text = "0302990041"
            grid_fatura.Col = 1
            grid_fatura.Text = codTodescri("0302990041")
            grid_fatura.Col = 2
            grid_fatura.Text = ""
            grid_fatura.Col = 3
            grid_fatura.Text = VB6.Format(Arredondamento, "#,##0.00")
            '-----------------------------------------------------------------------------------------------

            valorTotal = valorArredondado

            '----- Atualiza a tabela `unidb` com o saldo restante do arredondamento -----------------------------------
            lstrSql = "UPDATE `uc_faturamento` SET arredonda_ant = " & Replace(CStr(saldo), ",", ".") & " WHERE unid_id = " & unid_id & " "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)
            '----------------------------------------------------------------------------------------------------------
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub VerDelMultaJuro(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String)

        Dim lstrSql As String
        Dim strTexto As String
        Dim intP1 As Short
        Dim intP2 As Short
        Dim intP3 As Short
        Dim intP4 As Short
        Dim strAux As String
        Dim strRef As String
        Dim dblValor As Double
        Dim dblNFMulta As Double
        Dim strMAAMulta As String

        Dim dt As DataTable
        Dim dt_1 As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            lstrSql = "SELECT itensserv " & "  FROM `nftransicao` " & " WHERE cons_id = " & idblConsId & "   AND unid_id = " & idblUnidId & "   AND mesano=""" & Me.txtMesAno.Text & """" & "   AND fatura_complementar =0 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strTexto = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))
                    intP1 = 1
                    intP1 = InStr(intP1, strTexto, "9080000061")
                    If intP1 > 0 Then
                        While intP1 <= Len(strTexto)
                            intP1 = InStr(intP1, strTexto, "9080000061")
                            If intP1 > 0 Then
                                intP2 = InStr(intP1, strTexto, ";") 'acha o final do codigo

                                strAux = Mid(strTexto, intP1, (intP2 - intP1) + 1) 'separa a parte do codigo?valor$referencia
                                '         123456789012345678901234567890123456
                                'strAux = 9080000061?0,8802$Fatura 24 12/2007;
                                'straux = 9080000061?366.79$(  REF. MÊS 05/2008 )

                                intP3 = InStr(1, strAux, "$") 'acha onde fica o inicio da referencia
                                intP4 = InStr(1, strAux, ";") 'acha onde fica o final da referencia
                                strRef = Mid(strAux, intP3 + 1, (intP4 - intP3) - 1)
                                strRef = Replace(Replace(Replace(Replace(Replace(strRef, "Fatura", ""), "(  REF. MÊS", ""), ")", ""), "(", ""), ")", "")
                                strMAAMulta = Microsoft.VisualBasic.Right(Trim(strRef), 7)
                                strRef = Replace(strRef, strMAAMulta, "") 'Left(strRef, Len(strRef) - 7)
                                dblNFMulta = Val(strRef)

                                lstrSql = "SELECT * FROM `multajuros` " & " WHERE zona = '" & astrZona & "' " & "   AND livro = '" & astrLivro & "' " & "   AND conta = '" & astrConta & "' " & "   AND mesano = '" & strMAAMulta & "' " & "   AND isento = 0 "
                                If dblNFMulta > 0 Then
                                    lstrSql = lstrSql & "   AND numnf = " & dblNFMulta
                                End If
                                'Clipboard.Clear
                                'Clipboard.SetText lstrSql

                                objAtualizaBancoDados.QUERY_NAME = lstrSql
                                dt_1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                                If dt_1.Rows.Count <> 0 Then

                                    For Each row_1 As DataRow In dt_1.Rows

                                        lstrSql = "DELETE FROM `multajuros` " & " WHERE zona = '" & astrZona & "' " & "   AND livro = '" & astrLivro & "' " & "   AND conta = '" & astrConta & "' " & "   AND mesano = '" & strMAAMulta & "' " & "   AND isento = 0 "
                                        If dblNFMulta > 0 Then
                                            lstrSql = lstrSql & "   AND numnf = " & dblNFMulta
                                        End If

                                        objAtualizaBancoDados.QUERY_NAME = lstrSql
                                        repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                                    Next

                                    intP1 = intP2 + 1

                                Else
                                    intP1 = Len(strTexto) + 1
                                End If
                            End If
                        End While
                    End If

                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try




    End Sub

    Private Function VerificaExisteArrecad(ByVal alngUnidId As Integer) As Boolean

        Dim lblnRet As Boolean
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            lblnRet = False

            lstrSql = ""
            lstrSql = lstrSql & "SELECT numnf, mesano, mesano_ref, unid_id, grupo, cons_id, zona, livro, conta "
            lstrSql = lstrSql & "  FROM `nf` "
            lstrSql = lstrSql & " WHERE `mesano` = '" & Me.txtMesAno.Text & "' "
            lstrSql = lstrSql & "   AND `mesano_ref` = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
            lstrSql = lstrSql & "   AND `anomes_fat` = " & ilngAnoMes_Fat & " "
            lstrSql = lstrSql & "   AND `unid_id` = " & alngUnidId & " "
            lstrSql = lstrSql & "   AND `grupo` = 'A' "
            lstrSql = lstrSql & "   AND `fatura_complementar`=0 "
            lstrSql = lstrSql & " LIMIT 0, 1 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    lblnRet = dt.Rows.Count
                Next

            End If

            VerificaExisteArrecad = lblnRet


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function BuscaNumeroFaturaTransicao(ByVal alngUnidId As Integer, Optional ByRef adblNsu As Double = 0) As Double

        Dim ldblRet As Double
        Dim lstrSql As String



        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            ldblRet = 0
            adblNsu = 0
            lstrSql = ""
            lstrSql = lstrSql & "SELECT `numnf`, `mesano`, `unid_id`, `grupo`, `mesano_ref`, `nsu` "
            lstrSql = lstrSql & "  FROM `nftransicao` "
            lstrSql = lstrSql & " WHERE `mesano` = '" & Me.txtMesAno.Text & "' "
            lstrSql = lstrSql & "   AND `mesano_ref` = " & CInt(Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2)) & " "
            lstrSql = lstrSql & "   AND `anomes_fat` = " & ilngAnoMes_Fat
            lstrSql = lstrSql & "   AND `unid_id` = " & alngUnidId & " "
            lstrSql = lstrSql & "   AND `grupo` = 'A' "
            lstrSql = lstrSql & "   AND `fatura_complementar`=0 "
            lstrSql = lstrSql & " LIMIT 0, 1 "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    ldblRet = CDbl(IIf(IsDBNull(row("numnf")), 0, row("numnf")))
                    adblNsu = CDbl(IIf(IsDBNull(row("nsu")), 0, row("nsu")))
                Next

            Else
                ldblRet = 0
                adblNsu = 0
            End If





            BuscaNumeroFaturaTransicao = ldblRet


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub PegaIndContinuidade(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrGrupo As String, ByVal astrMesAno As String, ByRef astrItens As String)

        'Metas
        Dim ldblMetaDec As Double
        Dim ldblMetaFec As Double
        Dim ldblMetaDic As Double
        Dim ldblMetaFic As Double
        Dim ldblMetaMic As Double
        'Realizados
        Dim ldblRealDec As Double
        Dim ldblRealFec As Double
        Dim ldblRealDic As Double
        Dim ldblRealFic As Double
        Dim ldblRealMic As Double
        'Ressarcimento
        Dim ldblVDic As Double
        Dim ldblVFic As Double
        Dim ldblVMic As Double
        Dim ldblVCM As Double
        'Outros
        Dim lstrMesAnoRef As String
        Dim lstrSql As String


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            lstrSql = ""
            lstrSql = lstrSql & "SELECT `indicadores`.`mesanoref`, "
            lstrSql = lstrSql & "       `indicadores`.`mdec`, "
            lstrSql = lstrSql & "       `indicadores`.`mfec`, "
            lstrSql = lstrSql & "       `indicadores`.`mdic`, "
            lstrSql = lstrSql & "       `indicadores`.`mfic`, "
            lstrSql = lstrSql & "       `indicadores`.`mdmic`, "
            lstrSql = lstrSql & "       `indicadores`.`rdec`, "
            lstrSql = lstrSql & "       `indicadores`.`rfec`, "
            lstrSql = lstrSql & "       `indicadores`.`rdic`, "
            lstrSql = lstrSql & "       `indicadores`.`rfic`, "
            lstrSql = lstrSql & "       `indicadores`.`rdmic`, "
            lstrSql = lstrSql & "       `indicadores`.`tipo`, "
            lstrSql = lstrSql & "       `indicadores`.`vdic`, "
            lstrSql = lstrSql & "       `indicadores`.`vfic`, "
            lstrSql = lstrSql & "       `indicadores`.`vdmic`, "
            lstrSql = lstrSql & "       `indicadores`.`vcm`"
            lstrSql = lstrSql & "  FROM `indicadores` "
            lstrSql = lstrSql & " WHERE `indicadores`.`zona`   = """ & astrZona & """ "
            lstrSql = lstrSql & "   AND `indicadores`.`livro`  = """ & astrLivro & """ "
            lstrSql = lstrSql & "   AND `indicadores`.`conta`  = """ & astrConta & """ "
            lstrSql = lstrSql & "   AND `indicadores`.`grupo`  = """ & astrGrupo & """ "
            lstrSql = lstrSql & "   AND `indicadores`.`mesano` = """ & astrMesAno & """ "
            lstrSql = lstrSql & "   AND `indicadores`.`tipo` = ""M"" "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    'Metas

                    ldblMetaDec = CDbl(IIf(IsDBNull(row("mdec")), 0, row("mdec")))

                    ldblMetaFec = CDbl(IIf(IsDBNull(row("mfec")), 0, row("mfec")))

                    ldblMetaDic = CDbl(IIf(IsDBNull(row("mdic")), 0, row("mdic")))

                    ldblMetaFic = CDbl(IIf(IsDBNull(row("mfic")), 0, row("mfic")))

                    ldblMetaMic = CDbl(IIf(IsDBNull(row("mdmic")), 0, row("mdmic")))
                    'Realizados

                    ldblRealDec = CDbl(IIf(IsDBNull(row("rdec")), 0, row("rdec")))

                    ldblRealFec = CDbl(IIf(IsDBNull(row("rfec")), 0, row("rfec")))

                    ldblRealDic = CDbl(IIf(IsDBNull(row("rdic")), 0, row("rdic")))

                    ldblRealFic = CDbl(IIf(IsDBNull(row("rfic")), 0, row("rfic")))

                    ldblRealMic = CDbl(IIf(IsDBNull(row("rdmic")), 0, row("rdmic")))

                    lstrMesAnoRef = Trim(IIf(IsDBNull(row("mesanoref")), astrMesAno, row("mesanoref")))
                    'Ressarcimento

                    ldblVDic = CDbl(IIf(IsDBNull(row("vdic")), 0, row("vdic")))

                    ldblVFic = CDbl(IIf(IsDBNull(row("vfic")), 0, row("vfic")))

                    ldblVMic = CDbl(IIf(IsDBNull(row("vdmic")), 0, row("vdmic")))

                    ldblVCM = CDbl(IIf(IsDBNull(row("vcm")), 0, row("vcm")))

                    astrItens = Trim(astrItens & "0302080101?" & Replace(CStr(ldblMetaDec), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080102?" & Replace(CStr(ldblMetaFec), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080103?" & Replace(CStr(ldblMetaDic), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080104?" & Replace(CStr(ldblMetaFic), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080105?" & Replace(CStr(ldblMetaMic), ",", ".") & "$;")

                    astrItens = Trim(astrItens & "0302080001?" & Replace(CStr(ldblRealDec), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080002?" & Replace(CStr(ldblRealFec), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080003?" & Replace(CStr(ldblRealDic), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080004?" & Replace(CStr(ldblRealFic), ",", ".") & "$;")
                    astrItens = Trim(astrItens & "0302080005?" & Replace(CStr(ldblRealMic), ",", ".") & "$;")

                    astrItens = Trim(astrItens & "0302080097?" & Replace(CStr(ldblVCM), ",", ".") & "$;") 'Ressarcimento Indicadores CM

                    astrItens = Trim(astrItens & "0302080099?0$" & lstrMesAnoRef & ";")
                    System.Windows.Forms.Application.DoEvents()


                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobraDevolveValorDiferencaTributacao(ByRef row_grid As Short, ByRef adblValorTotalFatura As Double)

        Dim ldblIcms As Double
        Dim ldblPis As Double
        Dim ldblCofins As Double
        Dim ldblNumNF As Double
        Dim lstrMesAno As String
        Dim lstrRef As String
        Dim lstrMsg As String
        Dim lstrCod As String
        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            lstrSql = "SELECT * "
            lstrSql = lstrSql & "  FROM `cob_dev_grupo_a_tributacao` "
            lstrSql = lstrSql & " WHERE `anomes_fat` = " & Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) & " "
            lstrSql = lstrSql & "   AND `cons_id` = " & idblConsId
            lstrSql = lstrSql & "   AND `unid_id` = " & idblUnidId

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    ldblNumNF = IIf(IsDBNull(row("numnf")), 0, row("numnf"))

                    lstrMesAno = IIf(IsDBNull(row("mesano")), "", row("mesano"))

                    ldblIcms = IIf(IsDBNull(row("icms")), 0, row("icms"))
                    adblValorTotalFatura = adblValorTotalFatura + ldblIcms

                    ldblPis = IIf(IsDBNull(row("pis")), 0, row("pis"))
                    adblValorTotalFatura = adblValorTotalFatura + ldblPis

                    ldblCofins = IIf(IsDBNull(row("cofins")), 0, row("cofins"))
                    adblValorTotalFatura = adblValorTotalFatura + ldblCofins
                    lstrRef = " (" & lstrMesAno & " )"
                    lstrMsg = IIf(ldblIcms >= 0, "COB.DIF.ICMS", "DEV.DIF.ICMS")
                    lstrCod = IIf(ldblIcms >= 0, "0302062009", "0302061009")
                    AdicionaGridItem(row_grid, lstrCod, lstrMsg, 0, ldblIcms, lstrRef, "S")
                    lstrMsg = IIf(ldblPis >= 0, "COB.DIF.PIS", "DEV.DIF.PIS")
                    lstrCod = IIf(ldblPis >= 0, "0302062029", "0302061029")
                    AdicionaGridItem(row_grid, lstrCod, lstrMsg, 0, ldblPis, lstrRef, "S")
                    lstrMsg = IIf(ldblCofins >= 0, "COB.DIF.COFINS", "DEV.DIF.COFINS")
                    lstrCod = IIf(ldblCofins >= 0, "0302062030", "0302061030")
                    AdicionaGridItem(row_grid, lstrCod, lstrMsg, 0, ldblCofins, lstrRef, "S")

                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobraDevoConDemRea(ByRef row_grid As Short, ByRef adblValorTotalFatura As Double, ByVal adblCoefTribIcms As Double, ByVal astrUf As String)

        'Consumo
        Dim ldblkWh_p As Double
        Dim ldblTarCon_p As Double
        Dim ldblTarBan_p As Double
        Dim ldblkWh_f As Double
        Dim ldblTarCon_f As Double
        Dim ldblTarBan_f As Double
        'Demanda
        Dim ldblkW_p As Double
        Dim ldblTarDem_p As Double
        Dim ldblkW_f As Double
        Dim ldblTarDem_f As Double
        'Reativo
        Dim ldblkvArh_p As Double
        Dim ldblTarRea_p As Double
        Dim ldblkvArh_f As Double
        Dim ldblTarRea_f As Double
        'Referencia
        Dim ldblNumeroFat As Double
        Dim llngAnoMesRef As Integer
        'Faturados
        Dim lstrItens As String
        Dim ldblQFatkWh_p As Double
        Dim ldblQFatkWh_f As Double
        Dim ldblVFatkWh_p As Double
        Dim ldblVFatkWh_f As Double
        Dim ldblVFatBan_p As Double
        Dim ldblVFatBan_f As Double
        Dim ldblQFatkW_p As Double
        Dim ldblQFatkW_f As Double
        Dim ldblVFatkW_p As Double
        Dim ldblVFatkW_f As Double
        Dim ldblQFatkvArh_p As Double
        Dim ldblQFatkvArh_f As Double
        Dim ldblVFatkvArh_p As Double
        Dim ldblVFatkvArh_f As Double
        'Diferenças
        Dim ldblDifkWh_p As Double
        Dim ldblDifkWh_f As Double
        Dim ldblDifBan_p As Double
        Dim ldblDifBan_f As Double
        Dim ldblDifkW_p As Double
        Dim ldblDifkW_f As Double
        Dim ldblDifkvArh_p As Double
        Dim ldblDifkvArh_f As Double

        'Outros
        Dim lstrRef As String
        Dim lstrMsg As String
        Dim lstrSql As String

        Dim dt As DataTable
        Dim dt_1 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try


            lstrSql = "SELECT id,zona,livro,conta,consumo_p,tar_con_p,tar_ban_p,consumo_f,tar_con_f,tar_ban_f,demanda_p,tar_dem_p,demanda_f,tar_dem_f,reativo_p,tar_rea_p,reativo_f,tar_rea_f,numero_fiscal,anomes_ref,anomes_fat "
            lstrSql = lstrSql & " FROM `cobranca_devolucao_grupo_a` "
            lstrSql = lstrSql & "WHERE zona = '" & Me.txtZona.Text & "' "
            lstrSql = lstrSql & "  AND livro = '" & Me.txtLivro.Text & "' "
            lstrSql = lstrSql & "  AND conta = '" & Me.txtConta.Text & "' "
            lstrSql = lstrSql & "  AND anomes_fat = " & Microsoft.VisualBasic.Right(Me.txtMesAno.Text, 4) & Microsoft.VisualBasic.Left(Me.txtMesAno.Text, 2) & " "


            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    'Consumo

                    ldblkWh_p = IIf(IsDBNull(row("consumo_p")), 0, row("consumo_p"))

                    ldblTarCon_p = IIf(IsDBNull(row("tar_con_p")), 0, row("tar_con_p"))

                    ldblTarBan_p = IIf(IsDBNull(row("tar_ban_p")), 0, row("tar_ban_p"))

                    ldblkWh_f = IIf(IsDBNull(row("consumo_f")), 0, row("consumo_f"))

                    ldblTarCon_f = IIf(IsDBNull(row("tar_con_f")), 0, row("tar_con_f"))

                    ldblTarBan_f = IIf(IsDBNull(row("tar_ban_f")), 0, row("tar_ban_f"))
                    'Demanda

                    ldblkW_p = IIf(IsDBNull(row("demanda_p")), 0, row("demanda_p"))

                    ldblTarDem_p = IIf(IsDBNull(row("tar_dem_p")), 0, row("tar_dem_p"))

                    ldblkW_f = IIf(IsDBNull(row("demanda_f")), 0, row("demanda_f"))

                    ldblTarDem_f = IIf(IsDBNull(row("tar_dem_f")), 0, row("tar_dem_f"))
                    'Reativo

                    ldblkvArh_p = IIf(IsDBNull(row("reativo_p")), 0, row("reativo_p"))

                    ldblTarRea_p = IIf(IsDBNull(row("tar_rea_p")), 0, row("tar_rea_p"))

                    ldblkvArh_f = IIf(IsDBNull(row("reativo_f")), 0, row("reativo_f"))

                    ldblTarRea_f = IIf(IsDBNull(row("tar_rea_f")), 0, row("tar_rea_f"))
                    'Referencia

                    ldblNumeroFat = IIf(IsDBNull(row("numero_fiscal")), 0, row("numero_fiscal"))

                    llngAnoMesRef = IIf(IsDBNull(row("anomes_ref")), 0, row("anomes_ref"))

                    lstrSql = "SELECT * "
                    lstrSql = lstrSql & " FROM `nf` "
                    lstrSql = lstrSql & "WHERE mesano_ref = " & llngAnoMesRef & " "
                    lstrSql = lstrSql & "  AND numnf = " & ldblNumeroFat & " "
                    'lstrSql = lstrSql & "  AND zona = '" & Me.txtZona.Text & "' "
                    'lstrSql = lstrSql & "  AND livro = '" & Me.txtLivro.Text & "' "
                    'lstrSql = lstrSql & "  AND conta = '" & Me.txtConta.Text & "' "

                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


                    If dt_1.Rows.Count <> 0 Then

                        For Each row_1 As DataRow In dt_1.Rows

                            lstrItens = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))
                            'Consumo
                            ldblQFatkWh_p = BuscaValorItem(lstrItens, "0302010010")
                            ldblQFatkWh_f = BuscaValorItem(lstrItens, "0302010011")
                            ldblVFatkWh_p = BuscaValorItem(lstrItens, "0302020010")
                            ldblVFatkWh_f = BuscaValorItem(lstrItens, "0302020011")
                            'Bandeira
                            ldblVFatBan_p = BuscaValorItem(lstrItens, "0302120010")
                            ldblVFatBan_f = BuscaValorItem(lstrItens, "0302120011")
                            'Demanda
                            ldblQFatkW_p = BuscaValorItem(lstrItens, "0302010021")
                            ldblQFatkW_f = BuscaValorItem(lstrItens, "0302010025")
                            ldblVFatkW_p = BuscaValorItem(lstrItens, "0302020021")
                            ldblVFatkW_f = BuscaValorItem(lstrItens, "0302020023")
                            'Reativos
                            ldblQFatkvArh_p = BuscaValorItem(lstrItens, "0302010013")
                            ldblQFatkvArh_f = BuscaValorItem(lstrItens, "0302010014")
                            ldblVFatkvArh_p = BuscaValorItem(lstrItens, "0302020013")
                            ldblVFatkvArh_f = BuscaValorItem(lstrItens, "0302020014")


                        Next

                    End If


                    'Calcula as diferenças
                    ldblDifkWh_p = Truncate(ldblkWh_p * ldblTarCon_p, 2) - ldblVFatkWh_p
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifkWh_p / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifkWh_p, "#,##0.00"))
                    '
                    ldblDifkWh_f = Truncate(ldblkWh_f * ldblTarCon_f, 2) - ldblVFatkWh_f
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifkWh_f / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifkWh_f, "#,##0.00"))
                    '
                    ldblDifBan_p = Truncate(ldblkWh_p * ldblTarBan_p, 2) - ldblVFatBan_p
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifBan_p / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifBan_p, "#,##0.00"))
                    '
                    ldblDifBan_f = Truncate(ldblkWh_f * ldblTarBan_f, 2) - ldblVFatBan_f
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifBan_f / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifBan_f, "#,##0.00"))
                    '
                    ldblDifkW_p = Truncate(ldblkW_p * ldblTarDem_p, 2) - ldblVFatkW_p
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifkW_p / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifkW_p, "#,##0.00"))
                    '
                    ldblDifkW_f = Truncate(ldblkW_f * ldblTarDem_f, 2) - ldblVFatkW_f
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifkW_f / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifkW_f, "#,##0.00"))
                    '
                    ldblDifkvArh_p = Truncate(ldblkvArh_p * ldblTarRea_p, 2) - ldblVFatkvArh_p
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifkvArh_p / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifkvArh_p, "#,##0.00"))
                    '
                    ldblDifkvArh_f = Truncate(ldblkvArh_f * ldblTarRea_f, 2) - ldblVFatkvArh_f
                    BaseICMS = BaseICMS + (Calc_ICMS(ldblDifkvArh_f / adblCoefTribIcms, astrUf, idblAliqICMS, 5))
                    adblValorTotalFatura = adblValorTotalFatura + CDbl(VB6.Format(ldblDifkvArh_f, "#,##0.00"))
                    'Consumo
                    If ldblDifkWh_p <> 0 Then
                        If Arredondar(ldblkWh_p, 2) - Arredondar(ldblQFatkWh_p, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkWh_p, 2) & "-" & Arredondar(ldblQFatkWh_p, 2) & "x" & ldblTarCon_p & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkWh_p, 2) & "x" & ldblTarCon_p & "-" & Arredondar(ldblVFatkWh_p, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifkWh_p >= 0, "COB.DIF.CON.P", "DEV.DIF.CON.P")
                        AdicionaGridItem(row_grid, "0302020010", lstrMsg, (ldblkWh_p - ldblQFatkWh_p), ldblDifkWh_p, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302011010?" & Replace(CStr(ldblkWh_p - ldblQFatkWh_p), ",", ".") & "$;")
                    End If
                    If ldblDifkWh_f <> 0 Then
                        If Arredondar(ldblkWh_f, 2) - Arredondar(ldblQFatkWh_f, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkWh_f, 2) & "-" & Arredondar(ldblQFatkWh_f, 2) & "x" & ldblTarCon_f & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkWh_f, 2) & "x" & ldblTarCon_f & "-" & Arredondar(ldblVFatkWh_f, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifkWh_f > 0, "COB.DIF.CON.FP", "DEV.DIF.CON.FP")
                        AdicionaGridItem(row_grid, "0302020011", lstrMsg, (ldblkWh_f - ldblQFatkWh_f), ldblDifkWh_f, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302011011?" & Replace(CStr(ldblkWh_f - ldblQFatkWh_f), ",", ".") & "$;")
                    End If
                    'Bandeira
                    If ldblDifBan_p <> 0 Then
                        If Arredondar(ldblkWh_p, 2) - Arredondar(ldblQFatkWh_p, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkWh_p, 2) & "-" & Arredondar(ldblQFatkWh_p, 2) & "x" & ldblTarBan_p & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkWh_p, 2) & "x" & ldblTarBan_p & "-" & Arredondar(ldblVFatBan_p, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifBan_p >= 0, "COB.DIF.BAN.P", "DEV.DIF.BAN.P") 'codTodescri("0302120010")
                        AdicionaGridItem(row_grid, "0302120010", lstrMsg, (ldblkWh_p - ldblQFatkWh_p), ldblDifBan_p, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302111010?" & Replace(CStr(ldblkWh_p - ldblQFatkWh_p), ",", ".") & "$;")
                    End If
                    If ldblDifBan_f <> 0 Then
                        If Arredondar(ldblkWh_f, 2) - Arredondar(ldblQFatkWh_f, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkWh_f, 2) & "-" & Arredondar(ldblQFatkWh_f, 2) & "x" & ldblTarBan_f & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkWh_f, 2) & "x" & ldblTarBan_f & "-" & Arredondar(ldblVFatBan_f, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifBan_f >= 0, "COB.DIF.BAN.FP", "DEV.DIF.BAN.FP") '& codTodescri("0302120011")
                        AdicionaGridItem(row_grid, "0302120011", lstrMsg, (ldblkWh_f - ldblQFatkWh_f), ldblDifBan_f, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302111011?" & Replace(CStr(ldblkWh_f - ldblQFatkWh_f), ",", ".") & "$;")
                    End If
                    'Demanda
                    If ldblDifkW_p <> 0 Then
                        If Arredondar(ldblkW_p, 2) - Arredondar(ldblQFatkW_p, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkW_p, 2) & "-" & Arredondar(ldblQFatkW_p, 2) & "x" & ldblTarDem_p & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkW_p, 2) & "x" & ldblTarDem_p & "-" & Arredondar(ldblVFatkW_p, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifkW_p >= 0, "COB.DIF.DEM.P", "DEV.DIF.DEM.P") '& codTodescri("0302020021")
                        AdicionaGridItem(row_grid, "0302020021", lstrMsg, (ldblkW_p - ldblQFatkW_p), ldblDifkW_p, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302011021?" & Replace(CStr(ldblkW_p - ldblQFatkW_p), ",", ".") & "$;")
                    End If
                    If ldblDifkW_f <> 0 Then
                        If Arredondar(ldblkW_f, 2) - Arredondar(ldblQFatkW_f, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkW_f, 2) & "-" & Arredondar(ldblQFatkW_f, 2) & "x" & ldblTarDem_f & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkW_f, 2) & "x" & ldblTarDem_f & "-" & Arredondar(ldblVFatkW_f, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifkW_f >= 0, "COB.DIF.DEM.FP", "DEV.DIF.DEM.FP") '& codTodescri("0302020023")
                        AdicionaGridItem(row_grid, "0302020023", lstrMsg, (ldblkW_f - ldblQFatkW_f), ldblDifkW_f, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302011023?" & Replace(CStr(ldblkW_f - ldblQFatkW_f), ",", ".") & "$;")
                    End If
                    'Reativo
                    If ldblDifkvArh_p <> 0 Then
                        If Arredondar(ldblkvArh_p, 2) - Arredondar(ldblQFatkvArh_p, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkvArh_p, 2) & "-" & Arredondar(ldblQFatkvArh_p, 2) & "x" & ldblTarRea_p & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkvArh_p, 2) & "x" & ldblTarRea_p & "-" & Arredondar(ldblVFatkvArh_p, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifkvArh_p >= 0, "COB.DIF.REA.P", "DEV.DIF.REA.P") '& codTodescri("0302020013")
                        AdicionaGridItem(row_grid, "0302020013", lstrMsg, (ldblkvArh_p - ldblQFatkvArh_p), ldblDifkvArh_p, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302011013?" & Replace(CStr(ldblkvArh_p - ldblQFatkvArh_p), ",", ".") & "$;")
                    End If
                    If ldblDifkvArh_f <> 0 Then
                        If Arredondar(ldblkvArh_f, 2) - Arredondar(ldblQFatkvArh_f, 2) <> 0 Then
                            lstrRef = " (" & Arredondar(ldblkvArh_f, 2) & "-" & Arredondar(ldblQFatkvArh_f, 2) & "x" & ldblTarRea_f & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        Else
                            lstrRef = " (" & Arredondar(ldblkvArh_f, 2) & "x" & ldblTarRea_f & "-" & Arredondar(ldblVFatkvArh_f, 2) & " " & Microsoft.VisualBasic.Right(CStr(llngAnoMesRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngAnoMesRef), 4) & ")"
                        End If
                        lstrMsg = IIf(ldblDifkvArh_f >= 0, "COB.DIF.REA.FP", "DEV.DIF.REA.FP") 'codTodescri("0302020014")
                        AdicionaGridItem(row_grid, "0302020014", lstrMsg, (ldblkvArh_f - ldblQFatkvArh_f), ldblDifkvArh_f, lstrRef, "S")
                        Item_Fatura = Trim(Item_Fatura & "0302011014?" & Replace(CStr(ldblkvArh_f - ldblQFatkvArh_f), ",", ".") & "$;")
                    End If

                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

#End Region


End Class