Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports System.Collections.Generic
Imports fatd_faturamento.ENTIDADE
Imports fatd_faturamento.BLL.Repositorio
Imports System.Configuration

Friend Class frmFatGrupoANovo
    Inherits System.Windows.Forms.Form

    Dim Id_Consumidor As Double
    Dim Id_Unid As Double
    Dim Id_Cidade As String
    Dim classe As String
    Dim zlc As String
    Dim vlrqh As Double
    Dim qh As String
    Dim cidade As String
    '-- 0 -> Insert / 1 -> Update
    Dim modo As Byte
    '-- Inscrição estadial
    Dim InscEst As String
    '-- 0-> Convencional / 1-> HS Verde / 2-> HS Azul
    Dim tarifa As Integer
    'geral
    Dim BaseICMS As Double
    Dim BasePis As Double
    Dim BaseCofins As Double
    Dim ICMS As Double
    '-- Leituras Anteriores
    Dim ant_consumo_p As Double
    Dim ant_consumo_fp As Double
    Dim ant_demanda_p As Double
    Dim ant_demanda_fp As Double
    Dim ant_kvarh As Double
    Dim ant_demanda_ultra_p As Double
    Dim ant_demanda_ultra_fp As Double
    Dim ant_kvarh_fp As Double
    Dim ant_consumo_reservado As Double
    Dim ant_kwh_cap_reat_fp As Double
    '-- Tarifas do Convencional
    Dim tarConsumo As Double
    Dim tarDemanda As Double
    Dim tarDemUltra As Double
    Dim tarExtra As Double

    '-- Tarifas do Horo-Sazonal (Verde e Azul)
    Dim tarConsumo_p As Double
    Dim tarConsumo_fp As Double
    Dim tarDemanda_p As Double
    Dim tarDemanda_fp As Double
    Dim tarDemUltra_p As Double
    Dim tarDemUltra_fp As Double
    Dim tarCons_Reservado As Double

    '-- Tarifas do Auto Produtor
    Dim tarAutoConsumo As Double
    Dim tarAutoDemanda As Double
    Dim tarAutoDeficitDem As Double
    Dim tarAutoDeficitDemHI As Double

    '-- Aliquotas
    Dim AliqPIS As Double
    Dim AliqCofins As Double
    Dim aliqICMS As Double
    '-- Contém todos os codigos que não aparecerão no grid
    Dim Item_Fatura As String
    Dim Cod_Aliquota_ICMS As String
    Dim FP As String
    '-- Pra ver o esquema da res. 49, paragr.2 - Ultimos 12 consumos demanda
    Dim dDataContrato As Date
    Dim nAjuste_Demanda_P As Double
    Dim nAjuste_Demanda_FP As Double
    Dim nQtiMeses As Short
    '-- tarifas com PIS e COFINS
    Dim tarConsumoPISCOF As Double
    Dim tarDemandaPISCOF As Double
    Dim tarConsumo_pPISCOF As Double
    Dim tarDemanda_pPISCOF As Double
    Dim tarConsumo_fpPISCOF As Double
    Dim tarDemanda_fpPISCOF As Double
    Private iintMesIniPerSeco As Short
    Private iintMesFimPerSeco As Short
    Private istrRes414_Art93 As String
    Private istrRes414_Art104 As String

    Private Sub cmdImprimir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImprimir.Click
        'Call CenterForm(frmRelLeitGrupoA)
        'Call frmRelLeitGrupoA.Show()
    End Sub

    Private Sub frmFatGrupoANovo_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
        If KeyAscii = 27 Then
            Me.Close()
        ElseIf KeyAscii = 13 Then
            ''Call SendKeysA(System.Windows.Forms.Keys.Tab, True)
        End If
        eventArgs.KeyChar = Chr(KeyAscii)
        If KeyAscii = 0 Then
            eventArgs.Handled = True
        End If
    End Sub

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

            Me.txtMesAno.Text = GetConfig("MESANOFATURAMENTO")
            Me.txtMesAno.Text = Format(Me.txtMesAno, "MM/yyyy")
            Call Enche_Grid()
            Me.SSTLeituras.SelectedIndex = 0
            iintMesIniPerSeco = Val(GetConfig("MES_INI_PERIODO_SECO"))
            iintMesFimPerSeco = iintMesIniPerSeco + 6

            istrRes414_Art93 = Trim(GetConfig("RESOLUCAO_414_ART_93"))
            If istrRes414_Art93 = "-1" Then
                istrRes414_Art93 = "N"
                Call SetConfig("RESOLUCAO_414_ART_93", istrRes414_Art93, True, "Aplicar a regra da resolução 414 artigo 93.")
            ElseIf Len(istrRes414_Art93) = 0 Then
                istrRes414_Art93 = "N"
                Call SetConfig("RESOLUCAO_414_ART_93", "String", istrRes414_Art93)
            End If
            istrRes414_Art104 = Trim(GetConfig("RESOLUCAO_414_ART_104"))
            If istrRes414_Art104 = "-1" Then
                istrRes414_Art104 = "N"
                Call SetConfig("RESOLUCAO_414_ART_104", istrRes414_Art104, True, "Aplicar a regra da resolução 414 artigo 104.")
            ElseIf Len(istrRes414_Art104) = 0 Then
                istrRes414_Art104 = "N"
                Call SetConfig("RESOLUCAO_414_ART_104", "String", istrRes414_Art104)
            End If
        Catch ex As Exception

        End Try
    End Sub

    'Private Sub mhgDados_ClickEvent(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mhgDados.ClickEvent
    '    ''If mhgDados.Rows > 1 Then
    '    ''    mhgDados.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightAlways
    '    ''End If
    'End Sub

    'Private Sub ''grid_fatura_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ''grid_fatura.DblClick
    '    '  Dim aux As String
    '    '
    '    '  With ''grid_fatura
    '    '    aux = "Informações do Item da Fatura" & vbCrLf & vbCrLf
    '    '    aux = aux & "Código: " & .TextMatrix(.Row, 0) & vbCrLf
    '    '    aux = aux & "Descrição: " & .TextMatrix(.Row, 1) & vbCrLf
    '    '    aux = aux & "Quantidade: " & .TextMatrix(.Row, 2) & vbCrLf
    '    '    aux = aux & "Valor: R$ " & .TextMatrix(.Row, 3) & vbCrLf
    '    '  End With
    '    '
    '    '  Call MsgBox(aux, vbInformation, gstrTituloMensagem)
    'End Sub

    'UPGRADE_WARNING: Event opbDesligados.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub opbDesligados_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbDesligados.CheckedChanged
        If eventSender.Checked Then
            Call Enche_Grid()
        End If
    End Sub

    'UPGRADE_WARNING: Event opbLigados.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub opbLigados_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbLigados.CheckedChanged
        If eventSender.Checked Then
            Call Enche_Grid()
        End If
    End Sub

    'UPGRADE_WARNING: Event opbTodos.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub opbTodos_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbTodos.CheckedChanged
        If eventSender.Checked Then
            Call Enche_Grid()
        End If
    End Sub

    'UPGRADE_WARNING: Event optZLC.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub optZLC_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optZLC.CheckedChanged
        If eventSender.Checked Then
            Call Enche_Grid()
        End If
    End Sub

    'UPGRADE_WARNING: Event optNome.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub optNome_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optNome.CheckedChanged
        If eventSender.Checked Then
            Call Enche_Grid()
        End If
    End Sub

    'UPGRADE_WARNING: Event optTarifa.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub optTarifa_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optTarifa.CheckedChanged
        If eventSender.Checked Then
            Call Enche_Grid()
        End If
    End Sub

    Private Sub cmdGravaLeitura_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGravaLeitura.Click
        Call Grava_Leitura("leitura")
    End Sub

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

    Private Sub cmdCalcular_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCalcular.Click
        If Len(Me.txtDt_Leit_Anterior.Text) = 0 Or Len(Me.txtDt_Leit_Atual.Text) = 0 Then
            Call MsgBox("É necessário informar as datas de leitura!", MsgBoxStyle.Critical, "Mensagem do Sistema!")
            Me.txtDt_Leit_Atual.Focus()
            Exit Sub
            System.Windows.Forms.Application.DoEvents()
        Else
            'Convencional
            If tarifa = 0 Then
                Call Calc_Convencional()
                'Auto Produtor
            ElseIf tarifa = 3 Then
                Call Calc_AutoProdutor()
                'Horo Sazonal
            Else
                Call Calc_HoroSazonal()
            End If
        End If
        If gstrEmpresa_Sigla = "COORSEL" Then
            Call cmdGravarFatura_Click(cmdGravarFatura, New System.EventArgs())
        End If
    End Sub

    Private Function getUltConsumo(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrCodConsumo As String) As Double
        Dim strItens As String
        Dim dblConsumo As Double
        'strsql = "SELECT itensserv " & "  FROM nf USE INDEX(keyzona,keylivro,keyconta) " & " WHERE zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """ " & "   AND CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) = (SELECT MAX(CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2))) " & "  FROM nf USE INDEX(keyzona,keylivro,keyconta) " & " WHERE zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """) "

        strItens = IIf(IsDBNull(GetValorTabela("nf", "itensserv", " zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """ " & "   AND CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) = (SELECT MAX(CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2))) " & "  FROM nf USE INDEX(keyzona,keylivro,keyconta) " & " WHERE zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """) ")), 0, GetValorTabela("nf", "itensserv", " zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """ " & "   AND CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) = (SELECT MAX(CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2))) " & "  FROM nf USE INDEX(keyzona,keylivro,keyconta) " & " WHERE zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """) "))
        dblConsumo = BuscaVlrItem(strItens, astrCodConsumo)
        getUltConsumo = dblConsumo

    End Function

    Private Function IncideICMS(ByVal astrCodigo As String) As Boolean
        Dim lstrAux As String = "N"

        'lstrSql = "SELECT flgcasc FROM codigos WHERE num = """ & astrCodigo & """;"

        lstrAux = IIf(IsDBNull(GetValorTabela("codigos", "flgcasc", "num = '" & astrCodigo & "'")), "N", GetValorTabela("codigos", "flgcasc", "num = '" & astrCodigo & "'"))

        IncideICMS = lstrAux
    End Function

    Private Function IncidePisCof(ByVal astrCodigo As String) As Boolean
        Dim lrstIncide As String = "N"

        lrstIncide = IIf(IsDBNull(GetValorTabela("codigos", "flgPisCof", "num = '" & astrCodigo & "'")), "N", GetValorTabela("codigos", "flgPisCof", "num = '" & astrCodigo & "'"))

        IncidePisCof = lrstIncide
    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 lstrSql As String
        Dim ldblValor As Double
        Dim ldblVlrAux As Double
        Dim lstrRefere As String
        Dim lstrCodigo As String
        Dim vlist

        Dim objSobreTaxa As New entidadeSobreTaxa
        Dim repositorioSobreTaxa As New repositorioSobreTaxa

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            objSobreTaxa.ZONA = astrZona
            objSobreTaxa.LIVRO = astrLivro
            objSobreTaxa.CONTA = astrConta
            objSobreTaxa.MESANO = Me.txtMesAno.Text


            vlist = repositorioSobreTaxa.Select_1(objSobreTaxa)

            If vlist.Count <> 0 Then

                For Each objSobreTaxaFor As entidadeSobreTaxa In vlist


                    ldblValor = CDbl(IIf(IsDBNull(objSobreTaxaFor.VALOR), 0, objSobreTaxaFor.VALOR))
                    lstrCodigo = IIf(IsDBNull(objSobreTaxaFor.CODIGO), 0, objSobreTaxaFor.CODIGO)
                    lstrRefere = IIf(IsDBNull(objSobreTaxaFor.REFERENCIA), "", objSobreTaxaFor.REFERENCIA)

                    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 = lstrCodigo
                        ''''grid_fatura.Col = 1
                        ''''grid_fatura.Text = Trim(CStr(lstrCodigo)) '& " " & consulta!referencia
                        ''''grid_fatura.Col = 2
                        ''''grid_fatura.Text = ""
                        ''''grid_fatura.Col = 3
                        ''''grid_fatura.Text = Format(ldblValor, "Standard")
                        ''''grid_fatura.Col = 4
                        ''''grid_fatura.Text = lstrRefere

                        If Mid(lstrCodigo, 1, 4) = "9070" Then
                            vlrTotal = vlrTotal - ldblValor
                        Else
                            If IncideICMS(lstrCodigo) Then
                                ldblVlrAux = ldblVlrAux + Calc_ICMS(ldblValor, GetConfig("EMPRESA_UF"), aliq, 5)
                                vlrTotal = vlrTotal + ldblValor
                                BaseICMS = BaseICMS + ldblVlrAux
                            Else
                                vlrIsentoIcms = vlrIsentoIcms + CDbl(Replace(CStr(ldblValor), ".", ","))
                                vlrTotal = vlrTotal + ldblValor
                            End If
                        End If
                    End If
                    '----- Seta a parcela como paga ---------------------------------------------
                    lstrSql = "UPDATE sobretaxa SET " & "       flag   = ""P"", " & "       mesano = """ & Me.txtMesAno.Text & """, " & "       cons_id = " & alngConsId & ", " & "       unid_id = " & alngUnidId & " " & " WHERE zona   = """ & astrZona & """ " & "   AND livro  = """ & astrLivro & """ " & "   AND conta  = """ & astrConta & """ " & "   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 CobrarSobreTaxa(ByRef vlrTotal As Double, ByRef row_grid As Short, ByRef aliq As Double, ByRef coef As Double, ByRef vlrIsentoIcms As Double)
        Dim sql As String
        Dim valor As Double
        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

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

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                ''strDetail = row("VALOR")

                row_grid = 1 + row_grid

                ''''grid_fatura.Rows = row_grid + 1
                ''''grid_fatura.Row = row_grid
                ''''grid_fatura.Col = 0
                ''''grid_fatura.Text = consulta.Fields("codigo")
                '' ''grid_fatura.Col = 1
                ''''grid_fatura.Text = Trim(CStr(consulta.Fields("codigo"))) & " " & consulta.Fields("referencia")
                ''''grid_fatura.Col = 2
                ''''grid_fatura.Text = ""
                ''''grid_fatura.Col = 3
                ''''grid_fatura.Text = Format(consulta.Fields("valor"), "Standard")

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

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

                objAtualizaBancoDados.QUERY_NAME = sql
                repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

            Next row

        End If

    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)
        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 lrstConAux As ADODB.Recordset
        'lrstConAux = New ADODB.Recordset
        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        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 """ & 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 = 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(CStr(lstrCdConv)) & "  " & lstrRefere
                ''    .Col = 2
                ''    .Text = ""
                ''    .Col = 3
                ''    .Text = Format(ldblValor, "Standard")
                ''    .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)
                        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)
                        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

        End If
    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 lrstConAux As ADODB.Recordset
        'lrstConAux = New ADODB.Recordset
        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        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 """ & 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 = 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(CStr(lstrCdTaxa)) & "  " & lstrRefere
                ''    .Col = 2
                ''    .Text = ""
                ''    .Col = 3
                ''    .Text = Format(ldblValor, "Standard")
                ''    .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)
                        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)
                        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
        End If

    End Sub

    ''Private Sub mhgDados_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mhgDados.DblClick
    ''    Me.lblStatus.Text = ""
    ''    With mhgDados
    ''        If .Row > 0 Then
    ''            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)
    ''            zlc = Replace(.get_TextMatrix(.Row, 0), ".", "")
    ''        End If
    ''    End With
    ''    Call txtConta.Focus()
    ''    Call SendKeysA(System.Windows.Forms.Keys.Tab, True)
    ''    Call Form_''grid_fatura()
    ''End Sub

    Private Sub Enche_() ''grid_fatura()
        Dim sql As String
        Dim mesano As String
        Dim I As Short
        ''Dim lrstAux As ADODB.Recordset
        ''lrstAux = New ADODB.Recordset
        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        'mesano = Mid(txtMesAno.Text, 1, 3) & "20" & Mid(txtMesAno.Text, 4)
        mesano = txtMesAno.Text
        sql = "SELECT * FROM NF WHERE CONS_ID=" & Id_Consumidor & " AND MESANO='" & mesano & "'"

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

        If dt.Rows.Count < 1 Then
            MsgBox("Erro! Não encontrado nenhuma fatura para esse periodo!")
            Exit Sub
        End If

        Call Form_() ''grid_fatura()
        'Destrincha o ItensServ para encher o ''grid_fatura
        'For i = 1 To Len(lrstAux!itensserv)
        'Call BuscaCodItem(i, lrstAux!itensserv)
        '''grid_fatura.Row = 1
        'cstr (codserv)
        'Next
        ''lrstAux.Close()
    End Sub

    Private Sub Forma_Grid()
        ''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

        ''Call Form_''grid_fatura()
        ''System.Windows.Forms.Application.DoEvents()
    End Sub

    Private Sub Form_() ''grid_fatura()
        ''''grid_fatura.Clear()
        ''''grid_fatura.Rows = 2
        ''lblTotal.Text = ""
        ''lblTotalLiq.Text = ""
        ''With ''grid_fatura
        ''    .set_ColWidth(0,  , 1200)
        ''    .set_ColWidth(1,  , 5000)
        ''    .set_ColWidth(2,  , 1480)
        ''    .set_ColWidth(3,  , 1480)
        ''    .set_ColWidth(4,  , 0)

        ''    .Col = 0
        ''    .Row = 0
        ''    .Text = "Código"

        ''    .Col = 1
        ''    .Text = "Descrição"

        ''    .Col = 2
        ''    .Text = "Quantidade"

        ''    .Col = 3
        ''    .Text = "Valor"

        ''    .Col = 4
        ''    .Text = "Composição"
        ''End With
    End Sub

    Private Sub Loca_Consumidor()
        Dim strsql As String
        Dim mesano As String
        ''Dim rsUnidA As ADODB.Recordset
        ''Dim rsLeitTmp As ADODB.Recordset

        ''rsUnidA = New ADODB.Recordset
        ''rsLeitTmp = New ADODB.Recordset

        Dim dt As DataTable
        Dim dt1 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        If Trim(txtZona.Text) <> "" And Trim(txtLivro.Text) <> "" And Trim(txtConta.Text) <> "" Then
            zlc = Me.txtZona.Text & Me.txtLivro.Text & Me.txtConta.Text

            strsql = "SELECT u.clas, u.unid_id, u.ta, u.nome, u.cons_id, u.cidade, u.qh, u.rg, u.insc, u.pessoa " & "  FROM uc_faturamento u " & " WHERE CONCAT(u.zona,u.livro,u.conta)=""" & txtZona.Text & txtLivro.Text & txtConta.Text & """ "
            If Me.opbLigados.Checked Then
                strsql = strsql & " AND UPPER(u.situacao) = 'L' "
            ElseIf Me.opbDesligados.Checked Then
                strsql = strsql & " AND UPPER(u.situacao) <> 'L' "
            End If

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

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    classe = IIf(IsDBNull(row("clas")), "", row("clas"))
                    Me.txtNome.Text = IIf(IsDBNull(row("nome")), "", row("nome"))
                    Me.txtTA.Text = IIf(IsDBNull(row("ta")), "", row("ta"))
                    Id_Consumidor = IIf(IsDBNull(row("cons_id")), 0, row("cons_id"))
                    Id_Unid = IIf(IsDBNull(row("unid_id")), 0, row("unid_id"))
                    qh = IIf(IsDBNull(row("qh")), "N", row("qh"))
                    InscEst = IIf(IsDBNull(row("insc")), "", row("insc"))

                    'Define o tipo de Tarifa
                    If Mid(txtTA.Text, 1, 4) = "01AV" Then
                        tarifa = 1
                    ElseIf Mid(txtTA.Text, 1, 4) = "01AA" Or Mid(txtTA.Text, 1, 4) = "01AL" Then
                        tarifa = 2
                    ElseIf Mid(txtTA.Text, 1, 4) = "01AP" Then
                        tarifa = 3
                    ElseIf Mid(txtTA.Text, 1, 4) = "01A4" Then
                        tarifa = 0
                    End If

                    'Carrega os valores anteriores do Leitura_Temp
                    txtLeit_Consumo.Text = ""
                    txtConsumo_FP.Text = ""
                    txtLeit_Demanda.Text = ""
                    txtDemanda_FP.Text = ""
                    txtLeit_Kvarh.Text = ""
                    txtKvarh_FP.Text = ""
                    txtKvarh_P.Text = ""
                    txtConsumo_p.Text = ""
                    txtDemanda_p.Text = ""
                    txtKvarh_P.Text = ""
                    txtReservado.Text = ""

                    mesano = Me.txtMesAno.Text

                    strsql = "SELECT * " & "  FROM leitura " & " WHERE id_unid = " & Id_Unid & "   AND id_consumidor = " & Id_Consumidor & " AND mesano = """ & mesano & """ "

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

                    If dt1.Rows.Count <> 0 Then
                        For Each row1 As DataRow In dt1.Rows
                            modo = 1
                            txtDt_Faturamento.Text = IIf(IsDBNull(row1("dt_faturamento")), "", Format(row1("dt_faturamento"), "dd/mm/yyyy"))
                            txtDt_Leit_Anterior.Text = IIf(IsDBNull(row1("dt_leit_anterior")), "", Format(row1("dt_leit_anterior"), "dd/mm/yyyy"))
                            txtDt_Prox_Leit.Text = IIf(IsDBNull(row1("dt_prox_leit")), "", Format(row1("dt_prox_leit"), "dd/mm/yyyy"))
                            txtDt_Leit_Atual.Text = IIf(IsDBNull(row1("dt_leit_atual")), "", Format(row1("dt_leit_atual"), "dd/mm/yyyy"))
                            txtDt_Vencto.Text = IIf(IsDBNull(row1("dt_vencto")), "", Format(row1("dt_vencto"), "dd/mm/yyyy"))
                            txtDem_Exc_Ponta.Text = IIf(IsDBNull(row1("dem_exc_ponta")), "", row1("dem_exc_ponta"))
                            txtDem_Exc_FP.Text = IIf(IsDBNull(row1("dem_exc_fp")), "", row1("dem_exc_fp"))
                            txtKwh_Cap_Reat_FP.Text = IIf(IsDBNull(row1("kwh_cap_reat_fp")), "", row1("kwh_cap_reat_fp"))
                            txtConsumo_FP.Text = IIf(IsDBNull(row1("consumo_fp")), "", row1("consumo_fp"))
                            txtDemanda_FP.Text = IIf(IsDBNull(row1("demanda_fp")), "", row1("demanda_fp"))
                            txtDt_Apresenta.Text = IIf(IsDBNull(row1("dt_apresenta")), "", Format(row1("dt_apresenta"), "dd/mm/yyyy"))
                            txtKvarh_FP.Text = IIf(IsDBNull(row1("Kvarh_fp")), "", row1("Kvarh_fp"))
                            txtReservado.Text = IIf(IsDBNull(row1("cons_reservado")), "", row1("cons_reservado"))

                            If tarifa < 1 Then
                                txtLeit_Consumo.Text = IIf(IsDBNull(row1("consumo_p")), "", row1("consumo_p"))
                                txtLeit_Demanda.Text = IIf(IsDBNull(row1("demanda_p")), "", row1("demanda_p"))
                                txtLeit_Kvarh.Text = IIf(IsDBNull(row1("kVArh")), "", row1("kVArh"))
                            Else
                                txtConsumo_p.Text = IIf(IsDBNull(row1("consumo_p")), "", row1("consumo_p"))
                                txtDemanda_p.Text = IIf(IsDBNull(row1("demanda_p")), "", row1("demanda_p"))
                                txtKvarh_P.Text = IIf(IsDBNull(row1("kVArh")), "", row1("kVArh"))
                            End If
                        Next
                    Else
                        txtLeit_Consumo.Text = ""
                        txtConsumo_FP.Text = ""
                        txtLeit_Demanda.Text = ""
                        txtDemanda_FP.Text = ""
                        txtLeit_Kvarh.Text = ""
                        txtKvarh_FP.Text = ""
                        txtKvarh_P.Text = ""
                        txtConsumo_p.Text = ""
                        txtDemanda_p.Text = ""
                        txtKvarh_P.Text = ""
                        txtReservado.Text = ""
                        txtDem_Exc_FP.Text = ""
                        txtDem_Exc_Ponta.Text = ""
                        txtKwh_Cap_Reat_FP.Text = ""
                        modo = 0
                    End If
                    AliqPIS = Busca_Aliquota_PIS()
                    AliqCofins = Busca_Aliquota_COFINS()
                    Call Enche_Grid()
                Next
            End If

            If tarifa = 1 Or tarifa = 2 Then
                SSTLeituras.SelectedIndex = 1
            ElseIf tarifa = 0 Then
                SSTLeituras.SelectedIndex = 0
            ElseIf tarifa = 3 Then
                SSTLeituras.SelectedIndex = 3
            End If
        End If

    End Sub

    Private Sub Calc_AutoProdutor()
        Dim sql As String
        Dim uf As String
        'Dim intDias               As Integer
        Dim intRowGrid As Short
        Dim dblQtConsumo As Double
        Dim dblVlrConsumo As Double
        Dim dblQtDemandaSupl As Double
        Dim dblVlrDemandaSupl As Double
        Dim dblQtDeficitDem As Double
        Dim dblVlrDeficitDem As Double
        Dim dblQtDeficitDemHI As Double
        Dim dblVlrDeficitDemHI As Double
        Dim dblConstanteConsumo As Double
        Dim dblConstanteDemanda As Double
        Dim dblConstanteKvarh As Double
        Dim dblPerdas As Double
        Dim dblClasse As Double
        Dim dblBaseICMS As Double
        Dim dblIcms As Double
        Dim dblVlrPis As Double
        Dim dblVlrIcmsPisCofins As Double
        Dim dblVlrCofins As Double
        Dim dblVlrEncargo As Double
        Dim dblVlrICMSEce As Double
        Dim dblAliqICMS As Double
        Dim dblVlrTotal As Double
        Dim dblDemandaContratada As Double
        Dim dblIlum As Double
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset

        '  Dim dblKvarh              As Double
        '  Dim dblVlrKvarhConsumo    As Double
        '  Dim dblVlrKvarhDemanda    As Double
        '  Dim dblAux                As Double
        '  Dim dblFatorPotencia      As Double
        '  Dim dblLeitDemandaAux     As Double
        '  Dim dblLeitConsumoAux     As Double
        '  Dim dblBaseDemandaReativa As Double

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        sql = "SELECT * FROM uc_faturamento WHERE cons_id = " & Id_Consumidor & " AND unid_id = " & Id_Unid

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                dblConstanteConsumo = IIf(IsDBNull(row("Const_consumo")), 0, row("Const_consumo"))
                dblPerdas = IIf(IsDBNull(row("final")), 0, row("final"))
                dblConstanteDemanda = IIf(IsDBNull(row("const_demanda")), 0, row("const_demanda"))
                dblDemandaContratada = IIf(IsDBNull(row("demanda_contr")), 0, row("demanda_contr"))
                dDataContrato = IIf(IsDBNull(row("data_contrato_demanda")), "1951-01-01", row("data_contrato_demanda"))
                dblConstanteKvarh = IIf(IsDBNull(row("const_kvarh")), 0, row("const_kvarh"))
                If UCase(IIf(IsDBNull(row("pessoa")), "F", row("pessoa"))) = "J" Then
                    InscEst = row("insc")
                Else
                    InscEst = row("rg")
                End If
                If IsDBNull(row("uf")) Then
                    MsgBox("O consumidor " & row("Zona") & row("Livro") & row("Conta") & ", não possui UF!" & Chr(10) & Chr(13) & "*** Não faturado! ***", MsgBoxStyle.Critical, "Mensagem do Sistema!")

                    Exit Sub
                Else
                    uf = row("uf")
                End If
            Next
        Else
            Me.Close()
        End If



        Call Form_() ''grid_fatura()
        lblTotal.Text = "0,00"
        lblTotalLiq.Text = "0,00"
        dblBaseICMS = 0
        intRowGrid = 0
        dblAliqICMS = 29

        'intDias = CDate(txtDt_Leit_Atual.Text) - CDate(txtDt_Leit_Anterior.Text)

        Call Carr_Tarifa_AutoProdutor()

        '-- Consumo
        dblQtConsumo = Val(Txt_Auto_Consumo.Text)
        If dblConstanteConsumo > 0 Then
            dblQtConsumo = dblQtConsumo * dblConstanteConsumo
        End If
        If dblPerdas > 0 Then
            dblQtConsumo = dblQtConsumo + (dblQtConsumo * (dblPerdas / 100))
        End If
        dblQtConsumo = System.Math.Round(dblQtConsumo)
        dblVlrConsumo = dblQtConsumo * tarAutoConsumo
        If dblVlrConsumo <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020008"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = Trim(CStr("0302020008")) & " ( " & dblQtConsumo & " x " & tarAutoConsumo & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = CStr(dblQtConsumo)
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrConsumo, "Standard")
            ''''grid_fatura.Col = 4
            ''''grid_fatura.Text = "( " & dblQtConsumo & " x " & tarAutoConsumo & " )"
            dblBaseICMS = dblBaseICMS + Calc_ICMS(dblVlrConsumo, uf, dblAliqICMS, 0) + dblVlrConsumo
            dblVlrTotal = dblVlrTotal + dblVlrConsumo
            dblVlrPis = Aplica_Pis(dblQtConsumo, dblAliqICMS, tarAutoConsumo, 5)
            dblVlrCofins = Aplica_Cofins(dblQtConsumo, dblAliqICMS, tarAutoConsumo, 5)
        End If

        '-- Demanda Suplementar
        dblQtDemandaSupl = Val(Replace(Txt_Auto_Dem_Supl.Text, ",", "."))
        If dblConstanteDemanda > 0 Then
            dblQtDemandaSupl = dblQtDemandaSupl * dblConstanteDemanda
        End If
        If dblPerdas > 0 Then
            dblQtDemandaSupl = dblQtDemandaSupl + (dblQtDemandaSupl * (dblPerdas / 100))
        End If

        dblVlrDemandaSupl = dblQtDemandaSupl * tarAutoDemanda
        If dblVlrDemandaSupl <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020015"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302020015") & " ( " & dblQtDemandaSupl & " x " & tarAutoDemanda & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = CStr(dblQtDemandaSupl)
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrDemandaSupl, "Standard")
            ''''grid_fatura.Col = 4
            ''''grid_fatura.Text = "( " & dblQtDemandaSupl & " x " & tarAutoDemanda & " )"
            dblBaseICMS = dblBaseICMS + dblVlrDemandaSupl + Calc_ICMS(dblVlrDemandaSupl, uf, dblAliqICMS, 0)
            dblVlrTotal = dblVlrTotal + dblVlrDemandaSupl
            dblVlrPis = Aplica_Pis(dblQtDemandaSupl, dblAliqICMS, tarAutoDemanda, 2) + dblVlrPis
            dblVlrCofins = Aplica_Cofins(dblQtDemandaSupl, dblAliqICMS, tarAutoDemanda, 2) + dblVlrCofins
        End If

        '-- Deficit Demanda
        dblQtDeficitDem = Val(Replace(Txt_Auto_Deficit_Dem.Text, ",", "."))
        If dblConstanteDemanda > 0 Then
            dblQtDeficitDem = dblQtDeficitDem * dblConstanteDemanda
        End If

        dblVlrDeficitDem = dblQtDeficitDem * tarAutoDeficitDem
        If dblVlrDeficitDem <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020015"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302020015") & " ( " & dblQtDeficitDem & " x " & tarAutoDeficitDem & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = CStr(dblQtDeficitDem)
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrDeficitDem, "Standard")
            ''''grid_fatura.Col = 4
            ''''grid_fatura.Text = "( " & dblQtDeficitDem & " x " & tarAutoDeficitDem & " )"
            dblBaseICMS = dblBaseICMS + dblVlrDeficitDem + Calc_ICMS(dblVlrDeficitDem, uf, dblAliqICMS, 0)
            dblVlrTotal = dblVlrTotal + dblVlrDeficitDem
            dblVlrPis = Aplica_Pis(dblQtDeficitDem, dblAliqICMS, tarAutoDeficitDem, 2) + dblVlrPis
            dblVlrCofins = Aplica_Cofins(dblQtDeficitDem, dblAliqICMS, tarAutoDeficitDem, 2) + dblVlrCofins
        End If

        '-- Deficit Demanda Horario Incentivado
        dblQtDeficitDemHI = Val(Replace(Txt_Auto_Deficit_Dem_HI.Text, ",", "."))
        If dblConstanteDemanda > 0 Then
            dblQtDeficitDemHI = dblQtDeficitDemHI * dblConstanteDemanda
        End If

        dblVlrDeficitDemHI = dblQtDeficitDemHI * tarAutoDeficitDemHI
        If dblVlrDeficitDemHI <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020015"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302020015") & " ( " & dblQtDeficitDemHI & " x " & tarAutoDeficitDemHI & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = CStr(dblQtDeficitDemHI)
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrDeficitDemHI, "Standard")
            ''''grid_fatura.Col = 4
            ''''grid_fatura.Text = "( " & dblQtDeficitDemHI & " x " & tarAutoDeficitDemHI & " )"
            dblBaseICMS = dblBaseICMS + dblVlrDeficitDemHI + Calc_ICMS(dblVlrDeficitDemHI, uf, dblAliqICMS, 0)
            dblVlrTotal = dblVlrTotal + dblVlrDeficitDemHI
            dblVlrPis = Aplica_Pis(dblQtDeficitDemHI, dblAliqICMS, tarAutoDeficitDemHI, 2) + dblVlrPis
            dblVlrCofins = Aplica_Cofins(dblQtDeficitDemHI, dblAliqICMS, tarAutoDeficitDemHI, 2) + dblVlrCofins
        End If

        '-- Iluminação

        'dblIlum = Calc_ILUM(Id_Cidade, dblClasse, dblQtConsumo)
        If dblIlum <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020015"
            ''' ''grid_fatura.Col = 1
            ''' ''grid_fatura.Text = cstr("0302020015") & " ( " & dblQtDeficitDemHI & " x " & tarAutoDeficitDemHI & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = CStr(dblIlum)
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblIlum, "Standard")
        End If

        '-- Pis
        If dblVlrPis <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020029"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302020029") & " ( " & dblBaseICMS & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = Format(dblBaseICMS, "Standard")
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrPis, "Standard")
            ''Item_Fatura = Trim(Item_Fatura & "0302020033?" & Replace(CStr(dblBaseICMS), ",", ".") & ";") ' Base de Pis
            dblVlrTotal = dblVlrTotal + dblVlrPis
        End If

        '-- Cofins
        If dblVlrCofins <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302020030"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302020030") & " ( " & dblBaseICMS & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = Format(dblBaseICMS, "Standard")
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrCofins, "Standard")
            Item_Fatura = Trim(Item_Fatura & "0302020034?" & Replace(CStr(dblBaseICMS), ",", ".") & ";") ' Base de Cofins
            dblBaseICMS = dblBaseICMS + dblVlrPis
            dblBaseICMS = dblBaseICMS + dblVlrCofins
            dblVlrTotal = dblVlrTotal + dblVlrCofins

        End If

        '-- ICMS Pis/Cofins
        dblVlrIcmsPisCofins = Calc_ICMS(dblVlrPis + dblVlrCofins, uf, dblAliqICMS, 0)
        If dblVlrIcmsPisCofins <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302030012"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302030012") & " ( " & dblVlrPis + dblVlrCofins & " )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = Format(dblVlrPis + dblVlrCofins, "Standard")
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblVlrIcmsPisCofins, "Standard")
            dblBaseICMS = dblBaseICMS + dblVlrIcmsPisCofins
        End If

        '-- ICMS
        dblIcms = dblBaseICMS * (dblAliqICMS / 100)
        If dblIcms <> 0 Then
            intRowGrid = 1 + intRowGrid
            ''''grid_fatura.Rows = intRowGrid + 1
            ''''grid_fatura.Row = intRowGrid
            ''''grid_fatura.Col = 0
            ''''grid_fatura.Text = "0302030009"
            ''''grid_fatura.Col = 1
            ''''grid_fatura.Text = CStr("0302030009") & " ( " & dblBaseICMS & " x " & Format(dblAliqICMS, "Standard") & "% )"
            ''''grid_fatura.Col = 2
            ''''grid_fatura.Text = Format(dblBaseICMS, "Standard")
            ''''grid_fatura.Col = 3
            ''''grid_fatura.Text = Format(dblIcms, "Standard")
            ''''grid_fatura.Col = 4
            ''''grid_fatura.Text = "( " & dblBaseICMS & " x " & Format(dblAliqICMS, "Standard") & "% )"
            dblVlrTotal = dblVlrTotal + dblIcms
        End If

        lblTotal.Text = Format(dblVlrTotal, "Standard")
        lblTotalLiq.Text = lblTotal.Text
        System.Windows.Forms.Application.DoEvents()

    End Sub

    Private Sub Calc_HoroSazonal()
        'kWh   = Consumo
        'kW    = Demanda
        'kVarh = Reativo

        '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 lstrUf As String
        Dim lstrMesRef As String

        Dim llngCodigoCidade As Integer
        Dim lstrCidade As String

        Dim ldblDemandaContratadaPonta As Double
        Dim ldblDemandaContratadaForaPonta 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 Constante_Reservado As Double
        Dim ldblPerdas As Double


        Dim strMsg As String
        Dim lstrRetencoes As String
        Dim strMesRefMulta As String
        Dim TpConsumo As String
        Dim TpFaixaC As String
        Dim sql As String

        Dim casas As Short
        Dim lblnCobrarReativo As Boolean
        Dim leitura_reativo As Short

        Dim dias As Short
        Dim row_grid As Short

        Dim dtDataRefMulta As Date
        Dim dtDataFat As Date

        Dim aux1 As Double
        Dim aux2 As Double
        Dim auxdemanda As Double
        Dim auxDemandaReativa As Double
        Dim consumo As Double
        Dim tarAuxCons_Reservado As Double

        'faturado
        Dim consumo_p As Double
        Dim vlrConsumo_P As Double
        Dim consumo_fp As Double
        Dim vlrConsumo_FP As Double
        'lido e contrato
        Dim consumolido_p As Double
        Dim consumolido_fp As Double
        Dim consumocontr_p As Double
        Dim consumocontr_fp As Double
        'devolvido e ultrapassado
        Dim consumodevol_p As Double
        Dim vlrConsumodevol_P As Double
        Dim consumodevol_fp As Double
        Dim vlrConsumodevol_FP As Double
        Dim vlrConsumoDevolPT As Double
        Dim vlrConsumoDevolFPT As Double
        Dim consumoultrap_p As Double
        Dim vlrConsumoultrap_P As Double
        Dim consumoultrap_fp As Double
        Dim vlrConsumoultrap_FP As Double
        Dim vlrConsumoUltrapPT As Double
        Dim vlrConsumoUltrapFPT As Double

        Dim ldblMaeMaior As Double
        Dim ldblMaeMenor As Double

        Dim vlrTotal As Double
        Dim vlrIsentoIcms As Double
        Dim vlrLiqui As Double
        Dim aliqICMS As Double
        Dim vlrPis As Double
        Dim vlrIcmsPisCofins As Double
        Dim vlrCofins As Double
        Dim basePisCofins As Double
        Dim vlrEncargo As Double
        Dim vlrICMSEce As Double
        Dim Demanda_Faturada_P As Double
        Dim vlrDemanda_P As Double
        Dim Demanda_Lida_P As Double
        Dim Demanda_Faturada_FP As Double
        Dim vlrDemanda_FP As Double
        Dim Demanda_Lida_FP As Double
        Dim Dem_Ultrapassagem_FP As Double
        Dim vlrDem_Ultrapassagem_FP As Double
        Dim Dem_Ultrapassagem_P As Double
        Dim vlrDem_Ultrapassagem_P As Double


        Dim classe 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 vlrKvarh_Consumo_fp As Double
        Dim vlrReservado As Double
        Dim Reservado As Double
        Dim vlrKvarh_Demanda_p As Double
        Dim BaseDemanda_Reativa As Double
        Dim leitDemanda_aux As Double
        Dim Base_Demanda_Reativa_p As Double
        Dim Base_Demanda_Reativa_fp As Double
        Dim Perc_Desconto_Reservado As Double
        Dim leitura_maxima As Double
        Dim Ilum As Double
        Dim strClasseIlum As String
        Dim vlr_ajuste_demanda_p As Double
        Dim vlr_ajuste_demanda_fp As Double
        Dim aux As Double
        Dim consumoReativoCapacitivo As Double
        Dim vlrConsumoReativoCapacitivo As Double
        Dim fator_potencia As Double
        Dim VlrFERfp As Double
        Dim VlrFERp As Double
        Dim vlrqh As Double
        Dim retencao As Double
        Dim base_retencao As Double
        Dim vlr_retencao As Double
        Dim coefTribIcms As Double
        Dim coefTribSIcms As Double
        Dim vlrConsumoPT As Double
        Dim vlrConsumoFPT 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 consIsento As Double
        Dim consTrib As Double
        Dim vlrConsIsento As Double
        Dim vlrConsTrib As Double
        Dim FatorAjuste As Double
        Dim leitAtual As Double
        Dim vlrReservadoT As Double
        Dim ldblDemaAuxP As Double
        Dim ldblDemaAuxFP As Double

        Dim lstrPercDemU As String
        Dim ldblPercDemUP As Double
        Dim ldblPercDemUFP As Double

        'Controle de casa decimais do kwh, kw, kvarh
        Dim lintDecimalKwh As Short
        Dim lintDecimalKw As Short
        Dim lintDecimalKVarh As Short

        'RecordSet dos dados da UNIDA
        Dim lstrSql As String
        ''Dim lrstConsulta As ADODB.Recordset
        ''Dim lrstMultaJuros As ADODB.Recordset
        ''Dim lrstAux As ADODB.Recordset
        ''lrstConsulta = New ADODB.Recordset
        ''lrstMultaJuros = New ADODB.Recordset
        ''lrstAux = New ADODB.Recordset


        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        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
            Call SetConfig("GRUPOA_PERCENTUAL_KW_ULTRA_P", "String", CStr(ldblPercDemUP), True, "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
            Call SetConfig("GRUPOA_PERCENTUAL_KW_ULTRA_P", "STRING", CStr(ldblPercDemUP))
        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
            Call SetConfig("GRUPOA_PERCENTUAL_KW_ULTRA_FP", "String", CStr(ldblPercDemUFP), True, "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
            Call SetConfig("GRUPOA_PERCENTUAL_KW_ULTRA_FP", "String", CStr(ldblPercDemUFP))
        Else
            ldblPercDemUFP = CDbl(lstrPercDemU)
        End If

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

        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"

        casas = 9
        Item_Fatura = ""

        lblnCobrarReativo = MsgBox("Deseja cobrar consumo e demanda reativos?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes

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

        objAtualizaBancoDados.QUERY_NAME = sql
        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"))
                InscEst = IIf(IsDBNull(row("insc")), "", row("insc"))
                ldblPerdas = IIf(IsDBNull(row("final")), 0, row("final"))
                lstrCidade = Trim(IIf(IsDBNull(row("cidade")), "", row("cidade")))
                lstrUf = Trim(IIf(IsDBNull(row("uf")), "", row("uf")))
                strClasseIlum = Format(Trim(IIf(IsDBNull(row("clas")), "0", row("clas"))), "0000")
                classe = Val(strClasseIlum)
                ldblDemandaContratadaPonta = IIf(IsDBNull(row("dem_contr_ponta")), 0, row("dem_contr_ponta"))
                ldblDemandaContratadaForaPonta = IIf(IsDBNull(row("dem_contr_fp")), 0, row("dem_contr_fp"))

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

                leitura_maxima = IIf(IsDBNull(row("maior")), 0, row("maior"))
                lblnFlagSazonal = IIf(IsDBNull(row("flg_sazonal")), "N", row("flg_sazonal")) = "S"
                dDataContrato = 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"))


                'Tenho que arrumar esta retencao para pegar da config e tirar fora a marreta la em baixo no calculo
                retencao = CDbl(GetConfig("PERCENTUAL_RETENCAO_CONSUMO"))
            Next
        End If

        '*******************************************
        '* Busca o código da cidade de acordo      *
        '* com o nome da cidade que esta nos       *
        '* dados da unidade consumidora.           *
        '*******************************************
        lstrSql = "SELECT * " & "  FROM munic " & " WHERE nome LIKE ""%" & lstrCidade & "%"" "

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

        If dt.Rows.Count <> 0 Then
            For Each row As DataRow In dt.Rows
                llngCodigoCidade = IIf(IsDBNull(row("codnum")), 0, row("codnum"))
            Next
        Else
            llngCodigoCidade = 0
        End If

        '******************************************

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

        tarAuxCons_Reservado = tarConsumo_fp

        'leituras anteriores e atuais
        Item_Fatura = Trim(Item_Fatura & "0302040007?" & Replace(CStr(ant_consumo_p), ",", ".") & ";") 'consumo ponta anterior
        Item_Fatura = Trim(Item_Fatura & "0302040008?" & Replace(txtConsumo_p.Text, ",", ".") & ";") 'consumo ponta atual
        Item_Fatura = Trim(Item_Fatura & "0302040011?" & Replace(CStr(ant_demanda_p), ",", ".") & ";") 'demanda ponta anterior
        Item_Fatura = Trim(Item_Fatura & "0302040012?" & Replace(txtDemanda_p.Text, ",", ".") & ";") 'demanda ponta atual
        Item_Fatura = Trim(Item_Fatura & "0302040015?" & Replace(CStr(ant_kvarh), ",", ".") & ";") 'reativo ponta anterior
        Item_Fatura = Trim(Item_Fatura & "0302040016?" & Replace(txtKvarh_P.Text, ",", ".") & ";") 'reativo ponta atual

        Item_Fatura = Trim(Item_Fatura & "0302040009?" & Replace(CStr(ant_consumo_fp), ",", ".") & ";") 'consumo f ponta anterior
        Item_Fatura = Trim(Item_Fatura & "0302040010?" & Replace(txtConsumo_FP.Text, ",", ".") & ";") 'consumo f ponta atual
        Item_Fatura = Trim(Item_Fatura & "0302040013?" & Replace(CStr(ant_demanda_fp), ",", ".") & ";") 'demanda f ponta anterior
        Item_Fatura = Trim(Item_Fatura & "0302040014?" & Replace(txtDemanda_FP.Text, ",", ".") & ";") 'demanda f ponta atual
        Item_Fatura = Trim(Item_Fatura & "0302040017?" & Replace(CStr(ant_kvarh_fp), ",", ".") & ";") 'reativo f ponta anterior
        Item_Fatura = Trim(Item_Fatura & "0302040018?" & Replace(txtKvarh_FP.Text, ",", ".") & ";") 'reativo f ponta atual
        Item_Fatura = Trim(Item_Fatura & "0302040019?" & Replace(CStr(ant_consumo_reservado), ",", ".") & ";") 'reservado anterior
        Item_Fatura = Trim(Item_Fatura & "0302040020?" & Replace(txtReservado.Text, ",", ".") & ";") 'reservado atual

        '-- Percentual de desconto aplicado a tarifa reservado
        '-- de acordo com a região
        '-- Portaria 105/92 DNAEE
        If lstrUf = "GO" Then
            '    Perc_Desconto_Reservado = 80
        ElseIf lstrUf = "RS" Then
            Perc_Desconto_Reservado = 70
        End If

        aliqICMS = Busca_Aliquota_ICMS(lstrUf, 0, Str(classe))

        classe = Val(Mid(Trim(Str(classe)), 1, 1))

        If classe = 5 And lstrUf <> "GO" And lstrUf <> "RS" Then
            '-- Aplica desconto de 10% para tarifas rurais
            tarConsumo_p = Arredondar(tarConsumo_p * 0.9, 5)
            tarConsumo_fp = Arredondar(tarConsumo_fp * 0.9, 5)
            tarDemanda_p = Arredondar(tarDemanda_p * 0.9, 5)
            tarDemanda_fp = Arredondar(tarDemanda_fp * 0.9, 5)
            tarDemUltra_p = Arredondar(tarDemUltra_p * 0.9, 5)
            tarDemUltra_fp = Arredondar(tarDemUltra_fp * 0.9, 5)
            '  ElseIf classe = 7 Then
            '    '-- Aplica desconto de 15% para tarifas servico publico
            '    tarConsumo_p = Arredondar(tarConsumo_p * 0.85, 5)
            '    tarConsumo_fp = Arredondar(tarConsumo_fp * 0.85, 5)
            '    tarDemanda_p = Arredondar(tarDemanda_p * 0.85, 5)
            '    tarDemanda_fp = Arredondar(tarDemanda_fp * 0.85, 5)
            '    tarDemUltra_p = Arredondar(tarDemUltra_p * 0.85, 5)
            '    tarDemUltra_fp = Arredondar(tarDemUltra_fp * 0.85, 5)
        End If

        'Ricardo colocou essas tarifa de consumo Pis Cos para o calculo do CIP que estava faltado
        tarConsumo_pPISCOF = Truncate(tarConsumo_p / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)
        tarDemanda_pPISCOF = Truncate(tarDemanda_p / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)
        tarConsumo_fpPISCOF = Truncate(tarConsumo_fp / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)
        tarDemanda_fpPISCOF = Truncate(tarDemanda_fp / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)

        If classe = 5 And lstrUf = "RS" Then isento_demanda = "S"

        coefTribIcms = Truncate(1 - (((AliqPIS / 100) + (AliqCofins / 100)) / (1 - (aliqICMS / 100))), 11)
        coefTribSIcms = 1 - ((AliqPIS / 100) + (AliqCofins / 100))

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

        '  Item_Fatura = ""

        ''''grid_fatura.Redraw = False

        '***********************************************************
        'alteracao por ademir em 19/06/07
        'peguei as linhas de código que manipulam as leituras de
        'consumo e juntei elas todas antes de começar os cálculos
        'pra poder pegar o consumo todo no começo da rotina.
        'isso é importante, pois preciso saber quanto o consumidor
        'consumiu em kwh pra poder fazer o cálculo do icms do
        'consumidor rural no RS.
        '***********************************************************

        'consumo na ponta ******************************************
        leitAtual = CDbl(txtConsumo_p.Text)
        If leitAtual > 0 Then
            consumo_p = leitAtual - ant_consumo_p
            If consumo_p < 0 Then
                Select Case Len(Trim(Str(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
            consumo_p = (leitAtual - ant_consumo_p)
        End If

        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))
        End If

        consumo_p = Arredondar(consumo_p, lintDecimalKwh)
        consumolido_p = consumo_p
        'Busca contrato de consumo na ponta
        consumocontr_p = BuscaContrato(Id_Unid, Id_Consumidor, Me.txtTA.Text, CDate(Me.txtDt_Faturamento.Text), "0302010047")
        If consumocontr_p >= 0 Then
            If consumolido_p > consumocontr_p Then
                If consumolido_p <= (consumocontr_p * 1.1) Then
                    consumo_p = consumolido_p
                    consumoultrap_p = 0
                    consumodevol_p = 0
                Else
                    consumodevol_p = 0
                    consumoultrap_p = Arredondar(consumolido_p - consumocontr_p, lintDecimalKwh)
                    'consumo_p = consumocontr_p
                    consumo_p = consumolido_p
                End If
            ElseIf consumolido_p < consumocontr_p Then
                If consumolido_p >= (consumocontr_p - (consumocontr_p * 0.1)) Then
                    consumo_p = consumolido_p
                    consumoultrap_p = 0
                    consumodevol_p = 0
                Else
                    consumoultrap_p = 0
                    consumodevol_p = Arredondar(consumocontr_p - consumolido_p, lintDecimalKwh)
                    consumo_p = consumocontr_p
                End If
            Else
                consumo_p = consumolido_p
                consumoultrap_p = 0
                consumodevol_p = 0
            End If
        End If

        'consumo fora de ponta *************************************
        If Val(Replace(txtConsumo_FP.Text, ",", ".")) > 0 Then
            leitAtual = CDbl(txtConsumo_FP.Text)
            consumo_fp = leitAtual - ant_consumo_fp
            If consumo_fp < 0 Then
                Select Case Len(Trim(Str(ant_consumo_fp)))
                    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
                    Case 9
                        leitAtual = 999999999 + leitAtual + 1
                End Select
            End If
            'Refazer os calculo de consumo para apurar consumo real
            consumo_fp = (leitAtual - ant_consumo_fp)
        End If
        'Consumo_FP = Val(txtConsumo_FP.Text) - 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))
        End If
        consumo_fp = Arredondar(consumo_fp, lintDecimalKwh)
        consumolido_fp = consumo_fp
        'Busca contrato de consumo fora da ponta
        consumocontr_fp = BuscaContrato(Id_Unid, Id_Consumidor, Me.txtTA.Text, CDate(Me.txtDt_Faturamento.Text), "0302010048")
        If consumocontr_fp >= 0 Then
            If consumolido_fp > consumocontr_fp Then
                If consumolido_fp <= (consumocontr_fp * 1.1) Then
                    consumo_fp = consumolido_fp
                    consumoultrap_fp = 0
                    consumodevol_fp = 0
                Else
                    consumodevol_fp = 0
                    consumoultrap_fp = Arredondar(consumolido_fp - consumocontr_fp, lintDecimalKwh)
                    'consumo_fp = consumocontr_fp
                    consumo_fp = consumolido_fp
                End If
            ElseIf consumolido_fp < consumocontr_fp Then
                If consumolido_fp >= (consumocontr_fp - (consumocontr_fp * 0.1)) Then
                    consumo_fp = consumolido_fp
                    consumoultrap_fp = 0
                    consumodevol_fp = 0
                Else
                    consumoultrap_fp = 0
                    consumodevol_fp = Arredondar(consumocontr_fp - consumolido_fp, lintDecimalKwh)
                    consumo_fp = consumocontr_fp
                End If
            Else
                consumo_fp = consumolido_fp
                consumoultrap_fp = 0
                consumodevol_fp = 0
            End If
        End If
        'consumo reservado/incentivado *****************************
        If Val(Replace(txtReservado.Text, ",", ".")) > 0 Then
            '-- Verifica se tem faturas em aberto
            sql = "SELECT * FROM nf WHERE CONS_ID=" & Id_Consumidor & " AND DATAPAG IS NULL"

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

            If dt.Rows.Count <> 0 Then
                '-- tarConsumo_fp já com o desconto do Rural
                tarCons_Reservado = tarConsumo_fp
            Else
                '-- tarAuxCons_Reservado tem a tarifa cheia do consumo fora de ponta
                If classe = 5 And lstrUf = "RS" Then
                    tarCons_Reservado = tarConsumo_fp
                Else
                    tarCons_Reservado = tarAuxCons_Reservado * ((100 - Perc_Desconto_Reservado) / 100)
                End If
            End If

            Reservado = Val(Replace(txtReservado.Text, ",", ".")) - ant_consumo_reservado

            If Constante_Reservado > 0 Then
                Reservado = Reservado * Constante_Reservado
            End If

            If ldblPerdas > 0 Then
                Reservado = Reservado + (Reservado * (ldblPerdas / 100))
            End If
        End If
        '***********************************************************
        consTotal = consumo_p + consumo_fp + Reservado

        If Val(Replace(txtConsumo_p.Text, ",", ".")) > 0 Then
            vlrConsumo_P = Arredondar(consumo_p * tarConsumo_p, 2)
            If vlrConsumo_P <> 0 Then
                row_grid = 1 + row_grid
                ''''grid_fatura.Row = row_grid
                ''''grid_fatura.Col = 0
                ''''grid_fatura.Text = "0302020010"
                ''''grid_fatura.Col = 1
                ''''grid_fatura.Text = Trim(CStr("0302020010")) & " ( " & consumo_p & " x " & tarConsumo_p & " )"
                ''''grid_fatura.Col = 2
                ''''grid_fatura.Text = CStr(consumo_p)
                ''''grid_fatura.Col = 3
                ''''grid_fatura.Text = Format(vlrConsumo_P, "Standard")
                ''''grid_fatura.Col = 4
                ''''grid_fatura.Text = "( " & consumo_p & " x " & tarConsumo_p & " )"

                If classe = 5 And lstrUf = "GO" Then
                    vlrConsumoPT = Arredondar((vlrConsumo_P * 0.9) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(consumo_p / consTotal, 2) * 100
                    consIsento = consumo_p - consTrib
                    vlrConsTrib = Arredondar(((consTrib * tarConsumo_p) / coefTribIcms) * 0.9, 2)
                    vlrConsIsento = Arredondar(((consIsento * tarConsumo_p) / coefTribSIcms) * 0.9, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + vlrConsIsento
                ElseIf classe = 7 Then
                    vlrConsumoPT = Arredondar((vlrConsumo_P * 0.85) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    'vlrConsumoPT = Arredondar(Arredondar(consumolido_p * tarConsumo_p, 2) / coefTribIcms, 2)
                    vlrConsumoPT = Arredondar(vlrConsumo_P / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrConsumo_P, "Standard"))

                Item_Fatura = Trim(Item_Fatura & "0302010010?" & Replace(CStr(consumo_p), ",", ".") & "$;") 'Consumo Faturado Ponta
                Item_Fatura = Trim(Item_Fatura & "0302010045?" & Replace(CStr(consumolido_p), ",", ".") & "$;") 'Consumo Lido Ponta
                Item_Fatura = Trim(Item_Fatura & "0302010047?" & Replace(CStr(consumocontr_p), ",", ".") & "$;") 'Consumo contratado Ponta
            Else
                Item_Fatura = Trim(Item_Fatura & "0302010045?" & Replace(CStr(consumolido_p), ",", ".") & "$;") 'Consumo Lido Ponta
                Item_Fatura = Trim(Item_Fatura & "0302010047?" & Replace(CStr(consumocontr_p), ",", ".") & "$;") 'Consumo contratado Ponta
            End If
        End If
        'manda o novo valor e busca o valor do mes anterior para ser cobrado este mês
        consumodevol_p = ControleContratoKwh(Id_Unid, Id_Consumidor, Me.txtTA.Text, CDate(Me.txtDt_Faturamento.Text), "0302010041", consumodevol_p, lstrMesRef)
        consumodevol_fp = ControleContratoKwh(Id_Unid, Id_Consumidor, Me.txtTA.Text, CDate(Me.txtDt_Faturamento.Text), "0302010042", consumodevol_fp, lstrMesRef)
        consumoultrap_p = ControleContratoKwh(Id_Unid, Id_Consumidor, Me.txtTA.Text, CDate(Me.txtDt_Faturamento.Text), "0302010043", consumoultrap_p, lstrMesRef)
        consumoultrap_fp = ControleContratoKwh(Id_Unid, Id_Consumidor, Me.txtTA.Text, CDate(Me.txtDt_Faturamento.Text), "0302010044", consumoultrap_fp, lstrMesRef)
        Call BuscaPrecoMae(CDate(Me.txtDt_Faturamento.Text), ldblMaeMaior, ldblMaeMenor)
        ldblMaeMaior = (ldblMaeMaior / 1000)
        ldblMaeMenor = (ldblMaeMenor / 1000)
        'Consumo Devolvido na ponta
        consTotal = consumodevol_p + consumodevol_fp
        If consumodevol_p > 0 Then
            vlrConsumodevol_P = Arredondar(consumodevol_p * ldblMaeMenor, 2) * -1
            If vlrConsumodevol_P <> 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 = "0302020041"
                ''''grid_fatura.Col = 1
                ''''grid_fatura.Text = Trim(CStr("0302020041")) & " ( " & consumodevol_p & " x " & ldblMaeMenor & " ) ( " & lstrMesRef & " )"
                ''''grid_fatura.Col = 2
                ''''grid_fatura.Text = CStr(consumodevol_p)
                ''''grid_fatura.Col = 3
                ''''grid_fatura.Text = Format(vlrConsumodevol_P, "Standard")
                ''''grid_fatura.Col = 4
                ''''grid_fatura.Text = "( " & consumodevol_p & " x " & ldblMaeMenor & " ) ( " & lstrMesRef & " ) "
                If classe = 5 And lstrUf = "GO" Then
                    vlrConsumoDevolPT = Arredondar((vlrConsumodevol_P * 0.9) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoDevolPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(consumodevol_p / consTotal, 2) * 100
                    consIsento = consumodevol_p - consTrib
                    vlrConsTrib = Arredondar(((consTrib * ldblMaeMenor) / coefTribIcms) * 0.9, 2)
                    vlrConsIsento = Arredondar(((consIsento * ldblMaeMenor) / coefTribSIcms) * 0.9, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + vlrConsIsento
                ElseIf classe = 7 Then
                    vlrConsumoDevolPT = Arredondar((vlrConsumodevol_P * 0.85) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoDevolPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    vlrConsumoDevolPT = Arredondar(vlrConsumodevol_P / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoDevolPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(Format(vlrConsumodevol_P, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010041?" & Replace(CStr(consumodevol_p), ",", ".") & "$;") 'Consumo Devolvido Ponta
            End If
        End If

        'Consumo ultrap na ponta
        consTotal = consumoultrap_p + consumoultrap_fp
        If consumoultrap_p > 0 Then
            vlrConsumoultrap_P = Arredondar(consumoultrap_p * ldblMaeMaior, 2)
            If vlrConsumoultrap_P <> 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 = "0302020043"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = Trim(CStr("0302020043")) & " ( " & consumoultrap_p & " x " & ldblMaeMaior & " ) ( " & lstrMesRef & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(consumoultrap_p)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrConsumoultrap_P, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & consumoultrap_p & " x " & ldblMaeMaior & " ) ( " & lstrMesRef & " )"
                If classe = 5 And lstrUf = "GO" Then
                    vlrConsumoUltrapPT = Arredondar((vlrConsumoultrap_P * 0.9) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoUltrapPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(consumoultrap_p / consTotal, 2) * 100
                    consIsento = consumoultrap_p - consTrib
                    vlrConsTrib = Arredondar(((consTrib * ldblMaeMaior) / coefTribIcms) * 0.9, 2)
                    vlrConsIsento = Arredondar(((consIsento * ldblMaeMaior) / coefTribSIcms) * 0.9, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + vlrConsIsento
                ElseIf classe = 7 Then
                    vlrConsumoUltrapPT = Arredondar((vlrConsumoultrap_P * 0.85) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoUltrapPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    vlrConsumoUltrapPT = Arredondar(vlrConsumoultrap_P / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoUltrapPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(Format(vlrConsumoultrap_P, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010043?" & Replace(CStr(consumoultrap_p), ",", ".") & "$;") 'Consumo Ultrapassagem Ponta
            End If
        End If

        '-- Consumo Fora de Ponta
        consTotal = consumo_p + consumo_fp + Reservado
        If Val(Replace(txtConsumo_FP.Text, ",", ".")) > 0 Then
            vlrConsumo_FP = Arredondar(consumo_fp * tarConsumo_fp, 2)
            If vlrConsumo_FP <> 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 = "0302020011"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = Trim(CStr("0302020011")) & " ( " & consumo_fp & " x " & tarConsumo_fp & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(consumo_fp)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrConsumo_FP, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & consumo_fp & " x " & tarConsumo_fp & " )"
                If classe = 5 And lstrUf = "GO" Then
                    vlrConsumoFPT = Arredondar((vlrConsumo_FP * 0.9) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(consumo_fp / consTotal, 2) * 100
                    consIsento = consumo_fp - consTrib
                    vlrConsTrib = Arredondar(((consTrib * tarConsumo_fp) / coefTribIcms) * 0.9, 2)
                    vlrConsIsento = Arredondar(((consIsento * tarConsumo_fp) / coefTribSIcms) * 0.9, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + vlrConsIsento
                ElseIf classe = 7 Then
                    vlrConsumoFPT = Arredondar((vlrConsumo_FP * 0.85) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    'vlrConsumoFPT = Arredondar(Arredondar(consumolido_fp * tarConsumo_fp, 2) / coefTribIcms, 2)
                    vlrConsumoFPT = Arredondar(vlrConsumo_FP / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(Format(vlrConsumo_FP, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010011?" & Replace(CStr(consumo_fp), ",", ".") & "$;") 'Consumo Faturado Fora de Ponta
                Item_Fatura = Trim(Item_Fatura & "0302010046?" & Replace(CStr(consumolido_fp), ",", ".") & "$;") 'Consumo Lido Fora de Ponta
                Item_Fatura = Trim(Item_Fatura & "0302010048?" & Replace(CStr(consumocontr_fp), ",", ".") & "$;") 'Consumo contratado Fora de Ponta
            End If
        End If

        'Consumo Devolvido fora da ponta
        consTotal = consumodevol_p + consumodevol_fp
        If consumodevol_fp > 0 Then
            vlrConsumodevol_FP = Arredondar(consumodevol_fp * ldblMaeMenor, 2) * -1
            If vlrConsumodevol_FP <> 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 = "0302020042"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = Trim(CStr("0302020042")) & " ( " & consumodevol_fp & " x " & ldblMaeMenor & " ) ( " & lstrMesRef & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(consumodevol_fp)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrConsumodevol_FP, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & consumodevol_fp & " x " & ldblMaeMenor & " ) ( " & lstrMesRef & " )"
                If classe = 5 And lstrUf = "GO" Then
                    vlrConsumoDevolFPT = Arredondar((vlrConsumodevol_FP * 0.9) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoDevolFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(consumodevol_fp / consTotal, 2) * 100
                    consIsento = consumodevol_fp - consTrib
                    vlrConsTrib = Arredondar(((consTrib * ldblMaeMenor) / coefTribIcms) * 0.9, 2)
                    vlrConsIsento = Arredondar(((consIsento * ldblMaeMenor) / coefTribSIcms) * 0.9, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + vlrConsIsento
                ElseIf classe = 7 Then
                    vlrConsumoDevolFPT = Arredondar((vlrConsumodevol_FP * 0.85) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoDevolFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    vlrConsumoDevolFPT = Arredondar(vlrConsumodevol_FP / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoDevolFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(Format(vlrConsumodevol_FP, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010042?" & Replace(CStr(consumodevol_fp), ",", ".") & "$;") 'Consumo Devolvido fora Ponta
            End If
        End If

        'Consumo ultrap na fora ponta
        consTotal = consumoultrap_p + consumoultrap_fp
        If consumoultrap_fp > 0 Then
            vlrConsumoultrap_FP = Arredondar(consumoultrap_fp * ldblMaeMaior, 2)
            If vlrConsumoultrap_FP <> 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 = "0302020044"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = Trim(CStr("0302020044")) & " ( " & consumoultrap_fp & " x " & ldblMaeMaior & " ) ( " & lstrMesRef & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(consumoultrap_fp)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrConsumoultrap_FP, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & consumoultrap_fp & " x " & ldblMaeMaior & " ) ( " & lstrMesRef & " )"
                If classe = 5 And lstrUf = "GO" Then
                    vlrConsumoUltrapFPT = Arredondar((vlrConsumoultrap_FP * 0.9) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoUltrapFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(consumoultrap_fp / consTotal, 2) * 100
                    consIsento = consumoultrap_fp - consTrib
                    vlrConsTrib = Arredondar(((consTrib * ldblMaeMaior) / coefTribIcms) * 0.9, 2)
                    vlrConsIsento = Arredondar(((consIsento * ldblMaeMaior) / coefTribSIcms) * 0.9, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + vlrConsIsento
                ElseIf classe = 7 Then
                    vlrConsumoUltrapFPT = Arredondar((vlrConsumoultrap_FP * 0.85) / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoUltrapFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    vlrConsumoUltrapFPT = Arredondar(vlrConsumoultrap_FP / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrConsumoUltrapFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If
                vlrTotal = vlrTotal + CDbl(Format(vlrConsumoultrap_FP, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010044?" & Replace(CStr(consumoultrap_fp), ",", ".") & "$;") 'Consumo Ultrapassagem fora Ponta
            End If
        End If

        '-- Azul ou Livre
        If tarifa = 2 Then
            '-- Demanda Ponta
            '    If ldblDemandaContratadaPonta > 0 Then 'Or Val(Replace(txtDemanda_p.Text, ",", ".")) > 0 Then
            Demanda_Lida_P = CDbl(txtDemanda_p.Text) ' - ant_demanda_p

            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

            Demanda_Lida_P = Truncate(Demanda_Lida_P, 0)
            If Not lblnFlagSazonal Then
                If ldblDemandaContratadaPonta > 0 Then
                    If Demanda_Lida_P > ldblDemandaContratadaPonta Then
                        ' -- Determina se existe demanda de ultrapassagem na ponta
                        If (Demanda_Lida_P <= (ldblDemandaContratadaPonta * ((ldblPercDemUP / 100) + 1))) Then
                            Demanda_Faturada_P = Demanda_Lida_P
                        Else
                            Dem_Ultrapassagem_P = Arredondar(Demanda_Lida_P - ldblDemandaContratadaPonta, lintDecimalKw)
                            If istrRes414_Art104 = "S" Then
                                Demanda_Faturada_P = Demanda_Lida_P
                            Else
                                Demanda_Faturada_P = ldblDemandaContratadaPonta
                            End If
                        End If
                    ElseIf Demanda_Lida_P < ldblDemandaContratadaPonta Then
                        If classe = 5 Then
                            If Demanda_Lida_P <= (ldblDemandaContratadaPonta * (ldblPercDemUP / 100)) Then
                                Demanda_Faturada_P = (ldblDemandaContratadaPonta * (ldblPercDemUP / 100))
                            Else
                                Demanda_Faturada_P = Demanda_Lida_P
                            End If
                        Else
                            Demanda_Faturada_P = ldblDemandaContratadaPonta
                        End If
                    Else
                        Demanda_Faturada_P = Demanda_Lida_P
                    End If
                Else
                    Dem_Ultrapassagem_P = 0
                    Demanda_Faturada_P = Demanda_Lida_P
                End If
            End If

            Base_Demanda_Reativa_p = Demanda_Lida_P * tarDemanda_p
            Demanda_Faturada_P = Arredondar(Demanda_Faturada_P, lintDecimalKw)
            vlrDemanda_P = Arredondar(Demanda_Faturada_P * tarDemanda_p, 2)

            If vlrDemanda_P > 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 = "0302020021"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302020021") & " ( " & Demanda_Faturada_P & " x " & tarDemanda_p & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Demanda_Faturada_P)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrDemanda_P, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & Demanda_Faturada_P & " x " & tarDemanda_p & " )"

                If isento_demanda = "N" Then
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemandaPT = (vlrDemanda_P * 0.9) / coefTribIcms
                    ElseIf classe = 7 Then
                        vlrDemandaPT = (vlrDemanda_P * 0.85) / coefTribIcms
                    Else
                        vlrDemandaPT = vlrDemanda_P / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(vlrDemandaPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemandaPT = (vlrDemanda_P * 0.9) / coefTribSIcms
                    ElseIf classe = 7 Then
                        vlrDemandaPT = (vlrDemanda_P * 0.85) / coefTribSIcms
                    Else
                        vlrDemandaPT = vlrDemanda_P / coefTribSIcms
                    End If

                    baseICMSisenta = baseICMSisenta + vlrDemandaPT
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrDemanda_P, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010021?" & Replace(CStr(Demanda_Faturada_P), ",", ".") & "$;") 'demanda Ponta
                Item_Fatura = Trim(Item_Fatura & "0302010019?" & Replace(CStr(Demanda_Lida_P), ",", ".") & "$;") 'Demanda Lida Fora Ponta

                If nAjuste_Demanda_P > 0 Then
                    vlr_ajuste_demanda_p = nAjuste_Demanda_P * tarDemanda_p
                    If vlr_ajuste_demanda_p > 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 = "0302020021" 'alterar o codigo
                        ''grid_fatura.Col = 1
                        ''grid_fatura.Text = CStr("0302020021") & " ( " & nAjuste_Demanda_P & " x " & tarDemanda_p & " )"
                        ''grid_fatura.Col = 2
                        ''grid_fatura.Text = CStr(nAjuste_Demanda_P)
                        ''grid_fatura.Col = 3
                        ''grid_fatura.Text = Format(vlr_ajuste_demanda_p, "Standard")
                        ''grid_fatura.Col = 4
                        ''grid_fatura.Text = "( " & nAjuste_Demanda_P & " x " & tarDemanda_p & " )"
                    End If
                End If
            End If

            '-- Demanda de Ultrapassagem na Ponta
            If Dem_Ultrapassagem_P > 0 Then
                vlrDem_Ultrapassagem_P = Arredondar(Dem_Ultrapassagem_P * tarDemUltra_p, 2)
                row_grid = 1 + row_grid
                ''grid_fatura.Rows = row_grid + 1
                ''grid_fatura.Row = row_grid
                ''grid_fatura.Col = 0
                ''grid_fatura.Text = "0302020022"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302020022") & " ( " & Dem_Ultrapassagem_P & " x " & tarDemUltra_p & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Dem_Ultrapassagem_P)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrDem_Ultrapassagem_P, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & Dem_Ultrapassagem_P & " x " & tarDemUltra_p & " )"

                If isento_demanda = "N" Then
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemUltraPT = (vlrDem_Ultrapassagem_P * 0.9) / coefTribIcms
                    ElseIf classe = 7 Then
                        vlrDemUltraPT = (vlrDem_Ultrapassagem_P * 0.85) / coefTribIcms
                    Else
                        vlrDemUltraPT = vlrDem_Ultrapassagem_P / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(vlrDemUltraPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemUltraPT = (vlrDem_Ultrapassagem_P * 0.9) / coefTribSIcms
                    ElseIf classe = 7 Then
                        vlrDemUltraPT = (vlrDem_Ultrapassagem_P * 0.85) / coefTribSIcms
                    Else
                        vlrDemUltraPT = vlrDem_Ultrapassagem_P / coefTribSIcms
                    End If

                    baseICMSisenta = baseICMSisenta + vlrDemUltraPT
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrDem_Ultrapassagem_P, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010022?" & Replace(CStr(Dem_Ultrapassagem_P), ",", ".") & "$;") 'demanda ultrapassagem ponta
            End If
        End If 'Fim Azul

        '-- Demanda Fora de Ponta
        Demanda_Lida_FP = CDbl(txtDemanda_FP.Text) '- ant_demanda_fp

        If Constante_Demanda_FP > 0 Then
            Demanda_Lida_FP = Demanda_Lida_FP * Constante_Demanda_FP
        End If

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

        Demanda_Lida_FP = Arredondar(Demanda_Lida_FP, lintDecimalKw)

        If ldblDemandaContratadaForaPonta > 0 Then
            If Demanda_Lida_FP > ldblDemandaContratadaForaPonta Then
                ' -- Determina se existe demanda de ultrapassagem na ponta
                If (Demanda_Lida_FP <= Arredondar(ldblDemandaContratadaForaPonta * ((ldblPercDemUFP / 100) + 1))) Then
                    Demanda_Faturada_FP = Demanda_Lida_FP
                Else
                    Dem_Ultrapassagem_FP = Arredondar(Demanda_Lida_FP - ldblDemandaContratadaForaPonta, lintDecimalKw)
                    If istrRes414_Art104 = "S" Then
                        Demanda_Faturada_FP = Demanda_Lida_FP
                    Else
                        Demanda_Faturada_FP = ldblDemandaContratadaForaPonta
                    End If
                End If
            ElseIf Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                If classe = 5 Then
                    If Demanda_Lida_FP <= (ldblDemandaContratadaForaPonta * (ldblPercDemUFP / 100)) Then
                        Demanda_Faturada_FP = (ldblDemandaContratadaForaPonta * (ldblPercDemUFP / 100))
                    Else
                        Demanda_Faturada_FP = Demanda_Lida_FP
                    End If
                Else
                    Demanda_Faturada_FP = ldblDemandaContratadaForaPonta
                End If
            Else
                Demanda_Faturada_FP = Demanda_Lida_FP
            End If
        Else
            Dem_Ultrapassagem_FP = 0
            Demanda_Faturada_FP = Demanda_Lida_FP
        End If
        Base_Demanda_Reativa_fp = Demanda_Lida_FP * tarDemanda_fp
        Demanda_Faturada_FP = Arredondar(Demanda_Faturada_FP, lintDecimalKw)
        vlrDemanda_FP = Arredondar(Demanda_Faturada_FP * tarDemanda_fp, 2)

        If vlrDemanda_FP > 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 = "0302020023"
            ''grid_fatura.Col = 1
            ''grid_fatura.Text = IIf(tarifa = 2, CStr("0302020023"), "DEMANDA") & " ( " & Demanda_Faturada_FP & " x " & tarDemanda_fp & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = CStr(Demanda_Faturada_FP)
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrDemanda_FP, "Standard")
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "( " & Demanda_Faturada_FP & " x " & tarDemanda_fp & " )"
            If isento_demanda = "N" Then
                If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                    vlrDemandaFPT = (vlrDemanda_FP * 0.9) / coefTribIcms
                ElseIf classe = 7 Then
                    'Faz calculo da tributacao em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemandaFPT = ((Arredondar(Demanda_Lida_FP * tarDemanda_fp, 2)) * 0.85) / coefTribIcms
                    Else
                        vlrDemandaFPT = (vlrDemanda_FP * 0.85) / coefTribIcms
                    End If
                Else
                    'Faz calculo da tributacao em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemandaFPT = vlrDemanda_FP / coefTribIcms
                        baseIcmsAux = Calc_ICMS(vlrDemandaFPT, lstrUf, aliqICMS, 5)
                        vlrDemandaFPT = (Arredondar(Demanda_Lida_FP * tarDemanda_fp, 2)) / coefTribIcms
                        baseIcmsAux = baseIcmsAux - Calc_ICMS(vlrDemandaFPT, lstrUf, aliqICMS, 5)
                        baseIcmsAux = Arredondar(baseIcmsAux, 2)
                        baseICMSisenta = baseICMSisenta + baseIcmsAux
                        Item_Fatura = Trim(Item_Fatura & "0302030020?" & Replace(CStr(baseIcmsAux), ",", ".") & ";")
                    Else
                        vlrDemandaFPT = vlrDemanda_FP / coefTribIcms
                    End If
                End If
                baseIcmsAux = Calc_ICMS(vlrDemandaFPT, lstrUf, aliqICMS, 5)
                BaseICMS = BaseICMS + baseIcmsAux
            Else
                If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                    vlrDemandaFPT = (vlrDemanda_FP * 0.9) / coefTribSIcms
                ElseIf classe = 7 Then
                    'Faz calculo da tributacao em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemandaFPT = ((Arredondar(Demanda_Lida_FP * tarDemanda_fp, 2)) * 0.85) / coefTribSIcms
                    Else
                        vlrDemandaFPT = (vlrDemanda_FP * 0.85) / coefTribSIcms
                    End If
                Else
                    'Faz calculo da tributacao em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemandaFPT = (Arredondar(Demanda_Lida_FP * tarDemanda_fp, 2)) / coefTribSIcms
                    Else
                        vlrDemandaFPT = vlrDemanda_FP / coefTribSIcms
                    End If
                End If
                baseICMSisenta = baseICMSisenta + vlrDemandaFPT
            End If
            vlrTotal = vlrTotal + CDbl(Format(vlrDemanda_FP, "Standard"))
            Item_Fatura = Trim(Item_Fatura & "0302010025?" & Replace(CStr(Demanda_Faturada_FP), ",", ".") & "$;") 'Demanda faturada Fora Ponta
            Item_Fatura = Trim(Item_Fatura & "0302010023?" & Replace(CStr(Demanda_Lida_FP), ",", ".") & "$;") 'Demanda Lida Fora Ponta

            If nAjuste_Demanda_FP > 0 Then
                vlr_ajuste_demanda_fp = nAjuste_Demanda_FP * tarDemanda_fp

                If vlr_ajuste_demanda_fp > 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 = "0302020021" 'alterar o codigo
                    ''grid_fatura.Col = 1
                    ''grid_fatura.Text = CStr("0302020021") & " ( " & nAjuste_Demanda_FP & " x " & tarDemanda_fp & " )"
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = CStr(nAjuste_Demanda_FP)
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(vlr_ajuste_demanda_fp, "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & nAjuste_Demanda_FP & " x " & tarDemanda_fp & " )"
                End If
            End If
        End If
        '-- Demanda de Ultrapassagem na Fora de Ponta
        If Dem_Ultrapassagem_FP > 0 Then
            vlrDem_Ultrapassagem_FP = Arredondar(Dem_Ultrapassagem_FP * tarDemUltra_fp, 2)
            row_grid = 1 + row_grid
            ''grid_fatura.Rows = row_grid + 1
            ''grid_fatura.Row = row_grid
            ''grid_fatura.Col = 0
            ''grid_fatura.Text = "0302020026"
            ''grid_fatura.Col = 1
            ''grid_fatura.Text = CStr("0302020026") & " ( " & Dem_Ultrapassagem_FP & " x " & tarDemUltra_fp & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = CStr(Dem_Ultrapassagem_FP)
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrDem_Ultrapassagem_FP, "Standard")
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "( " & Dem_Ultrapassagem_FP & " x " & tarDemUltra_fp & " )"

            If isento_demanda = "N" Then
                If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                    vlrDemUltraFPT = (vlrDem_Ultrapassagem_FP * 0.9) / coefTribIcms
                ElseIf classe = 7 Then
                    'Isento o valor da ultrap fp na base de icms,pois o icms é em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemUltraFPT = 0
                    Else
                        vlrDemUltraFPT = (vlrDem_Ultrapassagem_FP * 0.85) / coefTribIcms
                    End If
                Else
                    'Isento o valor da ultrap fp na base de icms,pois o icms é em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemUltraFPT = 0
                    Else
                        vlrDemUltraFPT = vlrDem_Ultrapassagem_FP / coefTribIcms
                    End If
                End If

                baseIcmsAux = Calc_ICMS(vlrDemUltraFPT, lstrUf, aliqICMS, 5)
                BaseICMS = BaseICMS + baseIcmsAux
            Else
                If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                    vlrDemUltraFPT = (vlrDem_Ultrapassagem_FP * 0.9) / coefTribSIcms
                ElseIf classe = 7 Then
                    'Isento o valor da ultrap fp na base de icms,pois o icms é em cima da demanda lida
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemUltraFPT = 0
                    Else
                        vlrDemUltraFPT = (vlrDem_Ultrapassagem_FP * 0.85) / coefTribSIcms
                    End If
                Else
                    If lblnIcms_Demada_Lida And Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                        vlrDemUltraFPT = 0
                    Else
                        vlrDemUltraFPT = vlrDem_Ultrapassagem_FP / coefTribSIcms
                    End If
                End If

                baseICMSisenta = baseICMSisenta + vlrDemUltraPT
            End If

            vlrTotal = vlrTotal + CDbl(Format(vlrDem_Ultrapassagem_FP, "Standard"))
            Item_Fatura = Trim(Item_Fatura & "0302010026?" & Replace(CStr(Dem_Ultrapassagem_FP), ",", ".") & "$;") 'Consumo Ponta
        End If

        '***********************************************************
        ' CALCULOS DE CONSUMO REATIVO
        ' ALTERAÇÃO POR ADEMIR EM 26 E 27 DE JUNHO DE 2007
        ' - SEPARAÇÃO DO CÁLCULO DE FATOR DE POTÊNCIA ENTRE
        '   HOROSAZONAL VERDE E AZUL
        If lblnCobrarReativo Then
            If tarifa = 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 = Demanda_Lida_P * tarDemanda_p 'vlrDemanda_P + vlrDemanda_FP
                    Kvarh_P = CDbl(txtKvarh_P.Text) - 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

                    Kvarh_P = Arredondar(Kvarh_P, 2)

                    If Kvarh_P <> 0 Then
                        vlrqh = ((Kvarh_P * 2) - BaseConsumo_Reativo) / System.Math.Sqrt(3)
                    Else
                        vlrqh = 0
                    End If

                    If qh = "S" Then
                        aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (vlrqh * vlrqh))
                    Else
                        aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (Kvarh_P * Kvarh_P))
                    End If

                    If aux = 0 Then aux = 1

                    'Fator de Potencia
                    fator_potencia = Arredondar((1 / 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
                            aux = 0.92 / fator_potencia
                            aux = aux - 1
                            vlrKvarh_Consumo_p = Arredondar(vlrBaseConsumo_Reativo * aux, 2)
                            vlrKvarh_Demanda_p = Arredondar(BaseDemanda_Reativa * aux, 2)
                            leitConsumo_aux = aux
                            '-- Demanda Reativa
                            'LeitDemanda_Aux = aux
                        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 = Demanda_Lida_FP * tarDemanda_fp 'vlrDemanda_FP + vlrDem_Ultrapassagem_FP
                    Kvarh_fp = CDbl(txtKvarh_FP.Text) - ant_kvarh_fp 'Ricardo Comentou

                    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 = Arredondar(Kvarh_fp, 2)

                    If Kvarh_fp <> 0 Then
                        vlrqh = ((Kvarh_fp * 2) - BaseConsumo_Reativo) / System.Math.Sqrt(3)
                    Else
                        vlrqh = 0
                    End If

                    If qh = "S" Then
                        aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (vlrqh * vlrqh))
                    Else
                        aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (Kvarh_fp * Kvarh_fp))
                    End If

                    If aux = 0 Then aux = 1

                    fator_potencia = Arredondar((1 / aux) * BaseConsumo_Reativo, 5)

                    If fator_potencia < 0.92 Then
                        If fator_potencia <> 0 Then
                            '-- Consumo Reativo
                            aux = 0.92 / fator_potencia
                            aux = Arredondar(aux - 1, 5)
                            vlrKvarh_Consumo_fp = vlrBaseConsumo_Reativo * aux
                            leitConsumo_aux = aux
                            '-- Demanda Reativa
                            vlrKvarh_Demanda_fp = aux * BaseDemanda_Reativa
                        End If
                    End If
                Else 'If leitura_reativo = 1
                    '****************************
                    'consumo reativo na ponta
                    If gstrEmpresa_Sigla = "EFLUL" Then
                        Kvarh_P = CDbl(txtKvarh_P.Text) - 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
                    Else
                        Kvarh_P = CDbl(txtKvarh_P.Text)
                    End If
                    Kvarh_P = Arredondar(Kvarh_P, 2)
                    vlrKvarh_Consumo_p = Arredondar(Kvarh_P * tarConsumo_p, 2)
                    'demanda reativa na ponta
                    auxdemanda = IIf(ldblDemandaContratadaPonta > Demanda_Lida_P, ldblDemandaContratadaPonta, Demanda_Lida_P)
                    dblDemReatAux = CDbl(IIf(txtDem_Exc_Ponta.Text = "", "0", txtDem_Exc_Ponta.Text))
                    dblDemReatAux = dblDemReatAux * Constante_Kvarh_P
                    dblDemReatAux = Arredondar(dblDemReatAux)
                    If dblDemReatAux > auxdemanda Then
                        ldblDemaAuxP = dblDemReatAux - auxdemanda
                        vlrKvarh_Demanda_p = ldblDemaAuxP * tarDemanda_p
                    Else
                        vlrKvarh_Demanda_p = 0
                    End If
                    '****************************
                    'consumo reativo fora de ponta
                    If gstrEmpresa_Sigla = "EFLUL" Then
                        Kvarh_fp = CDbl(txtKvarh_FP.Text) - 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
                    Else
                        Kvarh_fp = CDbl(txtKvarh_FP.Text)
                    End If
                    Kvarh_fp = Arredondar(Kvarh_fp, 2)
                    vlrKvarh_Consumo_fp = Arredondar(Kvarh_fp * tarConsumo_fp, 2)
                    '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))
                    dblDemReatAux = Arredondar(dblDemReatAux)
                    If dblDemReatAux > auxdemanda Then
                        ldblDemaAuxFP = dblDemReatAux - auxdemanda
                        vlrKvarh_Demanda_fp = ldblDemaAuxFP * tarDemanda_fp
                    Else
                        vlrKvarh_Demanda_fp = 0
                    End If
                End If 'If leitura_reativo = 1
            Else 'if tarifa = 2
                If leitura_reativo = 1 Then
                    '*****************************
                    'CONSUMO E DEMANDA REATIVOS
                    'PELO FATOR DE POTÊNCIA MÉDIO
                    BaseConsumo_Reativo = consumo_p + consumo_fp + Reservado
                    vlrBaseConsumo_Reativo = vlrConsumo_P + vlrConsumo_FP + vlrReservado
                    BaseDemanda_Reativa = Demanda_Lida_FP * tarDemanda_fp 'vlrDemanda_P + vlrDemanda_FP
                    Kvarh_P = CDbl(txtKvarh_P.Text) - ant_kvarh 'Ricardo Comentou

                    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

                    Kvarh_P = Arredondar(Kvarh_P, 2)
                    Kvarh_fp = CDbl(txtKvarh_FP.Text) - ant_kvarh_fp 'Ricardo Comentou

                    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 = Arredondar(Kvarh_fp, 2)
                    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 qh = "S" Then
                        aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (vlrqh * vlrqh))
                    Else
                        aux = System.Math.Sqrt((BaseConsumo_Reativo * BaseConsumo_Reativo) + (Kvarh_fp * Kvarh_fp))
                    End If

                    If aux = 0 Then aux = 1

                    fator_potencia = Arredondar((1 / aux) * BaseConsumo_Reativo, 5)

                    If fator_potencia < 0.92 Then
                        If fator_potencia <> 0 Then
                            '-- Consumo Reativo
                            aux = 0.92 / fator_potencia
                            aux = Arredondar(aux - 1, 10)
                            vlrKvarh_Consumo_p = vlrConsumo_P * aux
                            vlrKvarh_Consumo_fp = (vlrConsumo_FP + vlrReservado) * aux
                            vlrKvarh_Consumo_fp = vlrKvarh_Consumo_fp '+ vlrKvarh_Consumo_p
                            leitConsumo_aux = aux

                            '-- Demanda Reativa
                            vlrKvarh_Demanda_fp = aux * BaseDemanda_Reativa

                            If Demanda_Lida_FP < ldblDemandaContratadaForaPonta Then
                                auxDemandaReativa = (ldblDemandaContratadaForaPonta - Demanda_Lida_FP) * tarDemanda_fp

                                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
                    If gstrEmpresa_Sigla = "EFLUL" Then
                        Kvarh_P = CDbl(txtKvarh_P.Text) - 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
                    Else
                        Kvarh_P = CDbl(txtKvarh_P.Text)
                    End If
                    Kvarh_P = Arredondar(Kvarh_P, lintDecimalKVarh)
                    vlrKvarh_Consumo_p = Arredondar(Kvarh_P * tarConsumo_p, 2)
                    'consumo reativo fora de ponta
                    If gstrEmpresa_Sigla = "EFLUL" Then
                        Kvarh_fp = CDbl(txtKvarh_FP.Text) - 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
                    Else
                        Kvarh_fp = CDbl(txtKvarh_FP.Text)
                    End If
                    Kvarh_fp = Arredondar(Kvarh_fp, lintDecimalKVarh)
                    vlrKvarh_Consumo_fp = Arredondar(Kvarh_fp * tarConsumo_fp, 2)
                    '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))
                    dblDemReatAux = Arredondar(dblDemReatAux, lintDecimalKVarh)
                    If dblDemReatAux > auxdemanda Then
                        ldblDemaAuxFP = dblDemReatAux - auxdemanda
                        vlrKvarh_Demanda_fp = ldblDemaAuxFP * tarDemanda_fp
                    Else
                        vlrKvarh_Demanda_fp = 0
                    End If
                End If
            End If
            If vlrKvarh_Consumo_p <> 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 = "0302020013"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302020013")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Kvarh_P)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrKvarh_Consumo_p, "Standard")

                If classe = 5 And lstrUf = "GO" Then
                    vlrConsReatPT = (vlrKvarh_Consumo_p * 0.9) / coefTribIcms
                    baseIcmsAux = Calc_ICMS(vlrConsReatPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    vlrConsReatPT = (vlrKvarh_Consumo_p * 0.9) / coefTribSIcms
                    baseICMSisenta = baseICMSisenta + (vlrConsReatPT * 0.9)
                ElseIf classe = 7 Then
                    vlrConsReatPT = (vlrKvarh_Consumo_p * 0.85) / coefTribIcms
                    baseIcmsAux = Calc_ICMS(vlrConsReatPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    vlrConsReatPT = vlrKvarh_Consumo_p / coefTribIcms
                    baseIcmsAux = Calc_ICMS(vlrConsReatPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrKvarh_Consumo_p, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010013?" & Replace(CStr(Kvarh_P), ",", ".") & ";") 'kvarh Ponta
            End If

            If vlrKvarh_Consumo_fp <> 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 = "0302020014"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302020014")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Kvarh_fp)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrKvarh_Consumo_fp, "Standard")

                If classe = 5 And lstrUf = "GO" Then
                    vlrConsReatFPT = (vlrKvarh_Consumo_fp * 0.9) / coefTribIcms
                    baseIcmsAux = Calc_ICMS(vlrConsReatFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    vlrConsReatFPT = (vlrKvarh_Consumo_fp * 0.9) / coefTribSIcms
                    baseICMSisenta = baseICMSisenta + (vlrConsReatFPT * 0.9)
                ElseIf classe = 7 Then
                    vlrConsReatFPT = (vlrKvarh_Consumo_fp * 0.85) / coefTribIcms
                    baseIcmsAux = Calc_ICMS(vlrConsReatFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    vlrConsReatFPT = vlrKvarh_Consumo_fp / coefTribIcms
                    baseIcmsAux = Calc_ICMS(vlrConsReatFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrKvarh_Consumo_fp, "Standard"))
                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
                row_grid = 1 + row_grid
                ''grid_fatura.Rows = row_grid + 1
                ''grid_fatura.Row = row_grid
                ''grid_fatura.Col = 0
                ''grid_fatura.Text = "0302020027"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302020027")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(CDbl(ldblDemaAuxP))
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrKvarh_Demanda_p, "Standard")

                If isento_demanda = "N" Then
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemReatPT = (vlrKvarh_Demanda_p * 0.9) / coefTribIcms
                    ElseIf classe = 7 Then
                        vlrDemReatPT = (vlrKvarh_Demanda_p * 0.85) / coefTribIcms
                    Else
                        vlrDemReatPT = vlrKvarh_Demanda_p / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(Arredondar(vlrDemReatPT, 2), lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemReatPT = (vlrKvarh_Demanda_p * 0.9) / coefTribSIcms
                    ElseIf classe = 7 Then
                        vlrDemReatPT = (vlrKvarh_Demanda_p * 0.85) / coefTribSIcms
                    Else
                        vlrDemReatPT = vlrKvarh_Demanda_p / coefTribSIcms
                    End If

                    baseICMSisenta = baseICMSisenta + vlrDemReatPT
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrKvarh_Demanda_p, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010027?" & Replace(CStr(dblDemReatAux - auxdemanda), ",", ".") & ";") 'demanda reativa Ponta
            End If

            If vlrKvarh_Demanda_fp <> 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 = "0302020028"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302020028")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(CDbl(ldblDemaAuxFP))
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrKvarh_Demanda_fp, "Standard")

                If isento_demanda = "N" Then
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemReatFPT = (vlrKvarh_Demanda_fp * 0.9) / coefTribIcms
                    ElseIf classe = 7 Then
                        vlrDemReatFPT = (vlrKvarh_Demanda_fp * 0.85) / coefTribIcms
                    Else
                        vlrDemReatFPT = vlrKvarh_Demanda_fp / coefTribIcms
                    End If

                    baseIcmsAux = Calc_ICMS(vlrDemReatFPT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                Else
                    If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") Then
                        vlrDemReatFPT = (vlrKvarh_Demanda_fp * 0.9) / coefTribSIcms
                    ElseIf classe = 7 Then
                        vlrDemReatFPT = (vlrKvarh_Demanda_fp * 0.85) / coefTribSIcms
                    Else
                        vlrDemReatFPT = vlrKvarh_Demanda_fp / coefTribSIcms
                    End If

                    baseICMSisenta = baseICMSisenta + vlrDemReatFPT
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrKvarh_Demanda_fp, "Standard"))
                Item_Fatura = Trim(Item_Fatura & "0302010028?" & Replace(CStr(dblDemReatAux - auxdemanda), ",", ".") & ";") 'demanda reativa Ponta
            End If
        End If 'lblnCobrarReativo

        'consumo reativo capacitivo fora de ponta
        If CDbl(txtKwh_Cap_Reat_FP.Text) > 0 Then
            consumoReativoCapacitivo = CDbl(txtKwh_Cap_Reat_FP.Text)
            vlrConsumoReativoCapacitivo = consumoReativoCapacitivo * tarConsumo_fp
        End If

        If vlrConsumoReativoCapacitivo <> 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 = "0302990105"
            ''grid_fatura.Col = 1
            ''grid_fatura.Text = CStr("0302990105")
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = CStr(consumoReativoCapacitivo)
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrConsumoReativoCapacitivo, "Standard")

            If classe = 5 And lstrUf = "GO" Then
                vlrConsCapFPT = (vlrConsumoReativoCapacitivo * 0.9) / coefTribIcms
                baseIcmsAux = Calc_ICMS(vlrConsCapFPT, lstrUf, aliqICMS, 5)
                BaseICMS = BaseICMS + baseIcmsAux
            ElseIf classe = 5 And lstrUf = "RS" Then
                vlrConsCapFPT = vlrConsumoReativoCapacitivo / coefTribSIcms
                baseICMSisenta = baseICMSisenta + (vlrConsCapFPT * 0.9)
            ElseIf classe = 7 Then
                vlrConsCapFPT = (vlrConsumoReativoCapacitivo * 0.85) / coefTribIcms
                baseIcmsAux = Calc_ICMS(vlrConsCapFPT, lstrUf, aliqICMS, 5)
                BaseICMS = BaseICMS + baseIcmsAux
            Else
                vlrConsCapFPT = vlrConsumoReativoCapacitivo / coefTribIcms
                baseIcmsAux = Calc_ICMS(vlrConsCapFPT, lstrUf, aliqICMS, 5)
                BaseICMS = BaseICMS + baseIcmsAux
            End If

            vlrTotal = vlrTotal + CDbl(Format(vlrConsumoReativoCapacitivo, "Standard"))
            Item_Fatura = Trim(Item_Fatura & "0302990110?" & Replace(CStr(consumoReativoCapacitivo), ",", ".") & ";") 'kvarh f Ponta
        End If

        '----- desconto consumidor rural -----
        If classe = 5 And (lstrUf = "GO" Or lstrUf = "RS") 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 = CStr("9070000002") & " (10%)"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = ""
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format((vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.1, "Standard")
            vlrTotal = vlrTotal - CDbl(Format((vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.1, "Standard"))
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "(10%)"
        End If

        '----- desconto 15% para o poder público -----
        If classe = 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 = CStr("9070000001")
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = ""
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format((vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.15, "Standard")
            vlrTotal = vlrTotal - CDbl(Format((vlrConsumo_P + vlrConsumo_FP + vlrDemanda_P + vlrDemanda_FP + vlrDem_Ultrapassagem_P + vlrDem_Ultrapassagem_FP + vlrKvarh_Consumo_p + vlrKvarh_Consumo_fp + vlrKvarh_Demanda_p + vlrKvarh_Demanda_fp + vlrConsumoReativoCapacitivo) * 0.15, "Standard"))
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "(15%)"
        End If

        '-- PRECISA OLHAR ESTE CONSUMO RESERVADO
        '-- Consumo Reservado
        Dim vlrKvarhReservado As Double
        Dim vlrKvarhReservadoT As Double
        If Val(Replace(txtReservado.Text, ",", ".")) > 0 Then
            Reservado = Arredondar(Reservado)

            If Reservado > 0 Then
                vlrReservado = Reservado * tarCons_Reservado
                row_grid = 1 + row_grid
                ''grid_fatura.Rows = row_grid + 1
                ''grid_fatura.Row = row_grid
                ''grid_fatura.Col = 0
                ''grid_fatura.Text = "0302990044"
                ''grid_fatura.Col = 1
                ''grid_fatura.Text = CStr("0302990044") & " ( " & Reservado & " x " & tarCons_Reservado & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Reservado)
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrReservado, "Standard")
                ''grid_fatura.Col = 4
                ''grid_fatura.Text = "( " & Reservado & " x " & tarCons_Reservado & " )"

                If classe = 5 And lstrUf = "GO" Then
                    If checaAdimplencia(lstrZona, lstrLivro, lstrConta) = 0 Then
                        vlrReservadoT = Arredondar((vlrReservado * 0.2) / coefTribIcms, 2)
                    Else
                        vlrReservadoT = Arredondar((vlrReservado * 0.9) / coefTribIcms, 2)
                    End If

                    baseIcmsAux = Calc_ICMS(vlrReservadoT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                ElseIf classe = 5 And lstrUf = "RS" Then
                    consTrib = Arredondar(Reservado / consTotal, 2) * 100
                    consIsento = Reservado - consTrib
                    vlrConsTrib = ((consTrib * tarCons_Reservado) / coefTribIcms) * 0.3
                    vlrConsIsento = ((consIsento * tarCons_Reservado) / coefTribSIcms) * 0.3
                    baseIcmsAux = Calc_ICMS(vlrConsTrib, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                    baseICMSisenta = baseICMSisenta + (vlrConsIsento)
                Else
                    vlrReservadoT = Arredondar(vlrReservado / coefTribIcms, 2)
                    baseIcmsAux = Calc_ICMS(vlrReservadoT, lstrUf, aliqICMS, 5)
                    BaseICMS = BaseICMS + baseIcmsAux
                End If

                vlrTotal = vlrTotal + CDbl(Format(vlrReservado, "Standard"))

                '----- Consumo reativo do reservado -----
                If lstrUf = "GO" Then

                    If aux <= 1 Then vlrKvarhReservado = vlrReservado * aux

                    If vlrKvarhReservado <> 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 = "0302010099"
                        ''grid_fatura.Col = 1
                        ''grid_fatura.Text = "CONSUMO REATIVO DO RESERVADO"
                        ''grid_fatura.Col = 2
                        ''grid_fatura.Text = ""
                        ''grid_fatura.Col = 3
                        ''grid_fatura.Text = Format(vlrKvarhReservado, "Standard")

                        If classe = 5 And lstrUf = "GO" Then
                            If checaAdimplencia(lstrZona, lstrLivro, lstrConta) = 0 Then
                                vlrKvarhReservadoT = (vlrKvarhReservado * 0.2) / coefTribIcms
                            Else
                                vlrKvarhReservadoT = (vlrKvarhReservado * 0.9) / coefTribIcms
                            End If

                            baseIcmsAux = Calc_ICMS(vlrKvarhReservadoT, lstrUf, aliqICMS, 5)
                            BaseICMS = BaseICMS + baseIcmsAux
                        End If

                        vlrTotal = vlrTotal + CDbl(Format(vlrKvarhReservado, "Standard"))
                        '            Item_Fatura = Trim(Item_Fatura & "03020100xx?" & Replace(Kvarh_P, ",", ".") & ";") 'kvarh Ponta
                    End If
                End If
            End If
        End If
        '----- fim do consumo reservado -----

        '----- desconto consumo incentivado/reservado rural -----
        If classe = 5 Then
            row_grid = 1 + row_grid
            ''grid_fatura.Rows = row_grid + 1
            ''grid_fatura.Row = row_grid
            ''grid_fatura.Col = 0
            ''grid_fatura.Text = "9070000003"
            ''grid_fatura.Col = 1

            If lstrUf = "GO" Then
                If checaAdimplencia(lstrZona, lstrLivro, lstrConta) = 0 Then
                    ''grid_fatura.Text = CStr("9070000003") & " ( 80% )"
                Else
                    ''grid_fatura.Text = CStr("9070000003") & " ( 10% )"
                End If
            ElseIf lstrUf = "RS" Or lstrUf = "SC" Then
                ''grid_fatura.Text = CStr("9070000003") & " ( 70% )"
            End If

            ''grid_fatura.Col = 2
            ''grid_fatura.Text = ""
            ''grid_fatura.Col = 4

            If lstrUf = "GO" Then
                If checaAdimplencia(lstrZona, lstrLivro, lstrConta) = 0 Then
                    ''grid_fatura.Text = "(80%)"
                Else
                    ''grid_fatura.Text = "(10%)"
                End If
            ElseIf lstrUf = "RS" Or lstrUf = "SC" Then
                ''grid_fatura.Text = "(70%)"
            End If

            If lstrUf = "GO" Then
                If checaAdimplencia(lstrZona, lstrLivro, lstrConta) = 0 Then
                    ''grid_fatura.Text = Format((vlrReservado + vlrKvarhReservado) * 0.8, "Standard")
                    vlrTotal = vlrTotal - CDbl(Format((vlrReservado + vlrKvarhReservado) * 0.8, "Standard"))
                Else
                    ''grid_fatura.Text = Format((vlrReservado + vlrKvarhReservado) * 0.1, "Standard")
                    vlrTotal = vlrTotal - CDbl(Format((vlrReservado + vlrKvarhReservado) * 0.1, "Standard"))
                End If
            ElseIf lstrUf = "RS" Or lstrUf = "SC" Then
                ''grid_fatura.Text = Format(vlrReservado * 0.7, "Standard")
                vlrTotal = vlrTotal - CDbl(Format(vlrReservado * 0.7, "Standard"))
            End If
        End If

        'calcula a base do ICMS
        'teste feito por ademir

        basePisCofins = Arredondar(BaseICMS + baseICMSisenta, 2)
        BasePis = basePisCofins
        BaseCofins = basePisCofins

        If gstrEmpresa_Sigla = "CHESP" Then
            Call CobrarSobreTaxa(vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        End If
        If gstrEmpresa_Sigla = "EFLUL" Then
            Call CobrarSobreTaxaEflul(lstrZona, lstrLivro, lstrConta, Id_Consumidor, Id_Unid, vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        End If

        Call CobrarConvenios(vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        Call CobrarTaxas(vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)


        '----- Pis ---------------------------------------------------------------------------------------------
        vlrPis = Arredondar(BasePis * (AliqPIS / 100), 2)
        'vlrPis = Arredondar(BaseICMS * (AliqPIS / 100), 2) + Arredondar(Arredondar(baseICMSisenta, 2) * (AliqPIS / 100), 2)
        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"
            ''grid_fatura.Col = 1
            ''grid_fatura.Text = CStr("0302020029") & " ( " & Format(AliqPIS, "Standard") & "% )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = Format(BasePis, "Standard")
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrPis, "Standard")
            vlrTotal = vlrTotal + CDbl(Format(vlrPis, "Standard"))
            Item_Fatura = Trim(Item_Fatura & "0302020033?" & Replace(CStr(BasePis), ",", ".") & ";") ' Base de Pis
        End If

        '----- Cofins ------------------------------------------------------------------------------------------
        vlrCofins = Arredondar(BaseCofins * (AliqCofins / 100), 2)
        'vlrCofins = Arredondar(BaseICMS * (AliqCofins / 100), 2) + Arredondar(Arredondar(baseICMSisenta, 2) * (AliqCofins / 100), 2)

        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 = CStr("0302020030") & " ( " & Format(AliqCofins, "Standard") & "% )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = Format(BaseCofins, "Standard")
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrCofins, "Standard")
            vlrTotal = vlrTotal + CDbl(Format(vlrCofins, "Standard"))
            Item_Fatura = Trim(Item_Fatura & "0302020034?" & Replace(CStr(BaseCofins), ",", ".") & ";") ' Base de Cofins
        End If


        '-- ICMS
        If BaseICMS > 0 Then
            ICMS = Arredondar(BaseICMS * (aliqICMS / 100), 2)
            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 = CStr("0302030009") & " (" & Format(aliqICMS, "Standard") & "% )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = Format(BaseICMS, "Standard")
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(ICMS, "Standard")
            ''grid_fatura.Col = 4
            vlrTotal = vlrTotal + CDbl(Format(ICMS, "Standard"))
        End If

        'Vou criar uma funcao para corrigir esta POG ai embaixo com outra POG, pois tens convenios e ou taxas que não incidem ICMS
        If isento_demanda = "N" Then
            'FatorAjuste = Arredondar((BaseICMS - vlrTotal) - vlrIsentoIcms, 2)
        Else
            FatorAjuste = Arredondar(BaseICMS - (vlrTotal - baseICMSisenta) - vlrIsentoIcms, 2)
        End If

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


        '-- Iluminação
        If strIsentIlum = "N" Then
            sql = "SELECT * FROM cip WHERE (CIDADE)=" & llngCodigoCidade & " "


            objAtualizaBancoDados.QUERY_NAME = sql
            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 Mid(classe, 1, 1) = "6" Then
            '        classeR = Val(Mid(classeR, 1, 2))
            '      Else
            '        classeR = Val(Mid(classe, 1, 1))
            '      End If

            '----- Verifica se o município é Ceres. Se for, pega o consumo do mês anterior para calcular a CIP. --
            sql = "SELECT nome FROM munic WHERE codnum = " & llngCodigoCidade

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

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows
                    If row("nome") = "CERES" Then
                        consumo_p = getUltConsumo(lstrZona, lstrLivro, lstrConta, "0302010010")
                        consumo_fp = getUltConsumo(lstrZona, lstrLivro, lstrConta, "0302010011")
                    End If
                Next
            End If

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

            Ilum = Calc_ILUM_Horo(llngCodigoCidade, strClasseIlum, consumolido_p, consumolido_fp, Demanda_Faturada_P, Demanda_Faturada_FP, Dem_Ultrapassagem_P, Dem_Ultrapassagem_FP, TpFaixaC)

            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 = CStr("0301000003")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Arredondar(Ilum, 2))
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(Ilum, "Standard")
                vlrTotal = vlrTotal + CDbl(Format(Ilum, "Standard"))
            End If
        End If
        '***********************************************************

        'Retenção Tributária
        If Mid(strClasseIlum, 1, 2) = "63" Then
            baseRetCons = Arredondar(vlrConsumoPT + vlrConsumoFPT + vlrReservadoT + vlrConsReatPT + vlrConsReatFPT + vlrConsCapFPT, 2)
            baseRetDem = Arredondar(vlrDemandaPT + vlrDemandaFPT + vlrDemUltraPT + vlrDemUltraFPT + vlrDemReatPT + vlrDemReatFPT, 2)
            baseRetCons = Arredondar(baseRetCons / (1 - (aliqICMS / 100)), 2)
            baseRetDem = Arredondar(baseRetDem / (1 - (aliqICMS / 100)), 2)
            base_retencao = Arredondar(baseRetCons + baseRetDem, 2)

            'lstrRetencoes = GetConfig("RETENCAO_FEDERAL")

            vlrLiqui = 0

            'retencao pis
            retPis = 0.65 / 100
            vlrRetPis = Arredondar(baseRetCons * 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 = Format(vlrRetPis, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetPis, "Standard"))
            End If

            'retencao cofins
            retCofins = 3 / 100
            vlrRetCofins = Arredondar(baseRetCons * 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 = Format(vlrRetCofins, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetCofins, "Standard"))
            End If

            'retencao csll
            retCsll = 1 / 100
            vlrRetCsll = Arredondar(baseRetCons * 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 = Format(vlrRetCsll, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetCsll, "Standard"))
            End If

            'retencao IR consumo
            retIRCons = 1.2 / 100
            vlrRetIRCons = Arredondar(baseRetCons * 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 = Format(vlrRetIRCons, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetIRCons, "Standard"))
            End If

            'retencao demanda
            retIRDem = 4.8 / 100
            vlrRetIRDem = Arredondar(baseRetDem * 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 = Format(vlrRetIRDem, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetIRDem, "Standard"))
            End If

            'retencao csll
            retCsll = 1 / 100
            vlrRetCsll = Arredondar(baseRetDem * 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 = Format(vlrRetCsll, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetCsll, "Standard"))
            End If

            'retencao cofins
            retCofins = 3 / 100
            vlrRetCofins = Arredondar(baseRetDem * 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 = Format(vlrRetCofins, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetCofins, "Standard"))
            End If

            'retencao pis
            retPis = 0.65 / 100
            vlrRetPis = Arredondar(baseRetDem * 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 = Format(vlrRetPis, "Standard")
                vlrLiqui = vlrLiqui - CDbl(Format(vlrRetPis, "Standard"))
            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
        Call VerDelMultaJuro(lstrZona, lstrLivro, lstrConta)

        dtDataFat = CDate(Format("01/" & txtMesAno.Text, "dd/mm/yyyy"))
        dtDataRefMulta = System.DateTime.FromOADate(dtDataFat.ToOADate - 1)
        strMesRefMulta = Format(dtDataRefMulta, "mm/yyyy")
        ''''''''Call CalculaMultaJuros(lstrZona, lstrLivro, lstrConta, strMesRefMulta)

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

        objAtualizaBancoDados.QUERY_NAME = sql
        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 = CStr("9080000061") & " REF. MÊS " & row("mesano")
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = ""
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(row("vlrMulta"), "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                    '''grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                    vlrTotal = vlrTotal + CDbl(Format(row("vlrMulta"), "Standard"))
                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 = CStr("9080000066") & " REF. MÊS " & row("mesano")
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = ""
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(row("vlrJuros"), "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                    '''grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                    vlrTotal = vlrTotal + CDbl(Format(row("vlrJuros"), "Standard"))
                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 = CStr("9080000067") & " REF. MÊS " & row("mesano")
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = ""
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(row("vlrCM"), "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                    '''grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                    vlrTotal = vlrTotal + CDbl(Format(row("vlrCM"), "Standard"))
                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.
        sql = "update multajuros set cobrado = 'S' where zona = '" & lstrZona & "' and livro = '" & lstrLivro & "' and conta = '" & lstrConta & "';"

        objAtualizaBancoDados.QUERY_NAME = sql
        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

        Item_Fatura = Trim(Item_Fatura & "40PIS00001?" & Replace(CStr(AliqPIS), ",", ".") & ";")
        Item_Fatura = Trim(Item_Fatura & "40COF00001?" & Replace(CStr(AliqCofins), ",", ".") & ";")
        Item_Fatura = Trim(Item_Fatura & "0302030001?" & Replace(CStr(BaseICMS), ",", ".") & ";")
        Item_Fatura = Trim(Item_Fatura & "0302030002?" & Replace(CStr(aliqICMS), ",", ".") & ";")



        '----- Cálculo do arredondamento -----------------------------
        If GetConfig("ARREDONDAR_TOTAL_NF") = "S" And vlrTotal > 0 Then
            Call Arredondamento(vlrTotal, Id_Unid)
        End If
        '-------------------------------------------------------------

        lblTotal.Text = Format(vlrTotal, "Standard")
        lblTotalLiq.Text = Format(vlrTotal + vlrLiqui, "Standard")

    End Sub

    Private Sub Calc_Convencional()
        Dim sql As String

        Dim strSigla As String
        Dim dias As Short
        Dim row_grid As Short

        Dim vlrConsumo 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 aliqICMS 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 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 coefTribIcms 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 baseIcmsAux As Double
        Dim baseICMSisenta As Double
        Dim FatorAjuste As Double
        Dim casas As Short


        Dim lstrSql As String
        '' Dim lrstConsulta As ADODB.Recordset
        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
        '----- 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 lrstMultaJuros As ADODB.Recordset
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset
        'lrstMultaJuros = New ADODB.Recordset
        'lrstConsulta = New ADODB.Recordset

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados



        lstrPercDemU = Trim(GetConfig("GRUPOA_PERCENTUAL_KW_ULTRAP"))
        If lstrPercDemU = "-1" Then
            ldblPercDemU = 10
            Call SetConfig("GRUPOA_PERCENTUAL_KW_ULTRAP", "String", CStr(ldblPercDemU), True, "Percentual de Demanda Ultrapassagem")
        ElseIf Len(lstrPercDemU) = 0 Then
            ldblPercDemU = 10
            Call SetConfig("GRUPOA_PERCENTUAL_KW_ULTRAP", "String", CStr(ldblPercDemU))
        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
        Call Form_() ''grid_fatura()
        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"))

        casas = 9

        lblnCalcReativo = MsgBox("Deseja calcular consumo e a demanda reativo", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes

        lstrSql = "SELECT * " & "  FROM uc_faturamento " & " WHERE cons_id = " & Id_Consumidor & "   AND unid_id = " & Id_Unid


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

        If dt.Rows.Count <> 0 Then
            For Each row As DataRow In dt.Rows
                lstrCidade = Trim(IIf(IsDBNull(row("cidade")), "", row("cidade")))
                lstrClasse = Format(Trim(IIf(IsDBNull(row("clas")), "0", row("clas"))), "0000")
                lstrZona = Trim(IIf(IsDBNull(row("zona")), "", row("zona")))
                lstrLivro = Trim(IIf(IsDBNull(row("livro")), "", row("livro")))
                lstrConta = Trim(IIf(IsDBNull(row("conta")), "", row("conta")))
                lstrInscricaoEstadual = Trim(IIf(IsDBNull(row("insc")), "", row("insc")))
                lstrUFUnidade = Trim(IIf(IsDBNull(row("uf")), "", row("uf")))

                ldblConstanteConsumo = IIf(IsDBNull(row("const_consumo")), 0, row("const_consumo"))
                ldblConstanteDemanda = IIf(IsDBNull(row("const_demanda")), 0, row("const_demanda"))
                ldblConstanteReativo = IIf(IsDBNull(row("const_kvarh")), 0, row("const_kvarh"))
                ldblPerdas = IIf(IsDBNull(row("final")), 0, row("final"))
                ldblContratoDemanda = IIf(IsDBNull(row("demanda_contr")), 0, row("demanda_contr"))
                dDataContrato = 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"
                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
            Call MsgBox("O consumidor " & lstrZona & "." & lstrLivro & "." & lstrConta & ", não possui Unidade Federativa!" & Chr(10) & Chr(13) & "*** Não será faturado! ***", MsgBoxStyle.Critical)
            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("codnum")), 0, row("codnum"))
            Next
        Else
            Call MsgBox("Atenção! O município " & lstrCidade & " não está cadastrado!", MsgBoxStyle.Information)
            Exit Sub
        End If

        Call Carr_Leit_Anterior(dDataContrato, ldblContratoDemanda, 0)
        Call TarifaConvencional()

        If CDbl(VB.Left(lstrClasse, 1)) = 5 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(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(txtLeit_Demanda.Text, ",", ".") & ";") 'demanda atual
        Item_Fatura = Trim(Item_Fatura & "0302040015?" & Replace(CStr(ant_kvarh), ",", ".") & ";") 'reativo anterior
        Item_Fatura = Trim(Item_Fatura & "0302040016?" & Replace(txtLeit_Kvarh.Text, ",", ".") & ";") 'reativo atual

        'tarifas aplicadas
        Item_Fatura = Trim(Item_Fatura & "01A4011101?" & Replace(CStr(tarConsumo), ",", ".") & ";") 'Tarifa do Consumo
        Item_Fatura = Trim(Item_Fatura & "01A4012101?" & Replace(CStr(tarDemanda), ",", ".") & ";") 'Tarifa Demanda
        Item_Fatura = Trim(Item_Fatura & "01A4012102?" & Replace(CStr(tarDemUltra), ",", ".") & ";") 'Tarifa Demanda Ultra

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

        leitAtual = CDbl(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)

        aliqICMS = Busca_Aliquota_ICMS(lstrUFUnidade, ldblQtdConsumo, lstrClasse)

        'Ricardo colocou essas tarifa para o calculo do CIP que estava faltando
        tarConsumoPISCOF = Truncate(tarConsumo / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), 5)
        tarDemandaPISCOF = Truncate(tarDemanda / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), 2)

        coefTribIcms = 1 - (((AliqPIS / 100) + (AliqCofins / 100)) / (1 - (aliqICMS / 100)))
        coefTribSIcms = 1 - ((AliqPIS / 100) + (AliqCofins / 100))


        vlrConsumo = Arredondar(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(CStr("0302020008")) & " ( " & ldblQtdConsumo & " x " & tarConsumo & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = CStr(ldblQtdConsumo)
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrConsumo, "Standard")
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "( " & ldblQtdConsumo & " x " & tarConsumo & " )"

            If CDbl(VB.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                vlrConsumoT = (vlrConsumo * 0.9) / coefTribIcms
            ElseIf CDbl(VB.Left(lstrClasse, 1)) = 7 Then
                vlrConsumoT = (vlrConsumo * 0.85) / coefTribIcms
            Else
                vlrConsumoT = vlrConsumo / coefTribIcms
            End If

            baseIcmsAux = Calc_ICMS(vlrConsumoT, lstrUFUnidade, aliqICMS, 5)
            BaseICMS = BaseICMS + baseIcmsAux

            vlrTotal = vlrTotal + CDbl(Format(vlrConsumo, "Standard"))

            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

        '-- 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)
                    If istrRes414_Art104 = "S" Then
                        Demanda_Faturada = Demanda_Lida
                    Else
                        Demanda_Faturada = ldblContratoDemanda
                    End If
                End If
            ElseIf Demanda_Lida < ldblContratoDemanda Then
                If CDbl(VB.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
        Demanda_Faturada = Arredondar(Demanda_Faturada, lintDecimalKw)
        vlrDemanda = Arredondar(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 = CStr("0302020015") & " ( " & Demanda_Faturada & " x " & tarDemanda & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = CStr(Demanda_Faturada)
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrDemanda, "Standard")
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "( " & Demanda_Faturada & " x " & tarDemanda & " )"

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

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

                baseICMSisenta = baseICMSisenta + vlrDemandaT
            End If

            vlrTotal = vlrTotal + CDbl(Format(vlrDemanda, "Standard"))

            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)
            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 = CStr("0302020018") & " ( " & Dem_Ultrapassagem & " x " & tarDemUltra & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = CStr(Dem_Ultrapassagem)
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrDem_ultrapassagem, "Standard")
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "( " & Dem_Ultrapassagem & " x " & tarDemUltra & " )"

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

                baseIcmsAux = Calc_ICMS(vlrDemUltraT, lstrUFUnidade, aliqICMS, 5)
                BaseICMS = BaseICMS + baseIcmsAux
            Else
                If CDbl(VB.Left(lstrClasse, 1)) = 5 And lstrUFUnidade = "RS" Then
                    vlrDemUltraT = (vlrDem_ultrapassagem * 0.9) / coefTribSIcms
                ElseIf CDbl(VB.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(Format(vlrDem_ultrapassagem, "Standard"))

            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)

                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)

                        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)
                '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
            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 = CStr("0302020012") '& " ( " & Arredondar(vlrConsumo, 2) & " x " & Arredondar(leitConsumo_aux, 5) & " )"
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Arredondar(vlrConsumo, 2))
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrKvarh_consumo, "Standard")

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

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

                vlrTotal = vlrTotal + CDbl(Format(vlrKvarh_consumo, "Standard"))

            End If
            Item_Fatura = Trim(Item_Fatura & "0302010012?" & Replace(CStr(kVArh), ",", ".") & ";") ' Consumo Reativo

            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 = CStr("0302020031")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Arredondar(leitDemanda_aux))
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(vlrKvarh_demanda, "Standard")

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

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

                vlrTotal = vlrTotal + CDbl(Format(vlrKvarh_demanda, "Standard"))
            End If
        End If

        '----- desconto consumidor rural -----
        If CDbl(VB.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 = CStr("9070000002") & "(10%)"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = ""
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format((vlrConsumo + vlrDemanda + vlrDem_ultrapassagem + vlrKvarh_consumo + vlrKvarh_demanda) * 0.1, "Standard")

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

        '----- desconto para o poder público -----
        If CDbl(VB.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 = CStr("9070000001") & " (15%)"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = ""
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format((vlrConsumo + vlrDemanda + vlrDem_ultrapassagem + vlrKvarh_consumo + vlrKvarh_demanda) * 0.15, "Standard")

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

        '-- Retenção Tributária
        If VB.Left(lstrClasse, 2) = "63" Then
            vlr_retencao = Arredondar(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" 'cstr("9080000088")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = ""
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = "-" & Format(vlr_retencao, "Standard")
            End If
        End If

        vlrPis = Arredondar(BaseICMS * (AliqPIS / 100), 2) + Arredondar(baseICMSisenta * (AliqPIS / 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 = CStr("0302020029") & " ( " & Format(AliqPIS, "Standard") & "% )"
            '& " ( " & BaseICMS & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = Format(BaseICMS, "Standard")
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrPis, "Standard")

            vlrTotal = vlrTotal + CDbl(Format(vlrPis, "Standard"))

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

        vlrCofins = Arredondar(BaseICMS * (AliqCofins / 100), 2) + Arredondar(baseICMSisenta * (AliqCofins / 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 = CStr("0302020030") & " ( " & Format(AliqCofins, "Standard") & "% )"
            '& " ( " & BaseICMS & " )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = Format(BaseICMS, "Standard")
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(vlrCofins, "Standard")

            vlrTotal = vlrTotal + CDbl(Format(vlrCofins, "Standard"))

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

        '-----------------------------------------------------------------
        If gstrEmpresa_Sigla = "CHESP" Then
            Call CobrarSobreTaxa(vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        End If
        If gstrEmpresa_Sigla = "EFLUL" Then
            Call CobrarSobreTaxaEflul(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, Id_Consumidor, Id_Unid, vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        End If

        Call CobrarConvenios(vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        Call CobrarTaxas(vlrTotal, row_grid, aliqICMS, coefTribIcms, vlrIsentoIcms)
        '-----------------------------------------------------------------

        ICMS = BaseICMS * (aliqICMS / 100)

        '-- ICMS
        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 = CStr("0302030009") & " ( " & Format(aliqICMS, "Standard") & "% )"
            '& " ( " & BaseICMS & " x " & Format(aliqICMS, "Standard") & "% )"
            ''grid_fatura.Col = 2
            ''grid_fatura.Text = Format(BaseICMS, "Standard")
            ''grid_fatura.Col = 3
            ''grid_fatura.Text = Format(ICMS, "Standard")
            ''grid_fatura.Col = 4
            ''grid_fatura.Text = "( " & BaseICMS & " x " & Format(aliqICMS, "Standard") & "% )"

            vlrTotal = vlrTotal + CDbl(Format(ICMS, "Standard"))

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

        FatorAjuste = Arredondar((BaseICMS - vlrTotal) - vlrIsentoIcms, 2)

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

            ''grid_fatura.Col = 2
            ''grid_fatura.set_TextMatrix(''grid_fatura.Row, ''grid_fatura.Col, Format(BaseICMS, "Standard"))
            ''grid_fatura.set_TextMatrix(''grid_fatura.Row - 1, ''grid_fatura.Col, Format(BaseICMS, "Standard"))
            ''grid_fatura.set_TextMatrix(''grid_fatura.Row - 2, ''grid_fatura.Col, Format(BaseICMS, "Standard"))
        End If

        '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
        Call VerDelMultaJuro(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text)

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

        ''''''''''Call CalculaMultaJuros(lstrZona, lstrLivro, lstrConta, strMesRefMulta)

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

        objAtualizaBancoDados.QUERY_NAME = sql
        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 = CStr("9080000061") & " REF. MÊS " & row("mesano")
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = ""
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(row("vlrMulta"), "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                    vlrTotal = vlrTotal + CDbl(Format(row("vlrMulta"), "Standard"))
                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 = CStr("9080000066") & " REF. MÊS " & row("mesano")
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = ""
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(row("vlrJuros"), "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                    '''grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                    vlrTotal = vlrTotal + CDbl(Format(row("vlrJuros"), "Standard"))
                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 = CStr("9080000067") & " REF. MÊS " & row("mesano")
                    ''grid_fatura.Col = 2
                    ''grid_fatura.Text = ""
                    ''grid_fatura.Col = 3
                    ''grid_fatura.Text = Format(row("vlrCM"), "Standard")
                    ''grid_fatura.Col = 4
                    ''grid_fatura.Text = "( " & " Fatura " & row("numNf") & " " & row("mesano") & " )"
                    '''grid_fatura.Text = "( " & " REF. MÊS " & lrstMultaJuros!mesano & " )"
                    vlrTotal = vlrTotal + CDbl(Format(row("vlrCM"), "Standard"))
                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.
        sql = "UPDATE multajuros SET cobrado = 'S' WHERE zona = '" & lstrZona & "' AND livro = '" & lstrLivro & "' AND conta = '" & lstrConta & "';"

        objAtualizaBancoDados.QUERY_NAME = sql
        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

        '-- Iluminação Publica
        If Not lblnIsentoIluminacao Then
            sql = "SELECT * FROM cip WHERE cidade = " & llngCodigoCidade & " "


            objAtualizaBancoDados.QUERY_NAME = sql
            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


            '----- Verifica se o município é Ceres. Se for, pega o consumo do mês anterior para calcular a CIP. ----
            '' sql = "SELECT nome FROM munic WHERE codnum = " & llngCodigoCidade
            If IIf(IsDBNull(GetValorTabela("munic", "nome", "codnum = " & llngCodigoCidade)), "", GetValorTabela("munic", "nome", "codnum = " & llngCodigoCidade)) = "CERES" Then
                ldblQtdConsumo = getUltConsumo(lstrZona, lstrLivro, lstrConta, "0302010009")
            End If

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

            If TpConsumo = "A" Then
                Ilum = Calc_ILUM(llngCodigoCidade, lstrClasse, ldblQtdConsumo, Demanda_Faturada, Dem_Ultrapassagem, TpFaixaC)
            Else
                Ilum = Calc_ILUM(llngCodigoCidade, lstrClasse, ldblQtdConsumo, Demanda_Faturada, Dem_Ultrapassagem, TpFaixaC)
            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 = CStr("0301000003")
                ''grid_fatura.Col = 2
                ''grid_fatura.Text = CStr(Arredondar(Ilum, 2))
                ''grid_fatura.Col = 3
                ''grid_fatura.Text = Format(Ilum, "Standard")

                vlrTotal = vlrTotal + CDbl(Format(Ilum, "Standard"))
            End If
        End If

        '----- Cálculo do arredondamento -----------------------------
        If GetConfig("ARREDONDAR_TOTAL_NF") = "S" And vlrTotal > 0 Then
            Call Arredondamento(vlrTotal, Id_Unid)
        End If
        '-------------------------------------------------------------

        ''grid_fatura.Redraw = True

        lblTotal.Text = Format(vlrTotal, "Standard")
        lblTotalLiq.Text = lblTotal.Text

    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 strsql 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 rsIluminacao As ADODB.Recordset

        ''rsIluminacao = New ADODB.Recordset

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

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


        objAtualizaBancoDados.QUERY_NAME = strsql
        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)

    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) As Double

        Dim strsql 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 rsIluminacao As ADODB.Recordset

        'rsIluminacao = New ADODB.Recordset

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Dim Cod As Short

        dblConsumo = (adblConsumoPonta + adblConsumoFponta)
        strsql = ""
        strsql = strsql & "SELECT * "
        strsql = strsql & "  FROM cip "
        strsql = strsql & " WHERE cidade = " & aintIdCidade & " "
        strsql = strsql & "   AND classe = " & Mid(Trim(astrClasse), 1, IIf(CDbl(VB.Left(astrClasse, 1)) = 6, 2, 1)) & " "
        strsql = strsql & "   AND " & Replace(CStr(dblConsumo), ",", ".") & " BETWEEN faixa_ini AND faixa_fim "
        strsql = strsql & "   AND data <= '" & Format(CDate(Me.txtDt_Leit_Atual.Text), "yyyy-MM-dd") & "' "
        strsql = strsql & " ORDER BY data DESC "
        strsql = strsql & " LIMIT 0, 1 "


        objAtualizaBancoDados.QUERY_NAME = strsql
        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)
                    End If
                ElseIf UCase(strTipo) = "P" Then  'caso for percentual
                    dblAuxIlum = dblConsumo * (dblIlum / 100)
                ElseIf UCase(strTipo) = "F" Then  'caso for valor fixo
                    dblAuxIlum = dblIlum
                End If
            Next
        End If
        Calc_ILUM_Horo = Arredondar(dblAuxIlum, 2)
    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 sql As String
        Dim localBase As Double
        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)

    End Function

    Private Sub Grava_Fatura()
        Dim strsql As String
        Dim dblNumNf As Double
        Dim dblNsuNr As Double
        Dim strItensServ As String
        Dim strBanco As String
        Dim strNmBco As String
        Dim lngConta As Integer

        'auxiliares para o codigo hash
        Dim strAuxHash As String
        Dim strCnpj As String
        Dim strNumNf As String
        Dim strVlrTotal As String
        Dim strBaseICMS As String
        Dim strVlrICMS As String
        Dim strCodHash As String
        Dim lngDias As Integer
        Dim strSigla As String
        Dim strCodBarra As String
        Dim strDvCBarra As String

        ''Dim rsFatura As ADODB.Recordset
        ''Dim rsConsulta As ADODB.Recordset
        ''Dim rsHash As ADODB.Recordset

        Dim dt As DataTable
        Dim dt1 As DataTable
        Dim dt2 As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        If Val(lblTotal.Text) < 1 Then
            If tarifa = 0 Then
                Call Calc_Convencional()
            ElseIf tarifa = 1 Then
                Call Calc_HoroSazonal()
            ElseIf tarifa = 2 Then
                Call Calc_AutoProdutor()
            End If
            System.Windows.Forms.Application.DoEvents()
        End If
        'strSigla = GetConfig("EMPRESA_SIGLA")
        Me.lblStatus.Text = "Gravando leituras..."
        modo = 0
        Call Grava_Leitura("leitura")
        modo = 1
        System.Windows.Forms.Application.DoEvents()



        Call PegaIndContinuidade(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, "A", Me.txtMesAno.Text, Item_Fatura)
        ' Carrega item de serviço
        strItensServ = ""
        ''For lngConta = 1 To grid_fatura.Rows - 1
        ''    grid_fatura.Row = lngConta
        ''    grid_fatura.Col = 0 'Codigo
        ''    strItensServ = Trim(strItensServ) & ''grid_fatura.Text
        ''    grid_fatura.Col = 3 'Valor
        ''    strItensServ = Trim(strItensServ) & "?" & Replace(Replace(''grid_fatura.Text, ".", ""), ",", ".")
        ''    grid_fatura.Col = 4 'Descrição dos itens faturados
        ''    strItensServ = Trim(strItensServ) & "$" & ''grid_fatura.Text & ";"
        ''Next lngConta

        strItensServ = Trim(strItensServ) '& Trim(Item_Fatura)

        Me.lblStatus.Text = "Gerando fatura... (Buscando sequencia de NF)"
        System.Windows.Forms.Application.DoEvents()
        If VerificaExisteArrecad(Id_Unid) Then
            Call MsgBox("Já possue fatura em arrecadação para o mês " & Me.txtMesAno.Text & ".", MsgBoxStyle.Information)
            GoTo pulaProcesso
        End If
        strsql = "SELECT * " & "  FROM nftransicao " & " WHERE cons_id=" & Id_Consumidor & "   AND unid_id=" & Id_Unid & "   AND mesano='" & Me.txtMesAno.Text & "'"


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

        If dt.Rows.Count < 1 Then

            dblNumNf = Int(CDbl(GetConfig("ULTIMONRFISCAL"))) + 1
            If GetConfig("EMPRESA_UF") = "SC" Then
                dblNsuNr = CDbl(GetConfig("ULTIMONRNSU")) + 1
            End If
            strsql = "SELECT * " & "  FROM uc_faturamento a, leitura l " & " WHERE a.cons_id =" & Id_Consumidor & "   AND a.cons_id = l.id_consumidor " & "   AND a.unid_id = " & Id_Unid & "   AND a.unid_id = l.id_unid " & "   AND l.dt_leit_atual = '" & Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & "' "


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

            If dt1.Rows.Count <> 0 Then

                For Each row1 As DataRow In dt1.Rows
                    Me.lblStatus.Text = "Gerando fatura..."
                    System.Windows.Forms.Application.DoEvents()
                    strBanco = IIf(IsDBNull(row1("banco")), "0", row1("banco"))
                    strNmBco = RetNmBanco(CInt(strBanco))


                    '''------- INCIO CODIGO HASH -----------------
                    ''strCnpj = PreparaCampo(IIf(IsDBNull(row1("cpf_cnpj")), "0", row1("cpf_cnpj")), NUMERICO, 14, "0")
                    ''strNumNf = PreparaCampo(Str(dblNumNf), NUMERICO, 9, "0")
                    ''strVlrTotal = PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(CDbl(Me.lblTotal.Text), 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                    ''strBaseICMS = PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(BaseICMS, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                    ''strVlrICMS = PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(ICMS, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                    ''strAuxHash = strCnpj & strNumNf & strVlrTotal & strBaseICMS & strVlrICMS
                    ''strsql = "SELECT CONVERT(MD5('" & strAuxHash & "') USING latin1) as `hash`"
                    ''Call Conectar(strsql, rsHash)
                    ''If rsHash.RecordCount > 0 Then
                    ''    strCodHash = IIf(IsDBNull(rsHash.Fields("hash")), "", rsHash.Fields("hash"))
                    ''Else
                    ''    strCodHash = ""
                    ''End If

                    '''------- FIM CODIGO HASH -------------------
                    '' Call MontaCodBarras(dblNumNf, Me.txtMesAno.Text, CDbl(Replace(lblTotal.Text, ".", "")), row1("zona"), rsConsulta.Fields("livro"), rsConsulta.Fields("conta"), strCodBarra, strDvCBarra)


                    lngDias = DateDiff(Microsoft.VisualBasic.DateInterval.Day, CDate(row1("dt_leit_anterior")), CDate(Me.txtDt_Leit_Atual.Text))
                    strsql = "INSERT INTO nftransicao (numnf, codclas, mesano, mesano_ref, codhash, datavenc, dataapr, "
                    strsql = strsql & "dataleit, dataem, dataleitant, datapag, flgst, valortot,"
                    strsql = strsql & "zona, livro, conta, rota, cons_id, unid_id, dataproxleit, cfop, "
                    strsql = strsql & "itensserv, ta, grupo, dias, fase, tensao, banarrec, banco_fatur, banident,valorliq"
                    If gstrEmpresa_Sigla = "COORSEL" Then
                        strsql = strsql & ",codbarra,dvcodbarra,nsu) VALUES ("
                    Else
                        strsql = strsql & ",nsu) VALUES ("
                    End If
                    strsql = strsql & dblNumNf & ","""
                    strsql = strsql & Format(row1("clas"), "0000") & ""","""
                    strsql = strsql & Me.txtMesAno.Text & ""","
                    strsql = strsql & CInt(VB.Right(Me.txtMesAno.Text, 4) & VB.Left(Me.txtMesAno.Text, 2)) & ","""
                    strsql = strsql & UCase(strCodHash) & ""","""
                    strsql = strsql & Format(Me.txtDt_Vencto.Text, "yyyy-MM-dd") & ""","""
                    strsql = strsql & Format(Me.txtDt_Apresenta.Text, "yyyy-MM-dd") & ""","""
                    strsql = strsql & Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & ""","""
                    strsql = strsql & Format(BuscaDataBD, "yyyy-MM-dd") & """,""" ' Data de Emissão
                    strsql = strsql & Format(row1("dt_leit_anterior"), "yyyy-MM-dd") & ""","""
                    strsql = strsql & "0000-00-00"","""
                    strsql = strsql & ""","""
                    strsql = strsql & Replace(Replace(lblTotal.Text, ".", ""), ",", ".") & ""","""
                    strsql = strsql & row1("zona") & ""","""
                    strsql = strsql & row1("livro") & ""","""
                    strsql = strsql & row1("conta") & ""","""
                    strsql = strsql & row1("rota") & ""","
                    strsql = strsql & Id_Consumidor & ","
                    strsql = strsql & Id_Unid & ","""
                    strsql = strsql & Format(row1("dt_prox_leit"), "yyyy-MM-dd") & ""","""
                    strsql = strsql & VB.Left(Replace(IIf(IsDBNull(row1("cfop")), "5.257", row1("cfop")), ",", "."), 5) & ""","""
                    strsql = strsql & strItensServ & Item_Fatura & """,""" 'Item de serviço
                    strsql = strsql & row1("ta") & ""","""
                    strsql = strsql & Mid(row1("ta"), 3, 1) & ""","""
                    strsql = strsql & lngDias & ""","""
                    strsql = strsql & row1("fase") & ""","""
                    strsql = strsql & row1("tensao") & ""","
                    strsql = strsql & strBanco & ","""
                    strsql = strsql & Format(strBanco, "000") & ""","""
                    strsql = strsql & strNmBco & ""","""
                    strsql = strsql & Replace(Replace(lblTotalLiq.Text, ".", ""), ",", ".") & ""","
                    strsql = strsql & """" & strCodBarra & """,""" & strDvCBarra & ""","
                    strsql = strsql & IIf(dblNsuNr < 1, "NULL", """" & dblNsuNr & """") & ")"

                    objAtualizaBancoDados.QUERY_NAME = strsql
                    repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

                    Call SetConfig("ULTIMONRFISCAL", "String", Trim(Str(dblNumNf)))
                    If GetConfig("EMPRESA_UF") = "SC" Then
                        Call SetConfig("ULTIMONRNSU", "String", Trim(Str(dblNsuNr)))
                    End If
                Next
            Else
                Me.lblStatus.Text = "Sem leitura..."
            End If

        Else

            For Each row As DataRow In dt.Rows
                'Deverá pegar o numero da nftrasicao ja gravada e atualizar
                dblNumNf = row("numNf")
                dblNsuNr = IIf(IsDBNull(row("nsu")), 0, row("nsu"))

                If GetConfig("EMPRESA_UF") = "SC" And dblNsuNr < 1 Then
                    dblNsuNr = CDbl(GetConfig("ULTIMONRNSU")) + 1
                End If

                strsql = "SELECT * " & "  FROM uc_faturamento a, leitura l " & " WHERE a.cons_id = " & Id_Consumidor & "   AND a.cons_id=l.id_consumidor " & "   AND a.unid_id = " & Id_Unid & "   AND a.unid_id = l.id_unid " & "   AND l.dt_leit_atual = """ & Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & """ "

                objAtualizaBancoDados.QUERY_NAME = strsql
                dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                If dt.Rows.Count <> 0 Then

                    For Each row2 As DataRow In dt2.Rows
                        Me.lblStatus.Text = "Gerando fatura..."
                        System.Windows.Forms.Application.DoEvents()
                        strBanco = CStr(Val(IIf(IsDBNull(row2("banco")), "0", row2("banco"))))
                        strNmBco = RetNmBanco(CInt(strBanco))
                        '''------- INCIO CODIGO HASH -----------------
                        ''strCnpj = PreparaCampo(IIf(IsDBNull(row2("cpf_cnpj")), "0", row2("cpf_cnpj")), NUMERICO, 14, "0")
                        ''strNumNf = PreparaCampo(Str(dblNumNf), NUMERICO, 9, "0")
                        ''strVlrTotal = PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(CDbl(Me.lblTotal.Text), 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                        ''strBaseICMS = PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(BaseICMS, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                        ''strVlrICMS = PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(ICMS, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
                        ''strAuxHash = strCnpj & strNumNf & strVlrTotal & strBaseICMS & strVlrICMS
                        ''strsql = "SELECT CONVERT(MD5('" & strAuxHash & "') USING latin1) as `hash`"
                        ''Call Conectar(strsql, rsHash)
                        ''If rsHash.RecordCount > 0 Then
                        ''    strCodHash = IIf(IsDBNull(rsHash.Fields("hash")), "", rsHash.Fields("hash"))
                        ''Else
                        ''    strCodHash = ""
                        ''End If
                        ''If rsHash.State = 1 Then Call rsHash.Close()
                        '''------- FIM CODIGO HASH -------------------
                        Call MontaCodBarras(dblNumNf, Me.txtMesAno.Text, CDbl(Replace(lblTotal.Text, ".", "")), row2("zona"), row2("livro"), row2("conta"), strCodBarra, strDvCBarra)

                        lngDias = DateDiff(Microsoft.VisualBasic.DateInterval.Day, CDate(row2("dt_leit_anterior")), CDate(Me.txtDt_Leit_Atual.Text))
                        strsql = "UPDATE nftransicao SET "
                        strsql = strsql & "codclas      = """ & row2("clas") & """, "
                        strsql = strsql & "datavenc     = """ & Format(Me.txtDt_Vencto.Text, "yyyy-MM-dd") & """, "
                        strsql = strsql & "dataapr      = """ & Format(Me.txtDt_Apresenta.Text, "yyyy-MM-dd") & """, "
                        strsql = strsql & "dataleit     = """ & Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & """, "
                        strsql = strsql & "dataem       = """ & Format(BuscaDataBD, "yyyy-MM-dd") & """, " ' Data de Emissão
                        strsql = strsql & "dataleitant  = """ & Format(row2("dt_leit_anterior"), "yyyy-MM-dd") & """, "
                        strsql = strsql & "datapag      = ""0000-00-00"", "
                        strsql = strsql & "flgst        = """", "
                        strsql = strsql & "valortot     = """ & Replace(Replace(Me.lblTotal.Text, ".", ""), ",", ".") & """, "
                        strsql = strsql & "valorliq     = """ & Replace(Replace(Me.lblTotalLiq.Text, ".", ""), ",", ".") & """, "
                        strsql = strsql & "nsu          = " & IIf(dblNsuNr < 1, "NULL", """" & dblNsuNr & """") & ", "
                        strsql = strsql & "zona         = """ & row2("zona") & """, "
                        strsql = strsql & "livro        = """ & row2("livro") & """, "
                        strsql = strsql & "conta        = """ & row2("conta") & """, "
                        strsql = strsql & "rota         = """ & row2("rota") & """, "
                        strsql = strsql & "dataproxleit = """ & Format(row2("dt_prox_leit"), "yyyy-MM-dd") & """, "
                        strsql = strsql & "cfop         = """ & VB.Left(Replace(IIf(IsDBNull(row2("cfop")), "5.257", row2("cfop")), ",", "."), 5) & """, "
                        strsql = strsql & "itensserv    = """ & strItensServ & Item_Fatura & """, " 'Item de serviço
                        strsql = strsql & "ta           = """ & row2("ta") & """, "
                        strsql = strsql & "grupo        = """ & Mid(row2("ta"), 3, 1) & """, "
                        strsql = strsql & "fase         = """ & row2("fase") & """, "
                        strsql = strsql & "tensao       = """ & row2("tensao") & """, "
                        strsql = strsql & "dias         = """ & lngDias & """, "
                        strsql = strsql & "codhash      = """ & UCase(strCodHash) & """, "
                        strsql = strsql & "banarrec     = " & strBanco & ", "
                        strsql = strsql & "banident     = """ & strNmBco & """, "
                        strsql = strsql & "codbarra   = """ & strCodBarra & """, "
                        strsql = strsql & "dvcodbarra   = """ & strDvCBarra & """, "
                        strsql = strsql & "banco_fatur  = """ & Format(strBanco, "000") & """ "
                        strsql = strsql & "WHERE cons_id = " & Id_Consumidor & " "
                        strsql = strsql & "AND unid_id   = " & Id_Unid & " "
                        strsql = strsql & "AND numnf     = " & dblNumNf & " "
                        strsql = strsql & "AND mesano    = """ & Me.txtMesAno.Text & """ "

                        objAtualizaBancoDados.QUERY_NAME = strsql
                        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

                    Next
                Else
                    Me.lblStatus.Text = "Sem leitura..."
                End If

            Next

        End If

        Call ComponentesFatura()

        'Deleta o itens da temp_item_fatura de acordo com o numero da nf e o mesano do faturamento
        strsql = "DELETE FROM temp_item_fatura " & "WHERE numnf = " & dblNumNf & " " & "AND mesano = '" & txtMesAno.Text & "'"
        objAtualizaBancoDados.QUERY_NAME = strsql
        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

        'Cria os itens da NFtransicao na temp_item_fatura de acordo com o numero da nftransicao e o mesano do faturamento
        strsql = "CALL criaitensfaturatrans(" & dblNumNf & ",'" & Me.txtMesAno.Text & "')"
        objAtualizaBancoDados.QUERY_NAME = strsql
        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

        Me.lblStatus.Text = "Gravação concluída!"
pulaProcesso:

    End Sub

    Private Sub ComponentesFatura()
        Dim strTarifa As String
        Dim strCodigo As String
        Dim strsql As String
        Dim strItens As String
        Dim strAux As String
        Dim strMesAnoAux As String
        Dim strMesAnoOld As String
        Dim dblPEnergia As Double 'percentual
        Dim dblPTransmissao As Double 'percentual
        Dim dblPDistribuicao As Double 'percentual
        Dim dblPEncSetoriais As Double 'percentual
        Dim dblVEnergia As Double 'valor
        Dim dblVTransmissao As Double 'valor
        Dim dblVDistribuicao As Double 'valor
        Dim dblVEncSetoriais As Double 'valor
        Dim dblValor As Double
        Dim dblAux As Double
        ''Dim rsFaturaC As ADODB.Recordset
        ''Dim rsComponente As ADODB.Recordset

        ''rsFaturaC = New ADODB.Recordset
        ''rsComponente = New ADODB.Recordset
        Dim dt As DataTable
        Dim dt2 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        strsql = "SELECT * FROM nftransicao WHERE cons_id = " & Id_Consumidor & " and unid_id = " & Id_Unid & " AND mesano='" & txtMesAno.Text & "'"

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

        dblVEnergia = 0
        dblVTransmissao = 0
        dblVDistribuicao = 0
        dblVEncSetoriais = 0

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows

                strTarifa = IIf(IsDBNull(row("ta")), "", row("ta"))
                strItens = IIf(IsDBNull(row("itensserv")), "", row("itensserv"))

                strsql = "SELECT * FROM composicao WHERE CONCAT(RIGHT(mesano,4),LEFT(mesano,2)) <= '" & VB.Right(txtMesAno.Text, 4) & VB.Left(Me.txtMesAno.Text, 2) & "' AND ta = '" & strTarifa & "' " & "ORDER BY RIGHT(mesano,4) DESC, LEFT(mesano,2) DESC, codigo ASC "


                objAtualizaBancoDados.QUERY_NAME = strsql
                dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                If dt2.Rows.Count <> 0 Then
                    strMesAnoAux = ""
                    strMesAnoOld = ""
                    For Each row2 As DataRow In dt2.Rows
                        strMesAnoAux = IIf(IsDBNull(row2("mesano")), "", row2("mesano"))
                        If Len(Trim(strMesAnoOld)) = 0 Then
                            strMesAnoOld = strMesAnoAux
                        End If
                        If strMesAnoAux = strMesAnoOld Then
                            strCodigo = IIf(IsDBNull(row2("codigo")), "", row2("codigo"))
                            dblPEnergia = IIf(IsDBNull(row2("energia")), 0, row2("energia"))
                            dblPTransmissao = IIf(IsDBNull(row2("transmissao")), 0, row2("transmissao"))
                            dblPDistribuicao = IIf(IsDBNull(row2("distribuicao")), 0, row2("distribuicao"))
                            dblPEncSetoriais = IIf(IsDBNull(row2("enc_setoriais")), 0, row2("enc_setoriais"))
                            dblValor = BuscaVlrItem(strItens, strCodigo)
                            If dblValor <> 0 Then
                                dblAux = dblValor * (dblPEnergia / 100)
                                dblVEnergia = dblVEnergia + dblAux
                                dblAux = dblValor * (dblPTransmissao / 100)
                                dblVTransmissao = dblVTransmissao + dblAux
                                dblAux = dblValor * (dblPDistribuicao / 100)
                                dblVDistribuicao = dblVDistribuicao + dblAux
                                dblAux = dblValor * (dblPEncSetoriais / 100)
                                dblVEncSetoriais = dblVEncSetoriais + dblAux
                            End If
                        End If

                    Next
                End If

            Next
        End If


        If dblVEnergia + dblVTransmissao + dblVDistribuicao + dblVEncSetoriais <> 0 Then
            strAux = "0302090001?" & Replace(CStr(Arredondar(dblVEnergia, 2)), ",", ".") & ";0302090002?" & Replace(CStr(Arredondar(dblVTransmissao, 2)), ",", ".") & ";0302090003?" & Replace(CStr(Arredondar(dblVDistribuicao, 2)), ",", ".") & ";0302090004?" & Replace(CStr(Arredondar(dblVEncSetoriais, 2)), ",", ".") & ";"
            strsql = "UPDATE nftransicao SET itensserv = CONCAT(itensserv,""" & strAux & """)" & " WHERE cons_id = " & Id_Consumidor & " and unid_id = " & Id_Unid & " AND mesano='" & txtMesAno.Text & "'"
            objAtualizaBancoDados.QUERY_NAME = strsql
            repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
        End If

    End Sub

    Private Sub Carr_Tarifa_AutoProdutor()
        Dim sql As String
        Dim data_aux As Date
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset
        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        sql = "select * from tarifa where substring(num,1,4)= '01AP' and not isnull(datanova) order by if(MID(datanova,7,2)<50,concat('20',mid(datanova,7,2)),concat('19',mid(datanova,7,2))) desc"


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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                'data_aux = CDate("01/" & Mid(txtMesAno.Text, 1, 3) & "20" & Mid(txtMesAno.Text, 4, 2))
                data_aux = CDate("01/" & txtMesAno.Text)
                If data_aux > CDate("01/" & Mid(Format(row("datanova"), "dd/mm/yyyy"), 4)) Then
                    Exit For
                End If
                '            If Not data_aux = lrstAux!datanova Then
                '                Exit Do
                '            End If
                If row("Num") = "01AP011101" Then 'Tarifa do consumo
                    tarAutoConsumo = Val(row("valor")) / 1000
                ElseIf row("Num") = "01AP011401" Then  'Tarifa demanda suplementar
                    tarAutoDemanda = Val(row("valor"))
                ElseIf row("Num") = "01AP012101" Then  'Tarifa Deficit Demanda
                    tarAutoDeficitDem = Val(row("valor"))
                ElseIf row("Num") = "01AP012102" Then  'Tarifa Deficit Demanda Horario Incentivado
                    tarAutoDeficitDemHI = Val(row("valor"))
                End If
            Next
        End If

    End Sub


    Private Sub Carr_Tarifa_Convencional()
        Dim sql As String
        Dim data_aux As Date
        Dim dt_tarifa As Date
        Dim teste As String
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        sql = "select * from tarifa where substring(num,1,4)= '01A4' and not isnull(datanova) order by datanova"
        'if(MID(datanova,7,2)<50,concat('20',mid(datanova,7,2)),concat('19',mid(datanova,7,2))) desc"

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                dt_tarifa = row("datanova")
                data_aux = CDate(txtDt_Leit_Atual.Text)

                If data_aux < CDate("01/" & Mid(Format(row("datanova"), "dd/mm/yyyy"), 4)) Then
                    Exit For
                End If
                If row("Num") = "01A4011101" Then
                    tarConsumo = Val(row("valor")) / 1000
                ElseIf row("Num") = "01A4011401" Then
                    tarExtra = Val(row("valor"))
                ElseIf row("Num") = "01A4012101" Then
                    tarDemanda = Val(row("valor"))
                ElseIf row("Num") = "01A4012102" Then
                    tarDemUltra = Val(row("valor"))
                End If
                dt_tarifa = row("datanova")

            Next
        End If

        'Proporcionalização
        If CDate(txtDt_Leit_Anterior.Text) < dt_tarifa Then
        End If

    End Sub

    Private Sub TarifaConvencional()
        Dim sql As String
        Dim dtTarifa As Date
        Dim dtLAnterior As Date
        Dim dtLAtual As Date
        Dim I As Short
        Dim vlrTarifa As Double
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        dtLAnterior = CDate(txtDt_Leit_Anterior.Text)
        dtLAtual = CDate(txtDt_Leit_Atual.Text)

        '************************************************************
        'consumo
        sql = "select * from tarifa where num='" & "01A4011101" & "' and not isnull(datanova) order by mid(datanova,7,4) asc"

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                ''For I = lrstAux.RecordCount To 1 Step -1
                vlrTarifa = row("valor")
                dtTarifa = row("datanova")

                'se a data da tarifa for menor que a anterior, fechou
                If dtTarifa <= dtLAnterior Then
                    tarConsumo = vlrTarifa / 1000
                    Exit For
                    'se a data da tarifa estiver entre as leituras anterior
                    'e atual, calcula proporcionalidade
                ElseIf dtTarifa >= dtLAnterior And dtTarifa <= dtLAtual Then
                    'calcula proporcionalidade
                    tarConsumo = TarifaProporcional(dtLAnterior, dtLAtual, "01A4011101", 3) / 1000
                    Exit For

                    'se a data da tarifa for maior que a data da leitura atual,
                    'é porque a tarifa a ser aplicada é mais velha que a atual
                    'e deve ser pesquisada pra trás
                    ''    Else
                    ''        lrstAux.MovePrevious()
                End If

                ''Next I
            Next
        Else
            tarConsumo = 0
        End If

        '************************************************************
        'demanda
        sql = "select * from tarifa where num='" & "01A4012101" & "' and not isnull(datanova) order by mid(datanova,7,4) asc"


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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                ''For I = lrstAux.RecordCount To 1 Step -1
                vlrTarifa = row("valor")
                dtTarifa = row("datanova")

                'se a data da tarifa for menor que a anterior, fechou
                If dtTarifa <= dtLAnterior Then
                    tarDemanda = vlrTarifa
                    Exit For
                    'se a data da tarifa estiver entre as leituras anterior
                    'e atual, calcula proporcionalidade
                ElseIf dtTarifa >= dtLAnterior And dtTarifa <= dtLAtual Then
                    'calcula proporcionalidade
                    tarDemanda = TarifaProporcional(dtLAnterior, dtLAtual, "01A4012101", 3)
                    Exit For
                    'se a data da tarifa for maior que a data da leitura atual,
                    'é porque a tarifa a ser aplicada é mais velha que a atual
                    'e deve ser pesquisada pra trás
                    ''Else
                    ''    lrstAux.MovePrevious()
                End If

                '' Next I
            Next
        Else
            tarDemanda = 0
        End If

        '************************************************************
        'demanda ultrapassagem
        sql = "select * from tarifa where num='" & "01A4012102" & "' and not isnull(datanova) order by mid(datanova,7,4) asc"


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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                ''For I = lrstAux.RecordCount To 1 Step -1
                vlrTarifa = row("valor")
                dtTarifa = row("datanova")

                'se a data da tarifa for menor que a anterior, fechou
                If dtTarifa <= dtLAnterior Then
                    tarDemUltra = vlrTarifa
                    Exit For
                    'se a data da tarifa estiver entre as leituras anterior
                    'e atual, calcula proporcionalidade
                ElseIf dtTarifa >= dtLAnterior And dtTarifa <= dtLAtual Then
                    'calcula proporcionalidade
                    tarDemUltra = TarifaProporcional(dtLAnterior, dtLAtual, "01A4012102", 3)
                    Exit For
                    'se a data da tarifa for maior que a data da leitura atual,
                    'é porque a tarifa a ser aplicada é mais velha que a atual
                    'e deve ser pesquisada pra trás
                    ''Else
                    ''    lrstAux.MovePrevious()
                End If
            Next
        Else
            tarDemUltra = 0
        End If

        If istrRes414_Art93 = "S" Then
            tarDemUltra = Arredondar(tarDemanda * 2, 5)
        End If

    End Sub

    Private Sub TarifaHorosazonal()
        '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

        ldteLeitAnt = CDate(Me.txtDt_Leit_Anterior.Text)
        ldteleitAtual = CDate(Me.txtDt_Leit_Atual.Text)
        lstrGrTar = VB.Left(Trim(Me.txtTA.Text), 4)

        lintMesLeitAtual = CShort(Mid(Me.txtDt_Leit_Atual.Text, 4, 2))

        lblnPeriodo = (lintMesLeitAtual >= iintMesIniPerSeco And lintMesLeitAtual <= iintMesFimPerSeco)

        '************************************************************
        '* Consumo na ponta                                         *
        '*               Período      Seco  ou  Úmido               *
        '************************************************************
        lstrCodigo = lstrGrTar & IIf(lblnPeriodo, "011101", "011105")
        tarConsumo_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
        Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(tarConsumo_p), ",", ".") & "$;")

        '************************************************************
        '* Consumo fora da ponta                                    *
        '*               Período      Seco  ou  Úmido               *
        '************************************************************
        lstrCodigo = lstrGrTar & IIf(lblnPeriodo, "011102", "011106")
        tarConsumo_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3) / 1000
        'Inclui nos itens da fatura a tarifa do consumo fora de ponta
        Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(tarConsumo_fp), ",", ".") & "$;")

        '************************************************************
        '* Demanda na ponta                                         *
        '************************************************************
        lstrCodigo = lstrGrTar & "012101"
        tarDemanda_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
        Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(tarDemanda_p), ",", ".") & "$;")

        '************************************************************
        '* Demanda fora da ponta                                    *
        '************************************************************
        lstrCodigo = lstrGrTar & "012102"
        tarDemanda_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
        Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(tarDemanda_fp), ",", ".") & "$;")

        '************************************************************
        '* Demanda de ultrapassagem na ponta                        *
        '************************************************************
        lstrCodigo = lstrGrTar & "012103"
        tarDemUltra_p = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
        '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
            tarDemUltra_p = Arredondar(tarDemanda_p * 2, 5)
        End If
        Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(tarDemUltra_p), ",", ".") & "$;")

        '************************************************************
        '* Demanda de ultrapassagem fora da ponta                   *
        '************************************************************
        lstrCodigo = lstrGrTar & "012104"
        tarDemUltra_fp = TarifaProporcional(ldteLeitAnt, ldteleitAtual, lstrCodigo, 3)
        If istrRes414_Art93 = "S" Then
            tarDemUltra_fp = Arredondar(tarDemanda_fp * 2, 5)
        End If
        Item_Fatura = Trim(Item_Fatura & lstrCodigo & "?" & Replace(CStr(tarDemUltra_fp), ",", ".") & "$;")

    End Sub

    Private Sub cmdGravarFatura_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGravarFatura.Click
        If GetConfig("MESANOFATURAMENTO") = Me.txtMesAno.Text Then
            Call Grava_Fatura()
        Else
            Call MsgBox("Você não pode efetuar a gravação em faturas com o mês já encerrado!", MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub Txt_Auto_Consumo_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Txt_Auto_Consumo.Enter
        Txt_Auto_Consumo.SelectionStart = 0
        Txt_Auto_Consumo.SelectionLength = Len(Txt_Auto_Consumo.Text)
    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
        Txt_Auto_Deficit_Dem.SelectionStart = 0
        Txt_Auto_Deficit_Dem.SelectionLength = Len(Txt_Auto_Deficit_Dem.Text)
    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
        Txt_Auto_Deficit_Dem_HI.SelectionStart = 0
        Txt_Auto_Deficit_Dem_HI.SelectionLength = Len(Txt_Auto_Deficit_Dem_HI.Text)
    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
        Txt_Auto_Dem_Supl.SelectionStart = 0
        Txt_Auto_Dem_Supl.SelectionLength = Len(Txt_Auto_Dem_Supl.Text)
    End Sub

    Private Sub txtAjusteDemandaFP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaFP.Enter
        txtAjusteDemandaFP.SelectionStart = 0
        txtAjusteDemandaFP.SelectionLength = Len(txtAjusteDemandaFP.Text)
    End Sub

    Private Sub txtajustedemandafp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaFP.Leave
        If Len(Trim(txtAjusteDemandaFP.Text)) <= 0 Then
            txtAjusteDemandaFP.Text = "0"
        End If
    End Sub

    Private Sub txtAjusteDemandaP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaP.Enter
        txtAjusteDemandaP.SelectionStart = 0
        txtAjusteDemandaP.SelectionLength = Len(txtAjusteDemandaP.Text)
    End Sub

    Private Sub txtajustedemandap_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAjusteDemandaP.Leave
        If Len(Trim(txtAjusteDemandaP.Text)) <= 0 Then
            txtAjusteDemandaP.Text = "0"
        End If
    End Sub

    Private Sub txtConsumo_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_FP.Enter
        txtConsumo_FP.SelectionStart = 0
        txtConsumo_FP.SelectionLength = Len(txtConsumo_FP.Text)
    End Sub

    Private Sub txtConsumo_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_FP.Leave
        If Len(Trim(txtConsumo_FP.Text)) <= 0 Then
            txtConsumo_FP.Text = "0"
        End If
    End Sub

    Private Sub txtConsumo_p_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_p.Enter
        txtConsumo_p.SelectionStart = 0
        txtConsumo_p.SelectionLength = Len(txtConsumo_p.Text)
    End Sub

    Private Sub txtConsumo_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConsumo_p.Leave
        If Len(Trim(txtConsumo_p.Text)) <= 0 Then
            txtConsumo_p.Text = "0"
        End If
    End Sub

    Private Sub txtConta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Enter
        txtConta.SelectionStart = 0
        txtConta.SelectionLength = Len(txtConta.Text)
    End Sub

    Private Sub txtConta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Leave
        If Len(txtConta.Text) >= 1 Then
            If IsNumeric(txtConta.Text) Then
                txtConta.Text = Format(txtConta.Text, "000000")
            Else
                txtConta.Text = ""
                'txtConta.SetFocus
            End If
        End If
        Call Loca_Consumidor()
    End Sub

    Private Sub txtDem_Exc_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_FP.Enter
        txtDem_Exc_FP.SelectionStart = 0
        txtDem_Exc_FP.SelectionLength = Len(txtDem_Exc_FP.Text)
    End Sub

    Private Sub txtdem_exc_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_FP.Leave
        If Len(Trim(txtDem_Exc_FP.Text)) <= 0 Then
            txtDem_Exc_FP.Text = "0"
        End If
    End Sub

    Private Sub txtDem_Exc_Ponta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_Ponta.Enter
        txtDem_Exc_Ponta.SelectionStart = 0
        txtDem_Exc_Ponta.SelectionLength = Len(txtDem_Exc_Ponta.Text)
    End Sub

    Private Sub txtdem_exc_ponta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDem_Exc_Ponta.Leave
        If Len(Trim(txtDem_Exc_Ponta.Text)) <= 0 Then
            txtDem_Exc_Ponta.Text = "0"
        End If
    End Sub

    Private Sub txtDemanda_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_FP.Enter
        txtDemanda_FP.SelectionStart = 0
        txtDemanda_FP.SelectionLength = Len(txtDemanda_FP.Text)
    End Sub

    Private Sub txtDemanda_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_FP.Leave
        If Len(Trim(txtDemanda_FP.Text)) <= 0 Then
            txtDemanda_FP.Text = "0"
        End If
    End Sub

    Private Sub txtDemanda_p_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_p.Enter
        txtDemanda_p.SelectionStart = 0
        txtDemanda_p.SelectionLength = Len(txtDemanda_p.Text)
    End Sub

    Private Sub txtDemanda_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDemanda_p.Leave
        If Len(Trim(txtDemanda_p.Text)) <= 0 Then
            txtDemanda_p.Text = "0"
        End If
    End Sub

    Private Sub txtDt_Apresenta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Apresenta.Enter
        txtDt_Apresenta.SelectionStart = 0
        txtDt_Apresenta.SelectionLength = Len(txtDt_Apresenta.Text)
    End Sub

    Private Sub txtDt_Apresenta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Apresenta.Leave
        ''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

    End Sub

    Private Sub txtDt_Faturamento_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Faturamento.Enter
        txtDt_Faturamento.SelectionStart = 0
        txtDt_Faturamento.SelectionLength = Len(txtDt_Faturamento.Text)

        If Mid(txtTA.Text, 1, 4) = "01AV" Then '-- Verde
            SSTLeituras.TabPages.Item(0).Visible = False
            SSTLeituras.TabPages.Item(1).Visible = True
            SSTLeituras.TabPages.Item(2).Visible = True
            SSTLeituras.TabPages.Item(3).Visible = False
            txtDemanda_p.Enabled = False
            txtDem_Exc_Ponta.Enabled = False
            txtKvarh_FP.Enabled = True
            txtKvarh_P.Enabled = True
            txtReservado.Enabled = True
            tarifa = 1
        ElseIf Mid(txtTA.Text, 1, 4) = "01AA" Or Mid(txtTA.Text, 1, 4) = "01AL" Then  '-- Azul
            SSTLeituras.TabPages.Item(0).Visible = False
            SSTLeituras.TabPages.Item(1).Visible = True
            SSTLeituras.TabPages.Item(2).Visible = True
            SSTLeituras.TabPages.Item(3).Visible = False
            label(13).Text = "Consumo na Ponta:"
            txtDemanda_FP.Enabled = True
            txtDemanda_p.Enabled = True
            txtKvarh_FP.Enabled = True
            txtKvarh_P.Enabled = True
            txtReservado.Enabled = False
            txtDem_Exc_Ponta.Enabled = True
            tarifa = 2
        ElseIf Mid(txtTA.Text, 1, 4) = "01AP" Then  '-- Auto Produtor
            SSTLeituras.TabPages.Item(0).Visible = False
            SSTLeituras.TabPages.Item(1).Visible = False
            SSTLeituras.TabPages.Item(2).Visible = True
            SSTLeituras.TabPages.Item(3).Visible = True
            Txt_Auto_Consumo.Enabled = True
            Txt_Auto_Dem_Supl.Enabled = True
            Txt_Auto_Deficit_Dem.Enabled = True
            Txt_Auto_Deficit_Dem_HI.Enabled = True
            tarifa = 3
        ElseIf Mid(txtTA.Text, 1, 4) = "01A4" Then  '-- Convencional
            SSTLeituras.TabPages.Item(0).Visible = True
            SSTLeituras.TabPages.Item(1).Visible = False
            SSTLeituras.TabPages.Item(2).Visible = True
            SSTLeituras.TabPages.Item(3).Visible = False
            tarifa = 0
        Else
            Call MsgBox("Tarifa não identificada: " & txtTA.Text & ", verifique o Cadastro!", MsgBoxStyle.Critical, "Erro!")
        End If
    End Sub

    Private Sub Grava_Leitura(ByRef nmTabela As String)
        'O parametro define se vai gravar na tabela temporaria ou na oficial
        Dim sql As String
        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        If modo = 0 Then
            sql = "DELETE FROM " & Trim(nmTabela) & " WHERE id_consumidor = " & Id_Consumidor & " and id_unid = " & Id_Unid & " AND dt_faturamento = '" & Format(txtDt_Faturamento.Text, "yyyy-MM-dd") & "' and mesano = """ & txtMesAno.Text & """ "

            objAtualizaBancoDados.QUERY_NAME = sql
            repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

            sql = "INSERT INTO " & Trim(nmTabela) & " SET "
        Else
            sql = "UPDATE " & Trim(nmTabela) & " SET "
        End If

        sql = sql & "dt_leit_atual    = '" & IIf(Len(txtDt_Leit_Atual.Text) > 0, Format(txtDt_Leit_Atual.Text, "yyyy-MM-dd"), "") & "', "
        sql = sql & "dt_leit_anterior = '" & IIf(Len(txtDt_Leit_Anterior.Text) > 0, Format(txtDt_Leit_Anterior.Text, "yyyy-MM-dd"), "") & "', "
        sql = sql & "dt_faturamento   = '" & IIf(Len(txtDt_Faturamento.Text) > 0, Format(txtDt_Faturamento.Text, "yyyy-MM-dd"), "") & "', "
        sql = sql & "dt_vencto        = '" & IIf(Len(txtDt_Vencto.Text) > 0, Format(txtDt_Vencto.Text, "yyyy-MM-dd"), "") & "', "
        sql = sql & "dt_cadastro      = '" & Format(Today, "yyyy-MM-dd") & "', "
        sql = sql & "consumo_p        = '" & IIf(tarifa < 1, IIf(Len(txtLeit_Consumo.Text) > 0, Replace(txtLeit_Consumo.Text, ",", "."), "0"), IIf(Len(txtConsumo_p.Text) > 0, Replace(txtConsumo_p.Text, ",", "."), "0")) & "', "
        sql = sql & "consumo_fp       = '" & IIf(Len(txtConsumo_FP.Text) > 0, Replace(txtConsumo_FP.Text, ",", "."), "0") & "', "
        sql = sql & "demanda_p        = '" & IIf(tarifa < 1, IIf(Len(txtLeit_Demanda.Text) > 0, Replace(txtLeit_Demanda.Text, ",", "."), "0"), IIf(Len(txtDemanda_p.Text) > 0, Replace(txtDemanda_p.Text, ",", "."), "0")) & "', "
        sql = sql & "demanda_fp       = '" & IIf(Len(txtDemanda_FP.Text) > 0, Replace(txtDemanda_FP.Text, ",", "."), "0") & "', "
        sql = sql & "kvarh            = '" & IIf(tarifa < 1, IIf(Len(txtLeit_Kvarh.Text) > 0, Replace(txtLeit_Kvarh.Text, ",", "."), "0"), IIf(Len(txtKvarh_P.Text) > 0, Replace(txtKvarh_P.Text, ",", "."), "0")) & "', "
        sql = sql & "dt_apresenta     = '" & IIf(Len(txtDt_Apresenta.Text) > 0, Format(txtDt_Apresenta.Text, "yyyy-MM-dd"), "") & "', "
        sql = sql & "id_consumidor    = '" & Id_Consumidor & "', "
        sql = sql & "cons_reservado   = '" & IIf(Len(txtReservado.Text) > 0, Replace(txtReservado.Text, ",", "."), "0") & "', "
        sql = sql & "dt_prox_leit     = '" & IIf(Len(txtDt_Prox_Leit.Text) > 0, Format(txtDt_Prox_Leit.Text, "yyyy-MM-dd"), "") & "', "
        sql = sql & "mesano           = '" & txtMesAno.Text & "', "
        sql = sql & "dem_exc_ponta    = '" & IIf(Len(txtDem_Exc_Ponta.Text) > 0, Replace(txtDem_Exc_Ponta.Text, ",", "."), "0") & "', "
        sql = sql & "dem_exc_fp       = '" & IIf(Len(txtDem_Exc_Ponta.Text) > 0, Replace(txtDem_Exc_FP.Text, ",", "."), "0") & "', "
        sql = sql & "kwh_cap_reat_fp  = '" & IIf(Len(txtKwh_Cap_Reat_FP.Text) > 0, Replace(txtKwh_Cap_Reat_FP.Text, ",", "."), "0") & "', "
        sql = sql & "id_unid          = '" & Id_Unid & "', "
        sql = sql & "kvarh_fp         = '" & IIf(Len(txtKvarh_FP.Text) > 0, Replace(txtKvarh_FP.Text, ",", "."), "0") & "', "
        sql = sql & "zlc              = '" & zlc & "' "

        If modo <> 0 Then
            sql = sql & "WHERE id_consumidor = " & Id_Consumidor & " "
            sql = sql & "  AND id_unid = " & Id_Unid & " "
            sql = sql & "AND dt_faturamento  = '" & Format(txtDt_Faturamento.Text, "yyyy-MM-dd") & "' "
        End If


        objAtualizaBancoDados.QUERY_NAME = sql
        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

    End Sub

    Private Sub Enche_Grid()
        Dim lstrSql As String
        '' Dim lrstConsulta As ADODB.Recordset
        Dim lstrSituacao As String
        Dim lstrMesAno As String
        Dim lstrZLC As String
        Dim lstrNome As String
        Dim lstrLeitura As String
        Dim lstrFatura As String
        Dim lstrGrTar As String

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        Call Forma_Grid()
        lstrMesAno = Me.txtMesAno.Text
        lstrSql = "SELECT IF((SELECT COUNT(*) " & "             FROM leitura " & "            WHERE id_unid = u.unid_id " & "              AND id_consumidor = u.cons_id " & "              AND mesano = """ & lstrMesAno & """) > 0, 'SIM', 'NAO') leitura, " & "       IF((SELECT COUNT(*) " & "             FROM nftransicao " & "            WHERE cons_id = u.cons_id " & "              AND unid_id = u.unid_id " & "              AND mesano = """ & lstrMesAno & """) > 0,'SIM','NAO') fatura, " & "       CONCAT(u.zona, u.livro, u.conta) zlc, " & "       u.nome nome, " & "       MID(u.ta, 3, 2) tarifa, " & "       situacao " & "  FROM uc_faturamento u "
        If Me.opbLigados.Checked Then
            lstrSql = lstrSql & " WHERE UPPER(u.situacao) = 'L' "
        ElseIf Me.opbDesligados.Checked Then
            lstrSql = lstrSql & " WHERE UPPER(u.situacao) <> 'L' "
        End If
        If optZLC.Checked = True Then
            lstrSql = lstrSql & "ORDER BY CONCAT(u.zona, u.livro, u.conta), u.nome, MID(u.ta, 3, 2) "
        ElseIf optNome.Checked = True Then
            lstrSql = lstrSql & "ORDER BY u.nome, CONCAT(u.zona, u.livro, u.conta), MID(u.ta, 3, 2) "
        ElseIf optTarifa.Checked Then
            lstrSql = lstrSql & "ORDER BY MID(u.ta, 3, 2), CONCAT(u.zona, u.livro, u.conta), u.nome "
        End If

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows

                lstrZLC = IIf(IsDBNull(row("zlc")), "", row("zlc"))
                lstrZLC = Mid(lstrZLC, 1, 3) & "." & Mid(lstrZLC, 4, 2) & "." & Mid(lstrZLC, 6)
                lstrNome = IIf(IsDBNull(row("nome")), "", row("nome"))
                lstrLeitura = IIf(IsDBNull(row("leitura")), "", row("leitura"))
                lstrFatura = IIf(IsDBNull(row("fatura")), "", row("fatura"))
                lstrGrTar = IIf(IsDBNull(row("tarifa")), "", row("tarifa"))
                lstrSituacao = UCase(IIf(IsDBNull(row("situacao")), "L", row("situacao")))

                ''With Me.mhgDados
                ''    .set_TextMatrix(.Rows - 1, 0, lstrZLC)
                ''    .set_TextMatrix(.Rows - 1, 1, lstrNome)
                ''    .set_TextMatrix(.Rows - 1, 2, lstrLeitura)
                ''    .set_TextMatrix(.Rows - 1, 3, lstrFatura)
                ''    .set_TextMatrix(.Rows - 1, 4, lstrGrTar)
                ''    .set_TextMatrix(.Rows - 1, 5, lstrSituacao)
                ''    'UPGRADE_ISSUE: VBControlExtender method mhgDados.FillStyle was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
                ''    .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillRepeat
                ''    If lstrSituacao <> "L" Then
                ''        .Row = .Rows - 1
                ''        .Col = 0
                ''        .ColSel = .get_Cols() - 1
                ''        .CellForeColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                ''    Else
                ''        .Row = .Rows - 1
                ''        .Col = 0
                ''        .ColSel = .get_Cols() - 1
                ''        .CellForeColor = System.Drawing.ColorTranslator.FromOle(&H80000008)
                ''    End If
                ''    'UPGRADE_ISSUE: VBControlExtender method mhgDados.FillStyle was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
                ''    .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillSingle
                ''    .Rows = .Rows + 1
                ''End With

            Next
        End If
        System.Windows.Forms.Application.DoEvents()
    End Sub

    Private Sub txtDt_Faturamento_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Faturamento.Leave
        '' txtDt_Faturamento.Text = FormataData(txtDt_Faturamento, 2)
    End Sub

    Private Sub txtDt_Leit_Anterior_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Anterior.Enter
        txtDt_Leit_Anterior.SelectionStart = 0
        txtDt_Leit_Anterior.SelectionLength = Len(txtDt_Leit_Anterior.Text)
    End Sub

    Private Sub txtDt_Leit_Anterior_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Anterior.Leave
        ''  txtDt_Leit_Anterior.Text = FormataData(txtDt_Leit_Anterior, 2)
    End Sub

    Private Sub txtDt_Leit_Atual_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Atual.Enter
        txtDt_Leit_Atual.SelectionStart = 0
        txtDt_Leit_Atual.SelectionLength = Len(txtDt_Leit_Atual.Text)
    End Sub

    Private Sub txtDt_Leit_Atual_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Leit_Atual.Leave
        ''txtDt_Leit_Atual.Text = FormataData(txtDt_Leit_Atual, 2)
    End Sub

    Private Sub txtDt_Prox_Leit_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Prox_Leit.Enter
        txtDt_Prox_Leit.SelectionStart = 0
        txtDt_Prox_Leit.SelectionLength = Len(txtDt_Prox_Leit.Text)

        If Len(Trim(txtDt_Apresenta.Text)) = 0 Then
            MsgBox("É necessário informar uma Data de Apresentação!", MsgBoxStyle.Critical, "Erro!")
            txtDt_Apresenta.Focus()
            System.Windows.Forms.Application.DoEvents()
            Exit Sub
        End If
        If Len(Trim(txtDt_Vencto.Text)) = 0 Then
            MsgBox("É necessário informar uma Data de Vencimento!", MsgBoxStyle.Critical, "Erro!")
            txtDt_Vencto.Focus()
            System.Windows.Forms.Application.DoEvents()
            Exit Sub
        End If
        If Mid(classe, 1, 2) = "62" Or Mid(classe, 1, 2) = "63" Or Mid(classe, 1, 2) = "64" Then
            If System.DateTime.FromOADate(CDate(txtDt_Vencto.Text).ToOADate - CDate(txtDt_Apresenta.Text).ToOADate) < System.DateTime.FromOADate(10) Then
                MsgBox("Atenção! Data de vencimento inferior a dez dias da apresentação!", MsgBoxStyle.Critical, "Data de Vencimento")
            End If
        Else
            If System.DateTime.FromOADate(CDate(txtDt_Vencto.Text).ToOADate - CDate(txtDt_Apresenta.Text).ToOADate) < System.DateTime.FromOADate(5) Then
                MsgBox("Atenção! Data de vencimento inferior a cinco dias da apresentação!", MsgBoxStyle.Critical, "Data de Vencimento")
            End If
        End If
    End Sub

    Private Sub txtDt_Prox_Leit_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Prox_Leit.Leave
        '' txtDt_Prox_Leit.Text = FormataData(txtDt_Prox_Leit, 2)
    End Sub

    Private Sub txtDt_Vencto_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Vencto.Enter
        txtDt_Vencto.SelectionStart = 0
        txtDt_Vencto.SelectionLength = Len(txtDt_Vencto.Text)

        If Len(Trim(txtDt_Leit_Atual.Text)) = 0 Then
            MsgBox("É necessário informar a Data de Leitura Atual!", MsgBoxStyle.Critical, "Erro!")
            txtDt_Leit_Atual.Focus()
            System.Windows.Forms.Application.DoEvents()
            Exit Sub
        End If
        If Len(Trim(txtDt_Leit_Anterior.Text)) = 0 Then
            MsgBox("É necessário informar a Data de Leitura Anterior!", MsgBoxStyle.Critical, "Erro!")
            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
            MsgBox("Atenção! Período de leitura superior a 33 dias!", MsgBoxStyle.Critical, "Datas de Leitura")
        ElseIf System.DateTime.FromOADate(CDate(txtDt_Leit_Atual.Text).ToOADate - CDate(txtDt_Leit_Anterior.Text).ToOADate) < System.DateTime.FromOADate(27) Then
            MsgBox("Atenção! Período de leitura inferior a 27 dias!", MsgBoxStyle.Critical, "Datas de Leitura")
        End If
    End Sub

    Private Sub txtDt_Vencto_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDt_Vencto.Leave
        '' txtDt_Vencto.Text = FormataData(txtDt_Vencto, 2)
    End Sub

    Private Sub txtId_Consumidor_GotFocus()
        If Len(txtMesAno.Text) = 0 Then
            MsgBox("É necessário informar o mês e ano de processamento!")
            txtMesAno.Focus()
            System.Windows.Forms.Application.DoEvents()
            Exit Sub
        End If
    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 lrstConsulta As ADODB.Recordset

        Dim llngMesano As Integer
        Dim ldblDemandaP(3) As Double
        Dim ldblDemandaFP(3) As Double
        Dim ldblAuxiliar As Double
        Dim llngConta As Integer

        'lrstConsulta = New ADODB.Recordset

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        llngMesano = CInt(VB.Right(Me.txtMesAno.Text, 4) & VB.Left(Me.txtMesAno.Text, 2))

        lstrSql = "SELECT * " & "  FROM leitura " & " WHERE id_consumidor = " & Id_Consumidor & " " & "   AND id_unid = " & Id_Unid & " " & "   AND CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) < " & llngMesano & " ORDER BY CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) 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_consumo_reservado = IIf(IsDBNull(row("cons_reservado")), 0, row("cons_reservado"))
                Me.lblStatus.Text = "Última leitura encontrada " & row("mesano")
                Me.lblStatus.Refresh()
            Next
        Else
            ''If .State = 1 Then Call .Close()
            lstrSql = "SELECT cap, leitant " & "  FROM uc_faturamento " & " WHERE cons_id = " & Id_Consumidor & " " & "   AND unid_id = " & Id_Unid & " "

            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("cap")), 0, row("cap"))
                    ant_consumo_fp = IIf(IsDBNull(row("leitant")), 0, row("leitant"))
                    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_consumo_reservado = 0
                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 tarifa > 0 Then
                lstrSql = "SELECT buscavlritem(itensserv,""0302010019"")+0 kwp, " & "       buscavlritem(itensserv,""0302010023"")+0 kwfp " & "  FROM nf USE INDEX (keycons, keyunid) " & " WHERE cons_id = " & Id_Consumidor & "   AND unid_id = " & Id_Unid & "   AND CONCAT(RIGHT(mesano, 4), LEFT(mesano, 2)) <= " & llngMesano & "   AND (dataleit <= """ & Format(Me.txtDt_Leit_Atual.Text, "yyyy-MM-dd") & """ AND " & "        dataleit >= """ & Format(adteContratoDemanda, "yyyy-MM-dd") & """) " & " 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
    End Sub

    Private Function Busca_Aliquota_ICMS(ByRef strUF As String, ByRef adlbConsumo As Double, ByRef strClasse As String) As Double
        Dim strsql As String
        '' Dim rsICMS As New ADODB.Recordset
        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        strsql = "  SELECT * FROM codigos " & "   WHERE CONCAT(MID(datanova,7,4),MID(datanova,4,2),MID(datanova,1,2)) <= " & Format(txtDt_Faturamento.Text, "yyyymmdd") & "     AND MID(num,1,5)='40" & strUF & "A'" & "ORDER BY CONCAT(MID(datanova,7,4),MID(datanova,4,2),MID(datanova,1,2)) DESC, num ASC"

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                'Rural Classe 5 Codigo A00001
                If row("Num") = "40" & strUF & "A00001" Then
                    If Mid(Trim(strClasse), 1, 1) = "5" Then

                        If strUF = "RS" Then
                            Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                        Else
                            If adlbConsumo <= row("limitkwh") Then
                                Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                            End If
                        End If
                    End If

                    'Rural Classe 5 Codigo A00009 Com Inscrição Estadual
                ElseIf row("Num") = "40" & strUF & "A00009" Then
                    If Mid(Trim(strClasse), 1, 1) = "5" Then
                        If Len(Trim(InscEst)) > 0 Then
                            Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                        End If
                    End If
                    'Rural Classe 5 Codigo A00010 Sem Inscrição Estadual
                ElseIf row("Num") = "40" & strUF & "A00010" Then
                    If Mid(Trim(strClasse), 1, 1) = "5" Then
                        If Len(Trim(InscEst)) < 1 Then
                            Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                        End If
                    End If
                    'Industrial e outros
                ElseIf row("Num") = "40" & strUF & "A00002" Then
                    If Val(Mid(Trim(strClasse), 1, 1)) < 4 Or Mid(Trim(strClasse), 1, 1) = "8" Or Mid(Trim(strClasse), 1, 1) = "7" Then
                        Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                    End If
                    'Comercial Classe 4, P.P.M Classe 61, P.P.F Classe 63 Codigo A00003
                ElseIf row("Num") = "40" & strUF & "A00003" Then
                    If (Mid(Trim(strClasse), 1, 1) = "4" Or Mid(Trim(strClasse), 1, 2) = "61" Or Mid(Trim(strClasse), 1, 2) = "63") Then
                        Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                    End If
                    'Poder Publico Estadual Classe 62 Codigo A00004 - Isento
                ElseIf row("Num") = "40" & strUF & "A00004" Then
                    If Mid(Trim(strClasse), 1, 2) = "62" Then
                        Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                    End If
                    'Iluminação Publica Classe 64 Codigo A00007
                ElseIf row("Num") = "40" & strUF & "A00007" Then
                    If Mid(Trim(strClasse), 1, 2) = "64" Then
                        Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                    End If
                    'Para Resindencial e Baixa Renda
                ElseIf (row("Num") = "40" & strUF & "A00005") Or (row("Num") = "40" & strUF & "A00006") Or (row("Num") = "40" & strUF & "A00008") Then
                    If Mid(Trim(strClasse), 1, 1) = "9" Then
                        If adlbConsumo <= row("limitkwh") Then
                            Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                        End If
                    End If
                    'SERVICO PUBLICO
                ElseIf row("Num") = "40" & strUF & "A00011" Then
                    If Mid(Trim(strClasse), 1, 1) = "7" Then
                        Busca_Aliquota_ICMS = Val(Replace(IIf(IsDBNull(row("valor")), 0, row("valor")), ",", "."))
                    End If
                End If
            Next
        End If

    End Function

    Private Function Busca_Aliquota_PIS() As Double
        Dim sql As String
        Dim dataaux As Date
        Dim aliq As Double
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset
        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        sql = "SELECT * FROM codigos WHERE MID(NUM,1,5)='40PIS' " & "ORDER BY datanova DESC, num ASC"

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

        If dt.Rows.Count <> 0 Then
            dataaux = CDate("01/" & txtMesAno.Text)
            For Each row As DataRow In dt.Rows
                aliq = Val(row("valor"))
                If dataaux >= CDate("01/" & Format(row("datanova"), "mm/yyyy")) Then
                    Exit For
                End If
            Next
        Else
            aliq = 0
        End If

        Busca_Aliquota_PIS = aliq
    End Function

    Private Function Busca_Aliquota_COFINS() As Double
        Dim sql As String
        Dim dataaux As Date
        Dim aliq As Double
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset
        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        sql = "SELECT * FROM codigos WHERE MID(NUM,1,5)='40COF' " & "ORDER BY datanova DESC, num ASC"

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

        If dt.Rows.Count <> 0 Then
            dataaux = CDate("01/" & txtMesAno.Text)
            For Each row As DataRow In dt.Rows
                aliq = Val(row("valor"))
                If dataaux >= CDate("01/" & Format(row("datanova"), "mm/yyyy")) Then
                    Exit For
                End If
            Next
        Else
            aliq = 0
        End If

        Busca_Aliquota_COFINS = aliq
    End Function
    'Private Function Busca_Aliquota_COFINS() As Double
    '    Dim sql As String
    '    Dim dataaux As Date
    '    Dim aliq As Double
    '    Dim lrstAux As ADODB.Recordset
    '    Set lrstAux = New ADODB.Recordset
    '    sql = "SELECT * FROM codigos WHERE MID(NUM,1,5)='40COF' " _
    ''    & "ORDER BY CONCAT(MID(datanova,7,4),MID(datanova,4,2),MID(datanova,1,2)) DESC, num ASC"
    '    Call conectar(sql, lrstAux)
    '    If lrstAux.RecordCount > 0 Then
    '        lrstAux.MoveFirst
    '        dataaux = CDate("01/" & txtMesAno.Text)
    '        Do While Not lrstAux.EOF
    '            aliq = Val(lrstAux!valor)
    '            If dataaux >= CDate("01/" & Format(lrstAux!datanova, "mm/yyyy")) Then
    '                Exit Do
    '            End If
    '            lrstAux.MoveNext
    '        Loop
    '    Else
    '        aliq = 0
    '    End If
    '    lrstAux.Close
    '    Busca_Aliquota_COFINS = aliq
    'End Function

    Private Function Ajuste_Demanda_Art49_456(ByRef AjusteDemanda_p As Double, Optional ByRef AjusteDemanda_FP As Double = 0) As Double
        '-- Analisa os 11 ultimos meses, dos Rurais e Sazonais
        '-- cobrando o ajuste de quem não chegou ao contrato de demanda
        '-- em pelo menos três meses de faturamento
        Dim sql As String
        Dim I As Integer
        Dim Data_Contrato As Date
        Dim dataaux As Date
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        dataaux = CDate("01/" & txtMesAno.Text)
        I = 0
        ' sql = "SELECT * FROM uc_faturamento WHERE cons_id = " & Id_Consumidor & " AND unid_id = " & Id_Unid

        Data_Contrato = GetValorTabela("uc_faturamento", "data_contrato_demanda", "cons_id = " & Id_Consumidor & " AND unid_id = " & Id_Unid)

        If Not Int((System.DateTime.FromOADate(CDate(Data_Contrato).ToOADate - dataaux.ToOADate).ToOADate * 12) / 360) = 11 Then
            Exit Function
        End If

        sql = "SELECT * FROM NF WHERE CONS_ID=" & Id_Consumidor & " ORDER BY MESANO DESC"

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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                I = I + 1
                If I > 11 Then
                    Exit For
                End If
            Next
        End If
    End Function

    Private Function Aplica_Pis(ByRef base As Double, ByRef aliqICMS As Double, ByRef tarifa As Double, ByRef casas As Short) As Double
        Dim localBase As Double
        Dim sql As String
        Dim Pis As Double
        Dim basePisCofins As Double

        localBase = base
        '   BasePisCofins = arredondar(tarifa / (1 - (((AliqPIS + AliqCofins) / 100) + (AliqICMS / 100))), casas)
        basePisCofins = Arredondar(tarifa / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)
        basePisCofins = localBase * basePisCofins
        localBase = (basePisCofins * (AliqPIS / 100))
        Aplica_Pis = localBase

    End Function

    Private Function Aplica_Pis2(ByRef base As Double, ByRef aliqICMS As Double, ByRef tarifa As Double, ByRef casas As Short) As Double
        Dim localBase As Double
        Dim sql As String
        Dim Pis As Double
        Dim basePisCofins As Double
        Dim aux As Double

        localBase = base
        basePisCofins = Truncate(tarifa / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)
        localBase = Arredondar(localBase * basePisCofins, 2)
        localBase = Arredondar(localBase / (1 - (aliqICMS / 100)), 2)
        localBase = localBase * (AliqPIS / 100)
        Aplica_Pis2 = Truncate(localBase, 2)
    End Function

    Private Function Aplica_Cofins(ByRef base As Double, ByRef aliqICMS As Double, ByRef tarifa As Double, ByRef casas As Short) As Double
        Dim localBase As Double
        Dim sql As String
        Dim cofins As Double
        Dim basePisCofins As Double
        Dim aux As Double

        localBase = base
        basePisCofins = Truncate(tarifa / (1 - (((AliqPIS + AliqCofins) / 100)) / (1 - (aliqICMS / 100))), casas)
        localBase = Arredondar(localBase * basePisCofins, 2)
        localBase = Arredondar(localBase / (1 - (aliqICMS / 100)), 2)
        localBase = Truncate(localBase * (AliqCofins / 100), 2)
        Aplica_Cofins = localBase

    End Function

    Private Function Aplica_Cofins2(ByRef base As Double, ByRef aliqICMS As Double, ByRef casas As Short) As Double
        Dim localBase As Double
        Dim sql As String
        Dim cofins As Double
        Dim basePisCofins As Double

        localBase = base
        basePisCofins = Arredondar(localBase / (1 - (((AliqPIS + AliqCofins) / 100) + (aliqICMS / 100))), casas)
        localBase = (basePisCofins * (AliqCofins / 100))
        Aplica_Cofins2 = localBase
    End Function

    Private Function RetIdBanco(ByRef astrBco As String) As Short
        '  Dim rsBanco As New ADODB.Recordset
        'Dim strsql As String

        ' strsql = "SELECT ban_id FROM bancos where nrbco = '" & astrBco & "'"

        If IsDBNull(GetValorTabela("bancos", "ban_id", "nrbco = '" & astrBco & "'")) Then
            RetIdBanco = 0
        Else
            RetIdBanco = GetValorTabela("bancos", "ban_id", "nrbco = '" & astrBco & "'")
        End If

    End Function

    Private Function RetNmBanco(ByRef alngBco As Integer) As String
        'Dim strsql As String
        'Dim rsBanco As New ADODB.Recordset

        'strsql = "SELECT * FROM bancos where ban_id = " & alngBco & " "

        If IsDBNull(GetValorTabela("bancos", "nmbco", "ban_id = '" & alngBco & "'")) Then
            RetNmBanco = ""
        Else
            RetNmBanco = GetValorTabela("bancos", "ban_id", "ban_id = '" & alngBco & "'")
        End If

    End Function

    Private Sub txtId_Consumidor_LostFocus()
        '  If Len(txtId_Consumidor.Text) = 0 Then
        '    MsgBox "É necessário informar uma identificação!"
        '    txtId_Consumidor.SetFocus
        '    DoEvents
        '    Exit Sub
        '  Else
        ' Call Loca_Consumidor
        'End If
    End Sub

    Private Sub txtKvarh_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_FP.Enter
        txtKvarh_FP.SelectionStart = 0
        txtKvarh_FP.SelectionLength = Len(txtKvarh_FP.Text)
    End Sub

    Private Sub txtkvarh_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_FP.Leave
        If Len(Trim(txtKvarh_FP.Text)) <= 0 Then
            txtKvarh_FP.Text = "0"
        End If
    End Sub

    Private Sub txtKvarh_P_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_P.Enter
        txtKvarh_P.SelectionStart = 0
        txtKvarh_P.SelectionLength = Len(txtKvarh_P.Text)
    End Sub

    Private Sub txtkvarh_p_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKvarh_P.Leave
        If Len(Trim(txtKvarh_P.Text)) <= 0 Then
            txtKvarh_P.Text = "0"
        End If
    End Sub

    Private Sub txtKwh_Cap_Reat_FP_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKwh_Cap_Reat_FP.Enter
        txtKwh_Cap_Reat_FP.SelectionStart = 0
        txtKwh_Cap_Reat_FP.SelectionLength = Len(txtKwh_Cap_Reat_FP.Text)
    End Sub

    Private Sub txtkwh_cap_reat_fp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtKwh_Cap_Reat_FP.Leave
        If Len(Trim(txtKwh_Cap_Reat_FP.Text)) <= 0 Then
            txtKwh_Cap_Reat_FP.Text = "0"
        End If
    End Sub

    Private Sub txtLeit_Consumo_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Consumo.Enter
        txtLeit_Consumo.SelectionStart = 0
        txtLeit_Consumo.SelectionLength = Len(txtLeit_Consumo.Text)
    End Sub

    Private Sub txtLeit_Demanda_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Demanda.Enter
        txtLeit_Demanda.SelectionStart = 0
        txtLeit_Demanda.SelectionLength = Len(txtLeit_Demanda.Text)
    End Sub

    Private Sub txtLeit_Kvarh_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLeit_Kvarh.Enter
        txtLeit_Kvarh.SelectionStart = 0
        txtLeit_Kvarh.SelectionLength = Len(txtLeit_Kvarh.Text)
    End Sub

    Private Sub txtLivro_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Enter
        txtLivro.SelectionStart = 0
        txtLivro.SelectionLength = Len(txtLivro.Text)
    End Sub

    Private Sub txtMesAno_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMesAno.Enter
        txtMesAno.SelectionStart = 0
        txtMesAno.SelectionLength = Len(txtMesAno.Text)
    End Sub

    Private Sub txtMesAno_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMesAno.Leave
        txtMesAno.Text = Format(txtMesAno.Text, "MM/yyyy")
    End Sub

    Private Sub txtReservado_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReservado.Enter
        txtReservado.SelectionStart = 0
        txtReservado.SelectionLength = Len(txtReservado.Text)
    End Sub

    Private Sub txtReservado_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtReservado.Leave
        If Len(Trim(txtReservado.Text)) <= 0 Then
            txtReservado.Text = "0"
        End If
    End Sub

    Private Sub txtZona_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Enter
        txtZona.SelectionStart = 0
        txtZona.SelectionLength = Len(txtZona.Text)
    End Sub

    Private Sub txtZona_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Leave
        If Len(txtZona.Text) >= 1 Then
            If IsNumeric(txtZona.Text) Then
                txtZona.Text = Format(txtZona.Text, "000")
            Else
                txtZona.Text = ""
                'txtZona.SetFocus
            End If
        End If
    End Sub

    Private Sub txtLivro_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Leave
        If Len(txtLivro.Text) >= 1 Then
            If IsNumeric(txtLivro.Text) Then
                txtLivro.Text = Format(txtLivro.Text, "00")
            Else
                txtLivro.Text = ""
                'txtLivro.SetFocus
            End If
        End If
    End Sub

    Private Function checaAdimplencia(ByRef Zona As String, ByRef Livro As String, ByRef Conta As String) As Short
        '**********************************************************
        '* Função que retorna o número de notas fiscais em aberto *
        '* para determinado consumidor.                           *
        '**********************************************************

        Dim sql As String
        '' Dim consulta As New ADODB.Recordset
        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        sql = "SELECT * "
        sql = sql & "FROM nf "
        sql = sql & "WHERE zona = '" & Zona & "' "
        sql = sql & "AND livro = '" & Livro & "' "
        sql = sql & "AND conta = '" & Conta & "' "
        sql = sql & "AND trim(flgst) = '' "
        sql = sql & "ORDER BY mesano "

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

        If dt.Rows.Count <> 0 Then
            checaAdimplencia = dt.Rows.Count
        Else
            checaAdimplencia = 0
        End If

    End Function

    Private Sub Arredondamento(ByRef valorTotal As Double, ByVal unid_id As Double)
        Dim sql As String
        'Dim consulta As New ADODB.Recordset

        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

        casasDecimais = CDbl(VB.Right(Format(valorTotal, "standard"), 2)) / 100

        sql = "SELECT arredonda FROM uc_faturamento WHERE unid_id = " & unid_id & " "


        objAtualizaBancoDados.QUERY_NAME = sql
        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(Format(0.5 - casasDecimais, "standard")) <= 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(Format(1 - casasDecimais, "standard")) <= 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 = CStr("0302990041")
        ''grid_fatura.Col = 2
        ''grid_fatura.Text = ""
        ''grid_fatura.Col = 3
        ''grid_fatura.Text = Format(Arredondamento, "standard")
        '-----------------------------------------------------------------------------------------------

        valorTotal = valorArredondado

        '----- Atualiza a tabela `unidb` com o saldo restante do arredondamento -----------------------------------
        sql = "UPDATE uc_faturamento SET arredonda_ant = " & Replace(CStr(saldo), ",", ".") & " WHERE unid_id = " & unid_id & " "
        objAtualizaBancoDados.QUERY_NAME = sql
        repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
        '----------------------------------------------------------------------------------------------------------
    End Sub

    Private Sub VerDelMultaJuro(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String)
        Dim strsql 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 rsMultaJuro As ADODB.Recordset
        'Dim rsFatura As ADODB.Recordset

        'rsFatura = New ADODB.Recordset
        'rsMultaJuro = New ADODB.Recordset

        Dim dt As DataTable
        Dim dt2 As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        strsql = "SELECT itensserv " & "  FROM nftransicao " & " WHERE cons_id = " & Id_Consumidor & "   AND unid_id = " & Id_Unid & "   AND mesano=""" & Me.txtMesAno.Text & """"


        objAtualizaBancoDados.QUERY_NAME = strsql
        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(strRef, "Fatura", ""), "(  REF. MÊS", ""), ")", "")
                            strMAAMulta = VB.Right(Trim(strRef), 7)
                            strRef = VB.Left(strRef, Len(strRef) - 7)
                            dblNFMulta = Val(strRef)

                            strsql = "SELECT * FROM multajuros " & " WHERE zona = '" & astrZona & "' " & "   AND livro = '" & astrLivro & "' " & "   AND conta = '" & astrConta & "' " & "   AND mesano = '" & strMAAMulta & "' " & "   AND isento = 0 "
                            If dblNFMulta > 0 Then
                                strsql = strsql & "   AND numnf = " & dblNFMulta
                            End If


                            objAtualizaBancoDados.QUERY_NAME = strsql
                            dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                            If dt2.Rows.Count <> 0 Then

                                For Each row2 As DataRow In dt2.Rows
                                    strsql = "DELETE FROM multajuros " & " WHERE zona = '" & astrZona & "' " & "   AND livro = '" & astrLivro & "' " & "   AND conta = '" & astrConta & "' " & "   AND mesano = '" & strMAAMulta & "' " & "   AND isento = 0 "
                                    If dblNFMulta > 0 Then
                                        strsql = strsql & "   AND numnf = " & dblNFMulta
                                    End If
                                    objAtualizaBancoDados.QUERY_NAME = strsql
                                    repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
                                Next
                            End If

                            intP1 = intP2 + 1
                        Else
                            intP1 = Len(strTexto) + 1
                        End If
                    End While
                End If
            Next
        End If

    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

        intDias = IIf(CDbl(VB.Left(Trim(classe), 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
    End Function

    Private Function VerificaExisteArrecad(ByVal alngUnidId As Integer) As Boolean
        Dim lstrSql As String
        lstrSql = IIf(IsDBNull(GetValorTabela("nf", "numnf", "mesano = """ & Me.txtMesAno.Text & """ " & "   AND unid_id = " & alngUnidId & "   AND MID(ta,3,1) = ""A"" " & " LIMIT 0, 1 ")), "", GetValorTabela("nf", "numnf", "mesano = """ & Me.txtMesAno.Text & """ " & "   AND unid_id = " & alngUnidId & "   AND MID(ta,3,1) = ""A"" " & " LIMIT 0, 1 "))

        If lstrSql = "" Then
            Return False
        Else
            Return True
        End If

    End Function

    Private Function BuscaContrato(ByVal alngUnidId As Integer, ByVal alngConsId As Integer, ByVal astrTarifa As String, ByVal adteRefer As Date, ByVal astrCodigo As String) As Double
        Dim ldblValor As Double
        Dim ldteRefer As Date
        'Dim lstrSql As String
        'Dim lrstContratos As ADODB.Recordset
        'lrstContratos = New ADODB.Recordset
        ldteRefer = CDate(Format("01/" & Format(adteRefer, "mm/yyyy"), "dd/mm/yyyy"))
        '' lstrSql = "SELECT contratos.valor " & "  FROM contratos " & " WHERE contratos.cons_id = " & alngConsId & "   AND contratos.unid_id = " & alngUnidId & "   AND contratos.ta = """ & astrTarifa & """ " & "   AND contratos.codigo = """ & astrCodigo & """ " & "   AND contratos.referencia = """ & Format(ldteRefer, "yyyy-MM-dd") & """ "

        ldblValor = IIf(IsDBNull(GetValorTabela("contratos", "contratos.valor", "contratos.cons_id = " & alngConsId & "   AND contratos.unid_id = " & alngUnidId & "   AND contratos.ta = """ & astrTarifa & """ " & "   AND contratos.codigo = """ & astrCodigo & """ " & "   AND contratos.referencia = """ & Format(ldteRefer, "yyyy-MM-dd") & """ ")), 0, IsDBNull(GetValorTabela("contratos", "contratos.valor", "contratos.cons_id = " & alngConsId & "   AND contratos.unid_id = " & alngUnidId & "   AND contratos.ta = """ & astrTarifa & """ " & "   AND contratos.codigo = """ & astrCodigo & """ " & "   AND contratos.referencia = """ & Format(ldteRefer, "yyyy-MM-dd") & """ ")))

        ldblValor = IIf(ldblValor = vbEmpty, 0, ldblValor)

        BuscaContrato = ldblValor
    End Function

    Private Function ControleContratoKwh(ByVal alngUnidId As Integer, ByVal alngConsId As Integer, ByVal astrTarifa As String, ByVal adteRefer As Date, ByVal astrCodigo As String, ByVal adblValor As Double, Optional ByRef astrMesRef As String = "") As Double
        Dim ldteAuxiliar As Date
        Dim ldblValor As Double
        Dim lstrSql As String
        'Dim lrstContratos As ADODB.Recordset
        'lrstContratos = New ADODB.Recordset

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        ldteAuxiliar = CDate(Format("01/" & Format(adteRefer, "mm/yyyy"), "dd/mm/yyyy"))
        ldteAuxiliar = System.DateTime.FromOADate(ldteAuxiliar.ToOADate - 1)
        ldteAuxiliar = CDate(Format("01/" & Format(ldteAuxiliar, "mm/yyyy"), "dd/mm/yyyy"))
        astrMesRef = Format(ldteAuxiliar, "mm/yyyy")
        'lstrSql = "SELECT controleutrpdevol.valor " & "  FROM controleutrpdevol " & " WHERE controleutrpdevol.cons_id = " & alngConsId & "   AND controleutrpdevol.unid_id = " & alngUnidId & "   AND controleutrpdevol.ta = """ & astrTarifa & """ " & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ " & "   AND DATE_FORMAT(controleutrpdevol.referencia,""%Y-%m"") = """ & Format(ldteAuxiliar, "yyyy-mm") & """ "

        lstrSql = IIf(IsDBNull(GetValorTabela("controleutrpdevol", "controleutrpdevol.valor", "controleutrpdevol.cons_id = " & alngConsId & "   AND controleutrpdevol.unid_id = " & alngUnidId & "   AND controleutrpdevol.ta = """ & astrTarifa & """ " & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ " & "   AND DATE_FORMAT(controleutrpdevol.referencia,""%Y-%m"") = """ & Format(ldteAuxiliar, "yyyy-mm") & """ ")), 0, GetValorTabela("controleutrpdevol", "controleutrpdevol.valor", "controleutrpdevol.cons_id = " & alngConsId & "   AND controleutrpdevol.unid_id = " & alngUnidId & "   AND controleutrpdevol.ta = """ & astrTarifa & """ " & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ " & "   AND DATE_FORMAT(controleutrpdevol.referencia,""%Y-%m"") = """ & Format(ldteAuxiliar, "yyyy-mm") & """ "))

        If lstrSql = 0 Or lstrSql = "" Then
            ldblValor = CDbl(lstrSql)
        Else
            ldblValor = 0
        End If

        ControleContratoKwh = ldblValor

        If adblValor <> 0 Then
            'Verifica se existe no mes atual em faturamento
            '  lstrSql = "SELECT controleutrpdevol.valor " & "  FROM controleutrpdevol " & " WHERE controleutrpdevol.cons_id = " & alngConsId & "   AND controleutrpdevol.unid_id = " & alngUnidId & "   AND controleutrpdevol.ta = """ & astrTarifa & """ " & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ " & "   AND controleutrpdevol.referencia = """ & Format(adteRefer, "yyyy-MM-dd") & """ "

            lstrSql = IIf(IsDBNull(GetValorTabela("controleutrpdevol", "Count(*)", "controleutrpdevol.cons_id = " & alngConsId & "   AND controleutrpdevol.unid_id = " & alngUnidId & "   AND controleutrpdevol.ta = """ & astrTarifa & """ " & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ " & "   AND controleutrpdevol.referencia = """ & Format(adteRefer, "yyyy-MM-dd") & """ ")), 0, GetValorTabela("controleutrpdevol", "controleutrpdevol.valor", "controleutrpdevol.cons_id = " & alngConsId & "   AND controleutrpdevol.unid_id = " & alngUnidId & "   AND controleutrpdevol.ta = """ & astrTarifa & """ " & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ " & "   AND controleutrpdevol.referencia = """ & Format(adteRefer, "yyyy-MM-dd") & """ "))


            If CInt(lstrSql) > 0 Then
                lstrSql = "UPDATE "
            Else
                lstrSql = "INSERT INTO "
            End If

            lstrSql = lstrSql & " controleutrpdevol SET "
            lstrSql = lstrSql & " controleutrpdevol.cons_id = " & alngConsId & ", "
            lstrSql = lstrSql & " controleutrpdevol.unid_id = " & alngUnidId & ", "
            lstrSql = lstrSql & " controleutrpdevol.ta = """ & astrTarifa & """, "
            lstrSql = lstrSql & " controleutrpdevol.codigo = """ & astrCodigo & """, "
            lstrSql = lstrSql & " controleutrpdevol.valor = " & Replace(CStr(adblValor), ",", ".") & ", "
            lstrSql = lstrSql & " controleutrpdevol.referencia = """ & Format(adteRefer, "yyyy-MM-dd") & """ "
            If VB.Left(Trim(lstrSql), 6) = "UPDATE" Then
                lstrSql = lstrSql & " WHERE controleutrpdevol.cons_id = " & alngConsId
                lstrSql = lstrSql & "   AND controleutrpdevol.unid_id = " & alngUnidId
                lstrSql = lstrSql & "   AND controleutrpdevol.ta = """ & astrTarifa & """ "
                lstrSql = lstrSql & "   AND controleutrpdevol.codigo = """ & astrCodigo & """ "
                lstrSql = lstrSql & "   AND controleutrpdevol.referencia = """ & Format(adteRefer, "yyyy-MM-dd") & """ "
            End If
            objAtualizaBancoDados.QUERY_NAME = lstrSql
            repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
        End If

    End Function

    Private Sub BuscaPrecoMae(ByVal adteReferencia As Date, ByRef adblPrecoMaior As Double, ByRef adblPrecoMenor As Double)
        Dim ldteAuxiliar As Date
        Dim lstrSql As String
        'Dim lrstPreco As ADODB.Recordset

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

        ldteAuxiliar = CDate(Format("01/" & Format(adteReferencia, "mm/yyyy"), "dd/mm/yyyy"))
        ldteAuxiliar = System.DateTime.FromOADate(ldteAuxiliar.ToOADate - 1)
        ldteAuxiliar = CDate(Format("01/" & Format(ldteAuxiliar, "mm/yyyy"), "dd/mm/yyyy"))

        lstrSql = ""
        lstrSql = lstrSql & "SELECT valormaior, valormenor "
        lstrSql = lstrSql & "  FROM precosmae "
        lstrSql = lstrSql & " WHERE referencia <= """ & Format(ldteAuxiliar, "yyyy-MM-dd") & """ "
        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
                adblPrecoMaior = IIf(IsDBNull(row("valormaior")), 0, row("valormaior"))
                adblPrecoMenor = IIf(IsDBNull(row("valormenor")), 0, row("valormenor"))
            Next
        Else
            adblPrecoMaior = 0
            adblPrecoMenor = 0
        End If
    End Sub

    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)
        Dim ldblMDec As Double
        Dim ldblMFec As Double
        Dim ldblMDic As Double
        Dim ldblMFic As Double
        Dim ldblMDmic As Double
        Dim ldblRDec As Double
        Dim ldblRFec As Double
        Dim ldblRDic As Double
        Dim ldblRFic As Double
        Dim ldblRDMic As Double
        Dim lstrMesAnoRef As String
        Dim lstrSql As String
        'Dim lrstConsulta As ADODB.Recordset
        'lrstConsulta = New ADODB.Recordset

        Dim dt As DataTable

        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        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 & "  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 & """ "


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

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                ldblMDec = IIf(IsDBNull(row("mdec")), 0, row("mdec"))
                ldblMFec = IIf(IsDBNull(row("mfec")), 0, row("mfec"))
                ldblMDic = IIf(IsDBNull(row("mdic")), 0, row("mdic"))
                ldblMFic = IIf(IsDBNull(row("mfic")), 0, row("mfic"))
                ldblMDmic = IIf(IsDBNull(row("mdmic")), 0, row("mdmic"))
                ldblRDec = IIf(IsDBNull(row("rdec")), 0, row("rdec"))
                ldblRFec = IIf(IsDBNull(row("rfec")), 0, row("rfec"))
                ldblRDic = IIf(IsDBNull(row("rdic")), 0, row("rdic"))
                ldblRFic = IIf(IsDBNull(row("rfic")), 0, row("rfic"))
                ldblRDMic = IIf(IsDBNull(row("rdmic")), 0, row("rdmic"))
                lstrMesAnoRef = IIf(IsDBNull(row("mesanoref")), astrMesAno, row("mesanoref"))
                astrItens = Trim(astrItens & "0302080101?" & Replace(CStr(ldblMDec), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080102?" & Replace(CStr(ldblMFec), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080103?" & Replace(CStr(ldblMDic), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080104?" & Replace(CStr(ldblMFic), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080105?" & Replace(CStr(ldblMDmic), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080001?" & Replace(CStr(ldblRDec), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080002?" & Replace(CStr(ldblRFec), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080003?" & Replace(CStr(ldblRDic), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080004?" & Replace(CStr(ldblRFic), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080005?" & Replace(CStr(ldblRDMic), ",", ".") & "$;")
                astrItens = Trim(astrItens & "0302080099?0$" & lstrMesAnoRef & ";")
            Next
        End If

    End Sub
End Class