Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE


Friend Class frmFaturaAvulsa
    Inherits System.Windows.Forms.Form


    Dim istrMesAnoFat As String
    Dim istrClasseBX As String
    Dim istrBxRenda As String
    Dim istrCTRLFalc As String
    Dim istrSigla As String
    Dim istrTabela As String
    Dim iintLimRes As Long
    Dim iintLimRur As Long
    Dim idblNumNf As Double
    Dim idblNsuNr As Double
    Dim idblDeduzir As Double
    Dim idblTarCons As Double
    Dim idblTotalNota As Double
    Dim idblTotalLiquid As Double
    Dim idblTotalBICMS As Double
    Dim idblTotalBICMSST As Double
    Dim idblTotalBICMS1 As Double
    Dim idblTotalBPCOF As Double
    Dim idblTotalBPis As Double
    Dim idblTotalBCof As Double
    Dim idblPercentual As Double
    Dim idblDescBxRenda As Double
    Dim idblBaseIcms As Double
    Dim idblValorIcms As Double
    Dim idblValorIcmsST As Double
    Dim iCoefTribIcms1 As Double
    Dim iCoefTribIcms As Double
    Dim iCoefTribSIcms As Double
    Dim idblAliqPIS As Double
    Dim idblAliqCOF As Double
    Dim idblTotalVlrBaseCip As Double



    Dim strIsentoICMS As String

    Dim auxTarifaRes As Double
    Dim auxPisBxRenda As Double
    Dim auxCofBxRenda As Double
    Dim auxPisBxRenda1 As Double
    Dim auxCofBxRenda1 As Double
    Dim auxTotalPisBxRenda As Double
    Dim auxTotalCofBxRenda As Double
    Dim auxICMSbxRenda As Double


    Dim fpFixo As Double
    Dim strFP As String
    Dim baseConsumoReativo As Double
    Dim vlrBaseConsumoReativo As Double

    Dim percentual_retencao As Double
    Dim valor_retencao As Double
    Dim strConvenioDesconto As String


#Region "Propriedades"

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


        Try

            istrMesAnoFat = GetConfig("mes.ano.faturamento")

            DTPLeitAnt.Value = Date.Now
            DTPLeitAtu.Value = Date.Now

            DTPFaturamento.Value = "01/" & istrMesAnoFat

            If Microsoft.VisualBasic.Left(istrMesAnoFat, 2) - 1 < 1 Then
                DTPLeitAnt.Value = "01/12/" & Microsoft.VisualBasic.Right(istrMesAnoFat, 4) - 1
            Else
                DTPLeitAnt.Value = "01/" & Microsoft.VisualBasic.Left(istrMesAnoFat, 2) - 1 & "/" & Microsoft.VisualBasic.Right(istrMesAnoFat, 4)
            End If

            If Microsoft.VisualBasic.Left(istrMesAnoFat, 2) + 1 > 12 Then
                DTPProxLeit.Value = "01/01/" & Microsoft.VisualBasic.Right(istrMesAnoFat, 4) + 1
            Else
                DTPProxLeit.Value = "01/" & Microsoft.VisualBasic.Left(istrMesAnoFat, 2) + 1 & "/" & Microsoft.VisualBasic.Right(istrMesAnoFat, 4)
            End If

            DTPApresenta.Value = DTPFaturamento.Value
            DTPVencto.Value = DTPFaturamento.Value
            DTPVectoPP.Value = DTPFaturamento.Value.AddMonths(5)

            istrSigla = GetConfig("empresa.sigla")

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

    End Sub

    Private Sub txtConta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Enter

        Try

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

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

    End Sub

    Private Sub txtConta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Leave

        Try
            txtConta.Text = VB6.Format(txtConta.Text, "000000")

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

    End Sub

    Private Sub txtLivro_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Enter

        Try

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

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

    End Sub

    Private Sub txtLivro_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Leave

        Try

            txtLivro.Text = VB6.Format(txtLivro.Text, "00")

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

    End Sub

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

        Try

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

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

    End Sub

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

        Try

            txtMesano.Text = FormataData(txtMesano, 1)

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

    End Sub

    Private Sub txtZona_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Enter

        Try

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

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

    End Sub

    Private Sub txtZona_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Leave

        Try

            txtZona.Text = VB6.Format(txtZona.Text, "000")

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

    End Sub

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

        Try

            MontaTabTarifa()
            Me.lblInfo.Text = " Processando Fatura..."
            LeituraDados()
            Me.lblInfo.Text = " Fatura Processada"
            MessageBox.Show("Fatura Processada com Sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)

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

    End Sub

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

        Try

            lClose()

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

    End Sub

    Private Sub FrmFAturaAvulsa_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii = 27 Then
                cmdFechar_Click(cmdFechar, New System.EventArgs())
            ElseIf KeyAscii = 13 Then
                TabEnter(KeyAscii, eventArgs)
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

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

    End Sub

#End Region

#Region "Métodos"

    Private Sub lClose()

        Try

            Me.Close()

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub LeituraDados()

        Dim strclasse As String
        Dim strClasseAux As String
        Dim strFase As String
        Dim strTensao As String
        Dim strNumMed As String
        Dim strTarifa As String
        Dim strUf As String
        Dim strCidade As String
        Dim strBanco As String
        Dim strNmbco As String
        Dim strZona As String
        Dim strLivro As String
        Dim strConta As String
        Dim strRota As String
        Dim strNumeroAtual As String
        Dim strDtVcto As String
        Dim strDtVctoPP As String
        Dim strDtVctoReal As String
        Dim strDtLeit As String
        Dim strDtApre As String
        Dim strDtLAnt As String
        Dim strDtPLei As String
        Dim strDtEmis As String
        Dim strIERural As String
        Dim strItensServ As String
        Dim strIsentoIlum As String
        Dim strIsentoReativo As String
        Dim strCpf_Cnpj As String
        Dim strCodEnd As String
        Dim strCfop As String
        Dim dblConsumo As Double
        Dim dblConsumoFat As Double
        Dim dblLeitAnt As Double
        Dim dblLeitAtual As Double
        Dim strOcorrenc As String
        Dim dblLeitkvahrAtual As Double
        Dim dblLeitkvahrAnt As Double
        Dim dblConsumoReativo As Double
        Dim strPagGov As String
        Dim strFlgAvulsa As String


        Dim intConsId As Integer
        Dim intUnidId As Integer
        Dim intDiaVenc As Short
        Dim lngBanId As Integer
        Dim dblConstMed As Double
        Dim dblAliqICMS As Double
        Dim dblAliqICMS1 As Double
        Dim VlrRetencao As Double
        '  Dim dblArredond    As Double
        Dim dblTotFaturas As Double
        Dim bNFatura As Boolean
        Dim lstrAgrupa As String
        Dim dblResiduo As Double

        Dim dt As DataTable

        Dim vlist

        Dim vlist_1

        Dim vlist_2

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Dim objNfTransicao As New entidadeNfTransicao
        Dim repositorioNfTransicao As New repositorioNfTransicao

        Dim objLeitmensal As New entidadeLeitmensal
        Dim repositorioLeitmensal As New repositorioLeitmensal

        Dim objMunic As New entidadeMunic
        Dim repositorioMunic As New repositorioMunic

        Dim objTempItemFatura As New entidadeTempItemFatura
        Dim repositorioTempItemFatura As New repositorioTempItemFatura

        Dim objTempItemFaturaB As New entidadeTempItemFaturaB
        Dim repositorioTempItemFaturaB As New repositorioTempItemFaturaB

        Try



            'Pega UF
            strUf = GetConfig("empresa.uf")

            'Pega limites de consumo
            iintLimRes = GetConfig("limite.residencial")
            iintLimRur = GetConfig("limite.rural")

            'Pega percentual de retenção
            percentual_retencao = GetConfig("percentual.retencao.consumo")

            idblAliqPIS = Aliquota_PIS(DTPFaturamento.Value)
            idblAliqCOF = Aliquota_COFINS(DTPFaturamento.Value)
            dblTotFaturas = 0

            'Pega a leitura pela faixa da rota e pela data da leitura e compara com o mesano do faturamento

            objUCFaturamento.ZONA = txtZona.Text
            objUCFaturamento.LIVRO = txtLivro.Text
            objUCFaturamento.CONTA = txtConta.Text
            objUCFaturamento.GRUPO = "B"

            vlist = repositorioUCFaturamento.Select_11(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    strclasse = objUCFaturamentoFor.CLAS
                    strTarifa = objUCFaturamentoFor.TA
                    strZona = objUCFaturamentoFor.ZONA
                    strLivro = objUCFaturamentoFor.LIVRO
                    strConta = objUCFaturamentoFor.CONTA
                    strRota = objUCFaturamentoFor.ROTA
                    intConsId = objUCFaturamentoFor.CONS_ID
                    intUnidId = objUCFaturamentoFor.UNID_ID

                    strDtVcto = VB6.Format(DTPVencto.Value, "yyyy-MM-dd")
                    strDtLeit = VB6.Format(DTPLeitAtu.Value, "yyyy-MM-dd")
                    strDtApre = VB6.Format(DTPApresenta.Value, "yyyy-MM-dd")
                    strDtEmis = VB6.Format(DTPFaturamento.Value, "yyyy-MM-dd")
                    strDtLAnt = VB6.Format(DTPLeitAnt.Value, "yyyy-MM-dd")
                    strDtPLei = VB6.Format(DTPProxLeit.Value, "yyyy-MM-dd")
                    'intDiaVenc = DTPVencto.Value
                    strDtVctoReal = VB6.Format(strDtVcto, "yyyy-MM-dd")
                    dblLeitAnt = CDbl(txtLeitAnt.Text)
                    dblLeitAtual = CDbl(txtLeitAtu.Text)

                    istrMesAnoFat = txtMesano.Text
                    strCfop = CalcularCFOP(strclasse)
                    strFase = objUCFaturamentoFor.FASE
                    strTensao = objUCFaturamentoFor.TENSAO

                    If Microsoft.VisualBasic.Left(strclasse, 1) = "5" And Microsoft.VisualBasic.Left(strclasse, 2) <> "55" Then
                        strIERural = IIf(IsDBNull(objUCFaturamentoFor.INSC), "", Trim(CStr(objUCFaturamentoFor.INSC)))
                    Else
                        strIERural = ""
                    End If

                    strNumMed = objUCFaturamentoFor.NUM
                    dblConstMed = IIf(IsDBNull(objUCFaturamentoFor.CONST), 0, objUCFaturamentoFor.CONST)
                    dblConsumo = (dblLeitAtual - dblLeitAnt) * dblConstMed
                    dblConsumoFat = CDbl(txtConsumo.Text)
                    strCidade = objUCFaturamentoFor.CIDADE
                    lngBanId = IIf(IsDBNull(objUCFaturamentoFor.BANCO), "0", objUCFaturamentoFor.BANCO)
                    strNmbco = RetNmBanco(lngBanId)
                    strCpf_Cnpj = IIf(IsDBNull(objUCFaturamentoFor.CPF_CNPJ), "", objUCFaturamentoFor.CPF_CNPJ)
                    strIsentoICMS = IIf(IsDBNull(objUCFaturamentoFor.ISENTO), "N", objUCFaturamentoFor.ISENTO)
                    strIsentoReativo = IIf(IsDBNull(objUCFaturamentoFor.ISENTOREATIVO), "N", objUCFaturamentoFor.ISENTOREATIVO)
                    strIsentoIlum = IIf(IsDBNull(objUCFaturamentoFor.ILUM), "N", objUCFaturamentoFor.ILUM)
                    lstrAgrupa = IIf(IsDBNull(objUCFaturamentoFor.AGRUPA), "", objUCFaturamentoFor.AGRUPA)
                    strCodEnd = IIf(IsDBNull(objUCFaturamentoFor.CODEND), "", objUCFaturamentoFor.CODEND)
                    strPagGov = IIf(IsDBNull(objUCFaturamentoFor.PAGTO_GOVERNO), "", objUCFaturamentoFor.PAGTO_GOVERNO)
                    strFlgAvulsa = "S"

                    'Iniciar Gravação do cabecalho da nota fiscal
                    'Verifica se a fatura já esta gravada ref com a zona,livro,conta,unid,consid,mesanofat

                    objNfTransicao.ZONA = strZona
                    objNfTransicao.LIVRO = strLivro
                    objNfTransicao.CONTA = strConta
                    objNfTransicao.MESANO = istrMesAnoFat
                    objNfTransicao.CONS_ID = intConsId
                    objNfTransicao.UNID_ID = intUnidId

                    vlist_1 = repositorioNfTransicao.Select_6(objNfTransicao)

                    If vlist_1.Count > 0 Then

                        For Each objNfTransicaoFor As entidadeNfTransicao In vlist_1

                            'Update da nftransicao
                            idblNumNf = objNfTransicaoFor.NUMNF
                            idblNsuNr = IIf(IsDBNull(objNfTransicaoFor.NSU), 0, objNfTransicaoFor.NSU)
                            strItensServ = IIf(IsDBNull(objNfTransicaoFor.ITENSSERV), "", objNfTransicaoFor.ITENSSERV)
                            'tirar essa marreta de if mes = 11 apos a instalacao do sistema como definitivo
                            If GetConfig("empresa.uf") = "SC" And idblNsuNr < 1 Then idblNsuNr = GetConfig("ultimo.nrnsu") + 1
                            'Call GravaConfig("ultimo.nr.nsu", Trim(Str(idblNsuNr))) 'so habilite esta linha para nivel de teste


                            objNfTransicao.NUMNF = idblNumNf
                            objNfTransicao.CODCLAS = strclasse
                            objNfTransicao.MESANO = istrMesAnoFat
                            objNfTransicao.DATAVENC = strDtVctoReal
                            objNfTransicao.DATALEIT = strDtLeit
                            objNfTransicao.DATAAPR = strDtApre
                            objNfTransicao.DATAEM = strDtEmis
                            objNfTransicao.DATALEITANT = strDtLAnt
                            objNfTransicao.NSU = IIf(idblNsuNr < 1, 0, idblNsuNr)
                            objNfTransicao.ZONA = strZona
                            objNfTransicao.LIVRO = strLivro
                            objNfTransicao.CONTA = strConta
                            objNfTransicao.ROTA = strRota
                            objNfTransicao.CONS_ID = intConsId
                            objNfTransicao.UNID_ID = intUnidId
                            objNfTransicao.DATAPROXLEIT = strDtPLei
                            objNfTransicao.CFOP = Replace(strCfop, ",", ".")
                            objNfTransicao.TA = strTarifa
                            objNfTransicao.GRUPO = Mid(strTarifa, 3, 1)
                            objNfTransicao.FASE = strFase
                            objNfTransicao.TENSAO = strTensao
                            objNfTransicao.BANARREC = VB6.Format(lngBanId, "000")
                            objNfTransicao.BANCO_FATUR = VB6.Format(lngBanId, "000")
                            objNfTransicao.BANIDENT = strNmbco
                            objNfTransicao.NUM_MED = strNumMed
                            objNfTransicao.AGRUPA = lstrAgrupa
                            objNfTransicao.CPF_CNPJ = strCpf_Cnpj
                            objNfTransicao.PAG_GOV = strPagGov
                            objNfTransicao.FLGMEDFAT = strFlgAvulsa
                            objNfTransicao.CONST_MED = Replace(CStr(dblConstMed), ",", ".")

                            lUpdate_2(objNfTransicao)

                        Next

                    Else

                        'Pega o último número da NF na tabela config

                        If gstrEmpresa_Sigla.ToUpper() = "CERES" Then

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

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


                        'tirar essa marreta de if mes = 11 apos a instalacao do sistema como definitivo
                        If GetConfig("empresa.uf") = "SC" Then
                            idblNsuNr = GetConfig("ultimo.nr.nsu") + 1
                        End If

                        While Not bNFatura

                            'Verifica se este número já esta gravado para outra zona, livro, conta

                            objNfTransicao.NUMNF = idblNumNf
                            objNfTransicao.MESANO = istrMesAnoFat

                            dt = repositorioNfTransicao.SelectCount_1(objNfTransicao)

                            If Convert.ToInt32(dt.Rows(0).ItemArray(0).ToString()) > 0 Then
                                idblNumNf = idblNumNf + 1
                            Else
                                bNFatura = True
                            End If

                            System.Windows.Forms.Application.DoEvents()

                        End While
                        '*********************

                        objNfTransicao.NUMNF = idblNumNf
                        objNfTransicao.CODCLAS = strclasse
                        objNfTransicao.MESANO = istrMesAnoFat
                        objNfTransicao.DATAVENC = strDtVctoReal
                        objNfTransicao.DATALEIT = strDtLeit
                        objNfTransicao.DATAAPR = strDtApre
                        objNfTransicao.DATAEM = strDtEmis
                        objNfTransicao.DATALEITANT = strDtLAnt
                        objNfTransicao.NSU = IIf(idblNsuNr < 1, 0, idblNsuNr)
                        objNfTransicao.ZONA = strZona
                        objNfTransicao.LIVRO = strLivro
                        objNfTransicao.CONTA = strConta
                        objNfTransicao.ROTA = strRota
                        objNfTransicao.CONS_ID = intConsId
                        objNfTransicao.UNID_ID = intUnidId
                        objNfTransicao.DATAPROXLEIT = strDtPLei
                        objNfTransicao.CFOP = Replace(strCfop, ",", ".")
                        objNfTransicao.TA = strTarifa
                        objNfTransicao.GRUPO = Mid(strTarifa, 3, 1)
                        objNfTransicao.FASE = strFase
                        objNfTransicao.TENSAO = strTensao
                        objNfTransicao.BANARREC = VB6.Format(lngBanId, "000")
                        objNfTransicao.BANCO_FATUR = VB6.Format(lngBanId, "000")
                        objNfTransicao.BANIDENT = strNmbco
                        objNfTransicao.NUM_MED = strNumMed
                        objNfTransicao.AGRUPA = lstrAgrupa
                        objNfTransicao.CPF_CNPJ = strCpf_Cnpj
                        objNfTransicao.PAG_GOV = strPagGov
                        objNfTransicao.FLGMEDFAT = strFlgAvulsa
                        objNfTransicao.CONST_MED = Replace(CStr(dblConstMed), ",", ".")

                        lInsert(objNfTransicao)

                        strNumeroAtual = CStr(idblNumNf)

                        'Grava o último número da Fatura na tabela Config

                        If gstrEmpresa_Sigla.ToUpper() = "CERES" Then

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

                        Else
                            SetConfig("ultimo.nr.fiscal", "String", strNumeroAtual, strNumeroAtual,, )
                        End If

                        If GetConfig("empresa.uf") = "SC" Then
                            SetConfig("ultimo.nr.fiscal", "String", Trim(Str(idblNsuNr)), Trim(Str(idblNsuNr)),, )
                        End If

                    End If

                    dblTotFaturas = dblTotFaturas + 1
                    ' If istrCTRLFalc = "S" Then Lixo.Clear
                    SetAvisos("[" & strZona & "." & strLivro & "." & strConta & "]: " & " Calculando a Fatura: " & idblNumNf)
                    SetLixo("Inicio da Fatura: " & idblNumNf & " as " & TimeOfDay)
                    'Termino da Gravação do cabecalho iniciar calculos

                    idblTotalNota = 0
                    idblTotalLiquid = 0
                    idblTotalBICMS = 0
                    idblTotalBICMSST = 0
                    idblTotalBICMS1 = 0
                    idblTotalBPCOF = 0
                    idblTotalBPis = 0
                    idblTotalBCof = 0
                    idblTotalVlrBaseCip = 0
                    idblValorIcmsST = 0
                    idblTotalBICMSST = 0

                    GradeItensTarifab.Rows = 1
                    GradeItensTarifab.Clear()
                    idblDeduzir = 0

                    strClasseAux = strclasse

                    '**INICIO DA GRAVAÇÃO DOS ITENS DA NOTA FISCAL EM UMA MATRIZ
                    If Microsoft.VisualBasic.Left(strclasse, 1) = "9" And isBaixaRenda(strZona, strLivro, strConta, dblConsumoFat, strClasseAux, strCpf_Cnpj) Then
                        '9104 res 296, 9105 res 485 ou 9106 res 694

                        objNfTransicao.NUMNF = idblNumNf
                        objNfTransicao.CODCLAS = strClasseAux
                        objNfTransicao.MESANO = istrMesAnoFat

                        lUpdate_3(objNfTransicao)

                        strClasseAux = strclasse

                    End If

                    'Pega a Aliquota de ICMS
                    SetLixo("Inicio da Aliquota_ICMS as " & TimeOfDay)

                    If dblConsumo > 50 Then
                        dblAliqICMS = Aliquota_ICMS(strUf, dblConsumoFat, strclasse, DTPFaturamento.Value, strIsentoICMS, strFase)
                    Else
                        dblAliqICMS = Aliquota_ICMS(strUf, dblConsumo, strclasse, DTPFaturamento.Value, strIsentoICMS, strFase)
                        SetLixo("Fim da Aliquota_ICMS as " & TimeOfDay)
                    End If

                    'Pega os Coeficientes para Calculo de Pis, Cofins e ICMS
                    iCoefTribIcms = 1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100) + (dblAliqICMS / 100))
                    iCoefTribSIcms = 1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100))

                    'O calculo do consumo quebrado serve para todas as classes
                    'visto que este cálculo ele faz dinamicamente as faixas de consumo
                    'ou seja, a classe tanto pode ter uma faixa de consumo como
                    'também pode ter várias faixas de consumo
                    SetLixo("Inicio do CalculoConsumoQuebrado as " & TimeOfDay)
                    CalcConsumoQuebrado(dblConsumo, dblConsumoFat, (DTPFaturamento.Value), dblAliqICMS, strClasseAux, strUf, dblAliqICMS1, strIERural, strZona & strLivro & strConta, CDate(strDtLAnt), CDate(strDtLeit), strFase, strIsentoReativo)
                    SetLixo("Fim do CalculoConsumoQuebrado as " & TimeOfDay)
                    '************************************************************

                    ' ----- Grava o residuo no item da fatura

                    objLeitmensal.ZONA = strZona
                    objLeitmensal.LIVRO = strLivro
                    objLeitmensal.CONTA = strConta


                    vlist_2 = repositorioLeitmensal.Select_3(objLeitmensal)

                    If vlist_2.Count > 0 Then

                        For Each objLeitmensalFor As entidadeLeitmensal In vlist_2

                            dblResiduo = IIf(IsDBNull(objLeitmensalFor.RESIDUO), 0, objLeitmensalFor.RESIDUO)

                        Next

                        If dblResiduo > 0 Then
                            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020998")
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblResiduo)
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                        End If

                    End If

                    ' ----- FIM Grava o residuo no item da fatura

                    If GetConfig("empresa.sigla") = "CHESP" Then
                        SetLixo("Inicio do CobrarSobretaxa as " & TimeOfDay)
                        CobrarSobreTaxa(strZona, strLivro, strConta, dblAliqICMS)
                        SetLixo("Fim do CobrarSobretaxa as " & TimeOfDay)
                    End If

                    'Calcula o ICMS
                    SetLixo("Inicio do CalcICMS as " & TimeOfDay)
                    CalcICMS(strUf, dblConsumoFat, dblAliqICMS, strIERural, strClasseAux, dblConsumo, strFase)
                    SetLixo("Fim do CalcICMS as " & TimeOfDay)

                    'Calculo do Pis e do Cofins
                    SetLixo("Inicio da CalcPisCon as " & TimeOfDay)
                    CalcPisCon(strUf, strClasseAux)
                    SetLixo("Fim da CalcPisCon as " & TimeOfDay)

                    'Busca parcelas da sobretaxa (somente para a Chesp)
                    '      If LeConfig("EMPRESA_SIGLA") = "CHESP" Then
                    '        Call SetLixo("Inicio do CobrarSobretaxa as " & Time)
                    '        Call CobrarSobreTaxa(strZona, strLivro, strConta)
                    '        Call SetLixo("Fim do CobrarSobretaxa as " & Time)
                    '      End If

                    'Busca as taxas
                    SetLixo("Inicio do CobrarTaxasb as " & TimeOfDay)
                    CobrarTaxasb(strZona, strLivro, strConta)
                    SetLixo("Fim do CobrarTaxasb as " & TimeOfDay)

                    ' ----- Esta rotina estava aqui, foi transferida para baixo.
                    '      'Busca as convenios
                    '      Call SetLixo("Inicio do CobrarConvenios as " & Time)
                    '      Call CobrarConvenios(strZona, strLivro, strConta)
                    '      Call SetLixo("Fim do CobrarConvenios as " & Time)

                    'Busca o codigo da Cidade
                    objMunic.NOME = strCidade


                    vlist_2 = repositorioMunic.Select_3(objMunic)

                    If vlist_2.Count > 0 Then

                        For Each objMunicFor As entidadeMunic In vlist_2

                            'Calculo da Iluminação Pública
                            SetLixo("Inicio do CalcIlumPub as " & TimeOfDay)

                            If strclasse <> "9104" And strclasse <> "9105" And strclasse <> "9106" And strIsentoIlum <> "S" And istrSigla <> "CHESP" Then
                                If istrSigla = "HIDROPAN" Then
                                    Calc_ILUM_Hidropan(CShort(objMunicFor.CODNUM), strclasse, dblConsumoFat)
                                ElseIf istrSigla = "EFLUL" Then
                                    CalcIlumPub(CShort(objMunicFor.CODNUM), strclasse, dblConsumoFat)
                                    '      ElseIf istrSigla = "EFLJCL" Then
                                    '         Call Calc_ILUM_EFLJCL(objMunicFor.codnum, strClasse, dblConsumoFat)
                                ElseIf istrSigla = "CERGAL" Then
                                    CalcIlumPub(CShort(objMunicFor.CODNUM), strclasse, dblConsumo)
                                Else
                                    CalcIlumPub(CShort(objMunicFor.CODNUM), strclasse, dblConsumoFat)
                                End If
                            Else
                                If istrSigla = "CHESP" Then
                                    If (CDbl(objMunicFor.CODNUM) = 3 Or (CDbl(objMunicFor.CODNUM) <> 3 And strclasse <> "9107")) And Microsoft.VisualBasic.Left(strclasse, 1) <> "5" And Mid(strclasse, 1, 2) <> "61" And Mid(strclasse, 1, 2) <> "64" And strIsentoIlum <> "S" Then
                                        CalcIlumPub(CShort(objMunicFor.CODNUM), strclasse, dblConsumo, strZona, strLivro, strConta, 0, strCodEnd)
                                    End If
                                End If
                            End If

                            SetLixo("Fim do CalcIlumPub as " & TimeOfDay)

                        Next

                    End If


                    '-------------Estou fazendo neste trecho mais posteriormente colocar como sub rotina
                    'Retenção tributária
                    valor_retencao = 0

                    If Microsoft.VisualBasic.Left(strclasse, 2) = "63" Then

                        'strTexto = LeConfig("RETENCAO_FEDERAL")
                        '''''pis
                        percentual_retencao = 0.65
                        VlrRetencao = Arredondar(idblBaseIcms * (percentual_retencao / 100), 2)
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9090000001")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, VlrRetencao) 'Replace(VlrRetencao, ".", ",")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "( " & 0.65 & "%)")
                        valor_retencao = valor_retencao + VlrRetencao

                        ''''cofins
                        percentual_retencao = 3
                        VlrRetencao = Arredondar(idblBaseIcms * (percentual_retencao / 100), 2)
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9090000002")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, VlrRetencao) 'Replace(VlrRetencao, ".", ",")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "( " & 3 & "%)")
                        valor_retencao = valor_retencao + VlrRetencao

                        ''''CSLL
                        percentual_retencao = 1
                        VlrRetencao = Arredondar(idblBaseIcms * (percentual_retencao / 100), 2)
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9090000003")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, VlrRetencao) 'Replace(VlrRetencao, ".", ",")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "( " & 1 & "%)")
                        valor_retencao = valor_retencao + VlrRetencao

                        ''''IRPJ
                        percentual_retencao = 1.2
                        VlrRetencao = Arredondar(idblBaseIcms * (percentual_retencao / 100), 2)
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9090000004")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, VlrRetencao) 'Replace(VlrRetencao, ".", ",")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "( " & 1.2 & "%)")
                        valor_retencao = valor_retencao + VlrRetencao

                    End If

                    VerDelMultaJuro(strItensServ, strZona, strLivro, strConta)

                    If Microsoft.VisualBasic.Left(strclasse, 1) <> "6" Then
                        'Busca as faturas em aberto

                        If gstrEmpresa_Sigla = "CHESP" Then
                            SetLixo("Inicio do  verificarFaturasVencidas as " & TimeOfDay)
                            verificarFaturasVencidas(strZona, strLivro, strConta, intUnidId, intConsId)
                            SetLixo("Fim do  verificarFaturasVencidas as " & TimeOfDay)
                        Else
                            SetLixo("Inicio do Verificarfaturaemabertas as " & TimeOfDay)
                            verificarFaturaEmAbertas(strZona, strLivro, strConta, intUnidId, intConsId)
                            SetLixo("Fim do Verificarfaturaemabertas as " & TimeOfDay)
                        End If
                        'Cobra Multa por Atraso
                        SetLixo("Inicio do CobrarMultaCtaVencida as " & TimeOfDay)
                        CobrarMultaCtaVencida(strZona, strLivro, strConta, intUnidId, intConsId)
                        SetLixo("Fim do CobrarMultaCtaVencida as " & TimeOfDay)
                    End If

                    'Leitua Atual, Leitura Anterior e ocorrencia
                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990039")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, Fix(dblLeitAtual)) 'Fix(Replace(dblLeitAtual, ".", ","))
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990040")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, Fix(dblLeitAnt)) 'Fix(Replace(dblLeitAnt, ".", ","))
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

                    If Len(Trim(strOcorrenc)) > 0 And Len(Trim(strOcorrenc)) <> 0 Then
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, PegaOcorrencia(strOcorrenc, 0))
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, strOcorrenc) ' 'Fix(Replace(dblLeitAtual, ".", ","))
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, PegaOcorrencia(strOcorrenc, 1))
                    End If
                    'leitura atual reativo,anterior reativo,consumo reativo,fator de potencia

                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030099")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, strFP) ' fator de potencia
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

                    If dblConsumoReativo > 0 Then
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302010046")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblLeitkvahrAnt) 'leitura anterior reativo
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302010045")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblLeitkvahrAtual) ' leitura atual reativo
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302010047")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblConsumoReativo) ' consumo reativo
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                    End If


                    'Busca as convenios
                    SetLixo("Inicio do CobrarConvenios as " & TimeOfDay)
                    CobrarConvenios(strZona, strLivro, strConta)
                    SetLixo("Fim do CobrarConvenios as " & TimeOfDay)


                    'Atualiza a coluna itenserv na NFTRANSICAO
                    SetLixo("Inicio do MontarItensNF as " & TimeOfDay)
                    MontarItensNF(intUnidId, strZona, strLivro, strConta, strDtVctoReal)
                    SetLixo("Fim do MontarItensNF as " & TimeOfDay)

                    ComponentesFatura(intUnidId, intConsId)

                    'Busca indicadores de continuidade e grava nos itens da fatura 
                    'InsereIndContinuidadeNF(idblNumNf, istrMesAnoFat)

                    If Mid(strTarifa, 3, 1) = "A" Then

                        objTempItemFatura.NUMNF = idblNumNf
                        objTempItemFatura.MESANO = istrMesAnoFat

                        lDelete(objTempItemFatura)

                        SetLixo("Gerado os Temp Itens as " & TimeOfDay)

                        objTempItemFatura.NUMNF = idblNumNf
                        objTempItemFatura.MESANO = istrMesAnoFat

                        repositorioTempItemFatura.Execute(objTempItemFatura)

                    ElseIf Mid(strTarifa, 3, 1) = "B" Then

                        objTempItemFaturaB.NUMNF = idblNumNf
                        objTempItemFaturaB.MESANO = istrMesAnoFat

                        lDelete(objTempItemFaturaB)

                        SetLixo("Gerado os Temp Itens as " & TimeOfDay)

                        objTempItemFaturaB.NUMNF = idblNumNf
                        objTempItemFaturaB.MESANO = istrMesAnoFat

                        repositorioTempItemFaturaB.Execute(objTempItemFaturaB)

                    End If

                    'End If 'ocorrencia = 26
                    'End If  ' consumo for nulo


                    'ProgressBar.Value = ProgressBar.Value + 1
                    'TotFaturas.Text = dblTotFaturas

                    System.Windows.Forms.Application.DoEvents()

                Next

                'Mensagem de Finalização do Processo
                SetAvisos("Notas Fiscais Transitorias gravadas com sucesso ")
                SetAvisos("Último número da Nota Fiscal " & idblNumNf)
                SetAvisos("***************Processamento Encerrado********************")

            Else
                MessageBox.Show("Não existe esse consumidor! ", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If



        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub MontaTabTarifa()

        Dim intCol As Short

        Dim vlist

        Dim objTarifagrbp As New entidadeTarifagrbp
        Dim repositorioTarifagrbp As New repositorioTarifagrbp

        Try

            SetAvisos("Preparando as tarifas para cálculo...")

            vlist = repositorioTarifagrbp.Select(objTarifagrbp)

            If vlist.Count > 0 Then

                GradeTarifa.Rows = 0



                For Each objTarifagrbpFor As entidadeTarifagrbp In vlist

                    GradeTarifa.Rows = GradeTarifa.Rows + 1

                    GradeTarifa.set_TextMatrix(GradeTarifa.Rows - 1, 1, objTarifagrbpFor.TIPO)
                    GradeTarifa.set_TextMatrix(GradeTarifa.Rows - 1, 2, objTarifagrbpFor.CODIGO)
                    GradeTarifa.set_TextMatrix(GradeTarifa.Rows - 1, 3, objTarifagrbpFor.FAIXA)
                    GradeTarifa.set_TextMatrix(GradeTarifa.Rows - 1, 4, objTarifagrbpFor.VALORTA)


                    System.Windows.Forms.Application.DoEvents()

                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function RefazTotal(astrTexto As String, ByVal adblValor As Double) As Double

        Try

            If astrTexto = "0302020029" Then 'Pis
                RefazTotal = adblValor
            End If
            If astrTexto = "0302020030" Then 'Cofins
                RefazTotal = adblValor
            End If
            If astrTexto = "0301000003" Then 'TIP
                RefazTotal = adblValor
            End If
            If astrTexto = "0302030009" Then 'ICMS1
                RefazTotal = adblValor
            End If
            If astrTexto = "0302030010" Then 'ICMS2
                RefazTotal = adblValor
            End If
            If Microsoft.VisualBasic.Left(astrTexto, 9) = "030202009" Then 'Valor Consumo
                RefazTotal = adblValor
            End If
            If astrTexto = "0302020012" Then 'Valor Reativo
                RefazTotal = adblValor
            End If
            If astrTexto = "0302990009" Then ' VALOR SOBRETAXA
                RefazTotal = adblValor - idblValorIcmsST
            End If
            If Microsoft.VisualBasic.Left(astrTexto, 1) = "9" And Microsoft.VisualBasic.Left(astrTexto, 4) <> "9070" And Microsoft.VisualBasic.Left(astrTexto, 4) <> "9090" And Microsoft.VisualBasic.Left(astrTexto, 4) <> "9041" Then
                RefazTotal = adblValor
            End If
            If Microsoft.VisualBasic.Left(astrTexto, 4) = "9070" Then
                RefazTotal = -adblValor
            End If

            adblValor = 0

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function SetLixo(ByRef astrTexto As String) As Object


        Try


            'Função para adicionar e ir percorrendo o list box a medida que vai adicionando
            If istrCTRLFalc = "S" Then
                Lixo.Items.Add(astrTexto)
                '    Lixo.ListIndex = Lixo.ListCount - 1
                System.Windows.Forms.Application.DoEvents()
            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function SetAvisos(ByRef astrTexto As String) As Object

        Try


            'Função para adicionar e ir percorrendo o list box a medida que vai adicionando

            'Avisos.Items.Add(astrTexto)
            '    Avisos.ListIndex = Lixo.ListCount - 1
            System.Windows.Forms.Application.DoEvents()


        Catch ex As Exception
            Exit Function
        End Try
    End Function

    Private Function CalcPisCon(ByRef uf As String, ByRef c As String) As Object

        Dim dblValorPIS As Double
        Dim dblValorCOF As Double
        Dim FatorAjuste As Double



        Try


            'rodrigo 9107 = 9101
            If (uf = "GO") And (Microsoft.VisualBasic.Left(c, 1) = "9" And Microsoft.VisualBasic.Right(c, 1) <> "1" And Microsoft.VisualBasic.Right(c, 1) <> "7") Or idblBaseIcms = 0 Then 'danilo

                idblTotalBPis = Arredondar(idblTotalBPis, 2)

                idblTotalBCof = Arredondar(idblTotalBPis, 2)

                dblValorPIS = Arredondar(idblTotalBPis * (idblAliqPIS / 100), 2)

                dblValorCOF = Arredondar(idblTotalBCof * (idblAliqCOF / 100), 2)
            Else
                idblTotalBCof = idblBaseIcms
                idblTotalBPis = idblBaseIcms

                dblValorPIS = Arredondar(idblBaseIcms * (idblAliqPIS / 100), 2)

                dblValorCOF = Arredondar(idblBaseIcms * (idblAliqCOF / 100), 2)
            End If

            'Valor PIS
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020029")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValorPIS) 'Replace((dblValorPIS), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Aliquota Pis
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990303")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, idblAliqPIS) 'Replace(idblAliqPIS, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Base Pis
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020033")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, idblTotalBPis) 'Replace(idblTotalBPis, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Valor Cofins
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020030")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValorCOF) 'Replace((dblValorCOF), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Aliquota Cofins
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990304")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, idblAliqCOF) 'Replace(idblAliqCOF, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Base Cofins
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020034")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, idblTotalBCof) 'Replace(idblTotalBCof, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'rodrigo 9101 = 9107
            If (uf = "GO") And (Microsoft.VisualBasic.Left(c, 1) = "9" And Microsoft.VisualBasic.Right(c, 1) <> "1" And Microsoft.VisualBasic.Right(c, 1) <> "7") Then

                FatorAjuste = Arredondar((idblTotalNota + dblValorCOF + dblValorPIS) - idblTotalBPis, 2)
                'DANILO
                idblTotalNota = idblTotalNota + (FatorAjuste * -1) + dblValorPIS + dblValorCOF

            Else

                If idblBaseIcms > 0 Then

                    FatorAjuste = Arredondar(idblTotalNota - idblBaseIcms, 2)
                Else
                    FatorAjuste = 0

                    idblTotalNota = Arredondar(idblTotalNota + dblValorPIS + dblValorCOF, 2)
                End If

                'rodrigo 9101=9107
                If (Microsoft.VisualBasic.Left(c, 1) = "9" And Microsoft.VisualBasic.Right(c, 1) <> "1" And Microsoft.VisualBasic.Right(c, 1) <> "7") Then
                    idblTotalNota = idblTotalNota
                Else
                    If FatorAjuste <> 0 Then
                        idblTotalNota = idblTotalNota + (FatorAjuste * -1)
                    End If
                End If
            End If


            'Consumo Total
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020009") '& intCtrlCod
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, Replace(CStr(idblTotalNota), ",", "."))


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function CalcICMS(ByRef astrUf As String, ByRef adblConsumo As Double, ByRef adblAliquota As Double, ByRef astrIERural As String, ByRef astrClasse As String, ByRef adblconsumoLid As Double, ByRef astrFase As String) As Object

        Dim dblBase As Double
        Dim dblBase1 As Double
        Dim dblValor As Double
        Dim dblValor1 As Double
        Dim dblAliq As Double
        Dim dblAliq1 As Double
        Dim dblValorAux As Double



        Try

            If istrSigla <> "CHESP" Then ' DANILO 06/10/2008
                dblBase = idblTotalBICMS
                dblBase1 = idblTotalBICMS1
            Else
                If adblconsumoLid <= 50 And (CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 9 Or CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 5) Or strIsentoICMS = "S" Then
                    dblBase = 0
                    dblBase1 = 0
                    idblTotalBICMS = 0
                    idblTotalBICMS1 = 0
                Else
                    dblBase = idblTotalBICMS 'DANILO
                    dblBase1 = idblTotalBICMS1
                End If
            End If
            dblValor1 = 0
            dblValor = 0
            dblAliq = 0
            dblAliq1 = 0

            If CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 9 Then
                If astrUf = "RS" Then

                    dblAliq = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS)
                    dblValor = (Arredondar((dblBase + dblBase1) * (dblAliq / 100), 2))
                Else
                    If adblConsumo >= iintLimRes Then
                        If astrUf = "GO" Then

                            dblAliq1 = Aliquota_ICMS(astrUf, CDbl(iintLimRes), astrClasse, DTPFaturamento.Value, strIsentoICMS, astrFase)

                            dblValor1 = Arredondar(dblBase1 * (dblAliq1 / 100), 2)

                            dblAliq = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS, astrFase)

                            dblValor = Arredondar(dblBase * (dblAliq / 100), 2)
                        Else

                            dblAliq1 = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS)

                            dblValor1 = Arredondar(dblBase1 * (dblAliq1 / 100), 2)

                            dblAliq = Aliquota_ICMS(astrUf, CDbl(iintLimRes), astrClasse, DTPFaturamento.Value, strIsentoICMS)

                            dblValor = Arredondar(dblBase * (dblAliq / 100), 2)
                        End If
                    Else

                        dblAliq = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS, astrFase)

                        dblValor = (Arredondar(dblBase * (dblAliq / 100), 2))
                    End If

                    ' ----- Ajuste para pegar aliquota do Residencial Bi e Tri
                    If istrSigla = "CHESP" Then
                        If astrFase <> "M" Then
                            If adblConsumo > 50 Then
                                dblAliq = 29
                                dblValor = (Arredondar(dblBase * (dblAliq / 100), 2))
                            Else
                                dblAliq = 0
                                dblValor = (Arredondar(dblBase * (dblAliq / 100), 2))
                            End If
                        End If
                    End If

                End If
            ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 5 Then
                If adblConsumo >= iintLimRur Then
                    If astrUf = "GO" Then
                        dblAliq1 = 0 'aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS, astrIERural)
                        dblValor1 = 0 'Arredondar((dblBase + dblBase1) * (dblAliq1 / 100), 2)

                        dblAliq = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS, astrIERural)
                        dblValor = (Arredondar((dblBase + dblBase1) * (dblAliq / 100), 2))
                    Else

                        dblAliq1 = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS, astrIERural)

                        dblValor1 = Arredondar(dblBase1 * (dblAliq1 / 100), 2)

                        dblAliq = Aliquota_ICMS(astrUf, CDbl(iintLimRur), astrClasse, DTPFaturamento.Value, strIsentoICMS, astrIERural)

                        dblValor = Arredondar(dblBase * (dblAliq / 100), 2)
                    End If
                Else

                    dblAliq = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS, astrIERural)
                    dblValor = (Arredondar(dblBase * (dblAliq / 100), 2))
                End If

            Else

                dblAliq = Aliquota_ICMS(astrUf, adblConsumo, astrClasse, DTPFaturamento.Value, strIsentoICMS)
                dblValor = (Arredondar(dblBase * (dblAliq / 100), 2))
            End If

            If istrSigla = "CHESP" Then 'DANILO 6/10/2008
                If adblconsumoLid <= 50 And (CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 9 Or CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 5) Then
                    dblAliq = 0
                End If
            End If



            dblValorAux = Arredondar(dblValor + dblValor1, 2)

            idblBaseIcms = Arredondar(idblTotalBICMS + idblTotalBICMS1, 2)

            If istrSigla = "CHESP" Then
                dblBase = dblBase + (idblTotalBICMSST + idblValorIcmsST)
                dblValor = dblValor + idblValorIcmsST
            End If

            'Base de Cálculo ICMS
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030001")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, IIf(dblBase < 0, 0, dblBase)) 'Replace(IIf(dblBase < 0, 0, dblBase), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
            'Valor ICMS
            idblValorIcms = dblValor
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030009")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, (dblValor)) 'Replace(dblValor, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Aliquota
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030002")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblAliq) 'Replace(dblAliq, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Base de Cálculo ICMS
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030003")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, IIf(dblBase1 < 0, 0, dblBase1)) 'Replace((IIf(dblBase1 < 0, 0, dblBase1)), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Valor ICMS
            idblValorIcms = dblValorAux
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030010")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValor1) 'Replace((dblValor1), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Aliquota
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030013")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblAliq1) 'Replace(dblAliq1, ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Base ICMS TOTAL
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030015")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, IIf(dblBase < 0, 0, dblBase) + IIf(dblBase1 < 0, 0, dblBase1)) 'Replace((IIf(dblBase < 0, 0, dblBase) + IIf(dblBase1 < 0, 0, dblBase1)), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            'Valor ICMS TOTAL
            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302030014")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, (dblValor + dblValor1)) 'Replace((dblValor + dblValor1), ".", ",")
            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")


            auxICMSbxRenda = Arredondar(dblValor + dblValor1, 2)

            idblTotalNota = Arredondar(idblTotalNota + dblValorAux, 2)

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function CalConsumoN(ByRef adblLeiAnt As Double, ByRef adblLeitAtual As Double, ByRef adblConstante As Double, ByRef aintGeraMedia As Short, ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByVal adblResiduo As Double) As Integer

        Dim dblLeitAtual As Double


        Try


            If aintGeraMedia <> 1 Then
                If adblLeitAtual >= 0 Then
                    'verificar de consumo menor que zero pois nescaso pode haver virada de medidor
                    If (adblLeitAtual - adblLeiAnt) < 0 Then
                        Select Case Len(CStr(adblLeiAnt))
                            Case 3
                                dblLeitAtual = (999 + adblLeitAtual) + 1
                            Case 4
                                dblLeitAtual = (9999 + adblLeitAtual) + 1
                            Case 5
                                dblLeitAtual = (99999 + adblLeitAtual) + 1
                            Case 6
                                dblLeitAtual = (999999 + adblLeitAtual) + 1
                            Case 7
                                dblLeitAtual = (9999999 + adblLeitAtual) + 1
                            Case 8
                                dblLeitAtual = (99999999 + adblLeitAtual) + 1
                            Case 9
                                dblLeitAtual = (999999999 + adblLeitAtual) + 1
                        End Select
                    Else
                        dblLeitAtual = adblLeitAtual
                    End If
                    'Refazer os calculo de consumo para apurar consumo real
                    CalConsumoN = Arredondar(((dblLeitAtual - adblLeiAnt) + adblResiduo) * adblConstante, 0)
                Else
                    CalConsumoN = 0
                End If
            Else
                'Quando tem Ocorrência que calcula a média, então faz pelo os ultimos 3 meses
                CalConsumoN = MediaMensal(astrZona, astrLivro, astrConta, 3)
            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Public Function CalConsumoR(ByRef adblLeitAnt As Double, ByRef adblLeitAtual As Double, ByRef adblConstante As Double) As Double

        Dim dblLeitAtual As Double

        Try

            'Verifica se consumo é menor que zero pois neste caso pode haver virada de medidor
            If (adblLeitAtual - adblLeitAnt) < 0 Then
                Select Case Len(adblLeitAnt)
                    Case 3
                        dblLeitAtual = (999 + adblLeitAtual) + 1
                    Case 4
                        dblLeitAtual = (9999 + adblLeitAtual) + 1
                    Case 5
                        dblLeitAtual = (99999 + adblLeitAtual) + 1
                    Case 6
                        dblLeitAtual = (999999 + adblLeitAtual) + 1
                    Case 7
                        dblLeitAtual = (9999999 + adblLeitAtual) + 1
                    Case 8
                        dblLeitAtual = (99999999 + adblLeitAtual) + 1
                    Case 9
                        dblLeitAtual = (999999999 + adblLeitAtual) + 1
                End Select
            Else
                dblLeitAtual = adblLeitAtual
            End If
            CalConsumoR = (dblLeitAtual - adblLeitAnt) * adblConstante

        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Function CalcularCFOP(ByRef astrClasse As String) As String

        Dim strclasse As String


        Try

            strclasse = Mid(astrClasse, 1, 1)

            If CDbl(strclasse) = 0 Or CDbl(strclasse) = 1 Or CDbl(strclasse) = 2 Or CDbl(strclasse) = 3 Then
                CalcularCFOP = "5.252"
            ElseIf CDbl(strclasse) = 5 Then
                CalcularCFOP = "5.256"
            ElseIf CDbl(strclasse) = 6 Or CDbl(strclasse) = 7 Or CDbl(strclasse) = 8 Or CDbl(strclasse) = 9 Then
                CalcularCFOP = "5.258"
            ElseIf CDbl(strclasse) = 4 Then
                CalcularCFOP = "5.253"

                If CDbl(Mid(astrClasse, 1, 2)) = 42 Then
                    CalcularCFOP = "5.254"
                ElseIf CDbl(Mid(astrClasse, 1, 2)) = 43 Then
                    CalcularCFOP = "5.255"
                End If
            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub CalcIlumCHESP(ByRef aintCidade As Short, ByRef astrClas As String, ByRef adblConsumo As Double, Optional ByRef Zona As String = "", Optional ByRef Livro As String = "", Optional ByRef Conta As String = "")

        Dim strTipo As String
        Dim strClas As String
        Dim intClas As Short
        Dim dblIlum As Double
        Dim dblCalcIlum As Double
        Dim auxConsumo As Double

        Dim vlist

        Dim objIluminacaoPublica As New entidadeIluminacaoPublica
        Dim repositorioIluminacaoPublica As New repositorioIluminacaoPublica

        Try


            If aintCidade = 2 Then
                auxConsumo = getUltConsumo(Zona, Livro, Conta)
            Else
                auxConsumo = adblConsumo
            End If

            strClas = Mid(astrClas, 1, 2)

            If CDbl(Mid(strClas, 1, 1)) <> 6 Then
                intClas = Val(Mid(strClas, 1, 1))
            Else
                intClas = Val(strClas)
            End If

            objIluminacaoPublica.CIDADE = aintCidade
            objIluminacaoPublica.CLASSE = intClas

            vlist = repositorioIluminacaoPublica.Select_1(objIluminacaoPublica)

            If vlist.Count > 0 Then

                For Each objIluminacaoPublicaFor As entidadeIluminacaoPublica In vlist

                    strTipo = IIf(IsDBNull(objIluminacaoPublicaFor.TIPO), "F", objIluminacaoPublicaFor.TIPO)

                    dblIlum = IIf(IsDBNull(objIluminacaoPublicaFor.VALOR), 0, objIluminacaoPublicaFor.VALOR)


                    'caso for percentual
                    If UCase(strTipo) = "P" Then
                        If auxConsumo > CDbl(objIluminacaoPublicaFor.FAIXA_FIM) Then
                            dblCalcIlum = Arredondar(CDbl((objIluminacaoPublicaFor.FAIXA_FIM)) * (dblIlum / 100), 2)
                        Else
                            dblCalcIlum = Arredondar(auxConsumo * (dblIlum / 100), 2)
                        End If
                    ElseIf UCase(strTipo) = "F" Then
                        dblCalcIlum = Arredondar(dblIlum, 2) 'caso for valor
                    End If


                Next

            Else
                dblCalcIlum = 0
            End If

            If dblCalcIlum <> 0 Then
                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0301000003")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblCalcIlum) 'Replace(dblCalcIlum, ".", ",")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                idblTotalNota = idblTotalNota + dblCalcIlum
            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function Calc_ILUM_Hidropan(ByRef aintCidade As Short, ByRef astrClas As String, ByRef adblConsumo As Double) As Object

        Dim strTipo As String
        Dim dblVlrIlum As Double
        Dim dblAuxIlum As Double
        Dim strAuxClass As String

        Dim vlist

        Dim objIluminacaoPublica As New entidadeIluminacaoPublica
        Dim repositorioIluminacaoPublica As New repositorioIluminacaoPublica

        Try

            dblAuxIlum = 0

            If Mid(astrClas, 1, 1) = "6" Then
                strAuxClass = Mid(astrClas, 1, 2)
            Else
                strAuxClass = Mid(astrClas, 1, 1)
            End If

            objIluminacaoPublica.CIDADE = aintCidade
            objIluminacaoPublica.CLASSE = strAuxClass
            objIluminacaoPublica.FAIXA_INI = adblConsumo
            objIluminacaoPublica.FAIXA_FIM = adblConsumo
            objIluminacaoPublica.DATA = DTPFaturamento.Value

            vlist = repositorioIluminacaoPublica.Select_1(objIluminacaoPublica)

            If vlist.Count > 0 Then

                For Each objIluminacaoPublicaFor As entidadeIluminacaoPublica In vlist

                    strTipo = UCase(IIf(IsDBNull(objIluminacaoPublicaFor.TIPO), "F", objIluminacaoPublicaFor.TIPO))
                    dblVlrIlum = IIf(IsDBNull(objIluminacaoPublicaFor.VALOR), 0, objIluminacaoPublicaFor.VALOR)

                    If strTipo = "P" Then
                        dblAuxIlum = idblTotalVlrBaseCip * (dblVlrIlum / 100) 'caso for percentual
                    ElseIf strTipo = "F" Then
                        dblAuxIlum = dblVlrIlum 'caso for valor
                    End If

                Next

            Else
                dblAuxIlum = 0
            End If

            dblAuxIlum = Arredondar(dblAuxIlum, 2)


            If dblAuxIlum <> 0 Then
                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0301000003")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblAuxIlum) 'Replace(dblAuxIlum, ".", ",")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                idblTotalNota = idblTotalNota + dblAuxIlum
            End If

        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Function isBaixaRenda(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef adblConsumo As Double, Optional ByRef astrClasse As String = "", Optional ByRef astrCpf_Cnpj As String = "") As Boolean

        Dim lstrBxRenda As String


        Try

            lstrBxRenda = Trim(GetConfig("calcular.baixarenda"))
            If lstrBxRenda = "-1" Then
                SetConfig("CALCULAR_BAIXARENDA", "String", "S", "S", "Calcular Baixa Renda (S/N).")
            ElseIf lstrBxRenda = "" Then
                SetConfig("CALCULAR_BAIXARENDA", "String", "S", "S", "Calcular Baixa Renda (S/N).")
            End If

            If gstrEmpresa_Sigla = "CHESP" Then '- chesp

                If lstrBxRenda = "S" Then
                    If checaFase(astrZona, astrLivro, astrConta) = "M" Then
                        If checa694(astrZona, astrLivro, astrConta) Then
                            If checaMedia(astrZona, astrLivro, astrConta, 0, 220, adblConsumo) Then ' >=0 e <=220
                                If VerificaBxRendaFaturamento(astrCpf_Cnpj, CStr(9106), astrZona, astrLivro, astrConta) Then
                                    isBaixaRenda = True
                                    astrClasse = "9106"
                                Else
                                    isBaixaRenda = False
                                End If
                            End If
                        ElseIf checaNis(astrZona, astrLivro, astrConta) Then
                            If checaMedia(astrZona, astrLivro, astrConta, 0, 220, adblConsumo) Then ' >79 e <=220
                                If VerificaBxRendaFaturamento(astrCpf_Cnpj, CStr(9105), astrZona, astrLivro, astrConta) Then
                                    isBaixaRenda = True
                                    astrClasse = "9105"
                                Else
                                    isBaixaRenda = False
                                End If
                            End If
                        ElseIf checaMedia(astrZona, astrLivro, astrConta, 0, 79.99, adblConsumo) Then  ' <= 79
                            If checaPicos(astrZona, astrLivro, astrConta, adblConsumo, 1) Then ' < 2 = true
                                If checaUnidade(astrZona, astrLivro, astrConta) Then 'Se esta unidade esta marcada como bx renda
                                    If VerificaBxRendaFaturamento(astrCpf_Cnpj, CStr(9104), astrZona, astrLivro, astrConta) Then
                                        isBaixaRenda = True
                                        astrClasse = "9104"
                                    Else
                                        isBaixaRenda = False
                                    End If
                                End If
                            Else
                                isBaixaRenda = False
                            End If
                        Else
                            isBaixaRenda = False
                        End If
                    Else
                        isBaixaRenda = False
                    End If
                Else
                    isBaixaRenda = False
                End If
            Else 'efljc - coorsel - cergal
                '[Se não tiver CPF ou for um CNPJ não concede o benefício]
                'If Len(Trim(astrCpf_Cnpj)) <> 11 Then
                If Len(Trim(astrCpf_Cnpj)) = 0 Or Len(Trim(astrCpf_Cnpj)) > 11 Then
                    isBaixaRenda = False
                Else
                    If checaFase(astrZona, astrLivro, astrConta) = "M" Then
                        If checaMedia(astrZona, astrLivro, astrConta, 79.99, 220, adblConsumo) Then ' >=80 e <=220
                            If checa694(astrZona, astrLivro, astrConta) Then
                                isBaixaRenda = True
                                astrClasse = "9106"
                            ElseIf checaNis(astrZona, astrLivro, astrConta) Then
                                isBaixaRenda = True
                                astrClasse = "9105"
                            Else
                                isBaixaRenda = False
                            End If
                        ElseIf checaMedia(astrZona, astrLivro, astrConta, 0, 79.99, adblConsumo) Then  ' <= 79
                            If checaPicos(astrZona, astrLivro, astrConta, adblConsumo, 1) Then ' < 3 = true
                                isBaixaRenda = True
                                astrClasse = "9104"
                            Else
                                isBaixaRenda = False
                            End If
                        Else
                            isBaixaRenda = False
                        End If
                    Else
                        isBaixaRenda = False
                    End If
                End If
            End If

        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Function checa694(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String) As Boolean

        Dim strRes694 As String

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try
            objUCFaturamento.ZONA = astrZona
            objUCFaturamento.LIVRO = astrLivro
            objUCFaturamento.CONTA = astrConta

            vlist = repositorioUCFaturamento.Select_4(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    strRes694 = IIf(IsDBNull(objUCFaturamentoFor.RES694), "N", UCase(Trim(CStr(objUCFaturamentoFor.RES694))))

                    If strRes694 = "S" Then
                        checa694 = True
                    Else
                        checa694 = False
                    End If

                Next
            Else
                checa694 = False
            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function checaPicos(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef adblConsumo As Double, ByVal aintQtdePicos As Short) As Boolean

        Dim intPicos As Short

        Dim vlist

        Dim objConsumos As New entidadeConsumos
        Dim repositorioConsumos As New repositorioConsumos

        Try

            If adblConsumo > 120 Then
                intPicos = 1
            End If

            objConsumos.ZONA = astrZona
            objConsumos.LIVRO = astrLivro
            objConsumos.CONTA = astrConta

            vlist = repositorioConsumos.Select_2(objConsumos)

            If vlist.Count > 0 Then

                For Each objConsumosFor As entidadeConsumos In vlist

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO1), 0, objConsumosFor.CONSUMO1), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO2), 0, objConsumosFor.CONSUMO2), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO3), 0, objConsumosFor.CONSUMO3), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO4), 0, objConsumosFor.CONSUMO4), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO5), 0, objConsumosFor.CONSUMO5), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO6), 0, objConsumosFor.CONSUMO6), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO7), 0, objConsumosFor.CONSUMO7), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO8), 0, objConsumosFor.CONSUMO8), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO9), 0, objConsumosFor.CONSUMO9), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO10), 0, objConsumosFor.CONSUMO10), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If

                    If CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO11), 0, objConsumosFor.CONSUMO11), "*", "")) > 120 Then
                        intPicos = intPicos + 1
                    End If


                Next

                checaPicos = (intPicos <= aintQtdePicos)

            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function checaFase(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String) As String

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try
            objUCFaturamento.ZONA = astrZona
            objUCFaturamento.LIVRO = astrLivro
            objUCFaturamento.CONTA = astrConta

            vlist = repositorioUCFaturamento.Select_4(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    checaFase = IIf(IsDBNull(objUCFaturamentoFor.FASE), "", Trim(CStr(objUCFaturamentoFor.FASE)))

                Next

            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function checaUnidade(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String) As Boolean

        Dim lstrBxRenda As String


        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try
            objUCFaturamento.ZONA = astrZona
            objUCFaturamento.LIVRO = astrLivro
            objUCFaturamento.CONTA = astrConta

            vlist = repositorioUCFaturamento.Select_4(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    lstrBxRenda = IIf(IsDBNull(objUCFaturamentoFor.BXRENDA), "N", Trim(CStr(objUCFaturamentoFor.BXRENDA)))
                    checaUnidade = IIf(lstrBxRenda = "S", True, False)

                Next

            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function getUltConsumo(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String) As Short

        Dim vConsusmo As String

        Dim vlist

        Dim objConsumos As New entidadeConsumos
        Dim repositorioConsumos As New repositorioConsumos

        Try

            objConsumos.ZONA = astrZona
            objConsumos.LIVRO = astrLivro
            objConsumos.CONTA = astrConta

            vlist = repositorioConsumos.Select_2(objConsumos)

            If vlist.Count > 0 Then

                For Each objConsumosFor As entidadeConsumos In vlist
                    vConsusmo = CStr(CShort(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO11), 0, objConsumosFor.CONSUMO11), "*", "")))
                Next

                getUltConsumo = CShort(vConsusmo)
            Else
                getUltConsumo = 0
            End If


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function PegaOcorrencia(ByVal astrCod As String, ByVal aintTipoRetorno As Short) As String

        Dim strCod As String
        Dim strRetorno As String

        Dim vlist

        Dim objCodigo As New entidadeCodigo
        Dim repositorioCodigo As New repositorioCodigo

        Try

            strRetorno = String.Empty

            strCod = VB6.Format(astrCod, "00")

            If strCod <> "00" Then

                strCod = "90410000" & strCod

                objCodigo.NUM = strCod

                vlist = repositorioCodigo.Select_1(objCodigo)

                If vlist.Count > 0 Then

                    For Each objCodigoFor As entidadeCodigo In vlist
                        If aintTipoRetorno = 0 Then
                            strRetorno = IIf(IsDBNull(objCodigoFor.NUM), "", objCodigoFor.NUM)
                        ElseIf aintTipoRetorno = 1 Then
                            strRetorno = IIf(IsDBNull(objCodigoFor.DESCRI), "", objCodigoFor.DESCRI)
                        End If
                    Next

                End If

            End If

            PegaOcorrencia = strRetorno

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function RetNmBanco(ByRef alngBco As Integer) As String

        Dim vlist

        Dim objBanco As New entidadeBanco
        Dim repositorioBanco As New repositorioBanco

        Try

            objBanco.BAN_ID = alngBco

            vlist = repositorioBanco.Select_2(objBanco)

            If vlist.Count > 0 Then

                For Each objBancoFor As entidadeBanco In vlist
                    RetNmBanco = objBancoFor.NRBCO
                Next
            Else
                RetNmBanco = ""
            End If


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function RetIdBanco(ByRef astrBco As String) As Integer

        Dim vlist

        Dim objBanco As New entidadeBanco
        Dim repositorioBanco As New repositorioBanco

        Try

            objBanco.NRBCO = astrBco

            vlist = repositorioBanco.Select_1(objBanco)

            If vlist.Count > 0 Then

                For Each objBancoFor As entidadeBanco In vlist
                    RetIdBanco = objBancoFor.BAN_ID
                Next
            Else
                RetIdBanco = 0
            End If


        Catch ex As Exception
            Exit Function
        End Try


    End Function

    Private Function checaMedia(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef adblFaixaMin As Double, ByRef adblFaixaMax As Double, ByRef adblConsumo As Double) As Boolean


        Dim intConsumos As Short
        Dim intCont As Short
        Dim dblMedia As Double
        Dim dblValor As Double
        Dim dblConsumo11 As Double
        Dim dblConsumo10 As Double
        Dim dblConsumo09 As Double
        Dim dblConsumo08 As Double
        Dim dblConsumo07 As Double
        Dim dblConsumo06 As Double
        Dim dblConsumo05 As Double
        Dim dblConsumo04 As Double
        Dim dblConsumo03 As Double
        Dim dblConsumo02 As Double
        Dim dblConsumo01 As Double
        Dim dblConsumo00 As Double

        Dim dt As DataTable

        Dim vlist

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Dim objConsumos As New entidadeConsumos
        Dim repositorioConsumos As New repositorioConsumos

        Try

            dblMedia = 0

            'começa sempre pelo consumo do mes em faturamento em questão
            '[Só faz isso se a última fatura não foi cancelada]
            objNf.ZONA = astrZona
            objNf.LIVRO = astrLivro
            objNf.CONTA = astrConta
            objNf.GRUPO = "'C'"

            dt = repositorioNf.SelectCount_1(objNf)

            If Convert.ToInt32(dt.Rows(0).ItemArray(0).ToString()) = 0 Then
                intConsumos = 1
                dblValor = adblConsumo
            End If

            objConsumos.ZONA = astrZona
            objConsumos.LIVRO = astrLivro
            objConsumos.CONTA = astrConta

            vlist = repositorioConsumos.Select_3(objConsumos)

            For Each objConsumosFor As entidadeConsumos In vlist

                dblConsumo11 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO11), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO11)) = "", 0, objConsumosFor.CONSUMO11)), "*", ""))

                dblConsumo10 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO10), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO10)) = "", 0, objConsumosFor.CONSUMO10)), "*", ""))

                dblConsumo09 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO9), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO9)) = "", 0, objConsumosFor.CONSUMO9)), "*", ""))

                dblConsumo08 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO8), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO8)) = "", 0, objConsumosFor.CONSUMO8)), "*", ""))

                dblConsumo07 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO7), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO7)) = "", 0, objConsumosFor.CONSUMO7)), "*", ""))

                dblConsumo06 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO6), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO6)) = "", 0, objConsumosFor.CONSUMO6)), "*", ""))

                dblConsumo05 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO5), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO5)) = "", 0, objConsumosFor.CONSUMO5)), "*", ""))

                dblConsumo04 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO4), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO4)) = "", 0, objConsumosFor.CONSUMO4)), "*", ""))

                dblConsumo03 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO3), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO3)) = "", 0, objConsumosFor.CONSUMO3)), "*", ""))

                dblConsumo02 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO2), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO2)) = "", 0, objConsumosFor.CONSUMO2)), "*", ""))

                dblConsumo01 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO1), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO1)) = "", 0, objConsumosFor.CONSUMO1)), "*", ""))

                dblConsumo00 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO0), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO0)) = "", 0, objConsumosFor.CONSUMO0)), "*", ""))


                If Not IsDBNull(objConsumosFor.CONSUMO11) And Trim(CStr(objConsumosFor.CONSUMO11)) <> "" Then
                    dblValor = dblValor + dblConsumo11
                    intConsumos = intConsumos + 1
                End If

                If Not IsDBNull(objConsumosFor.CONSUMO10) And Trim(CStr(objConsumosFor.CONSUMO10)) <> "" Then
                    dblValor = dblValor + dblConsumo10
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO9) And Trim(CStr(objConsumosFor.CONSUMO9)) <> "" Then
                    dblValor = dblValor + dblConsumo09
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO8) And Trim(CStr(objConsumosFor.CONSUMO8)) <> "" Then
                    dblValor = dblValor + dblConsumo08
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO7) And Trim(CStr(objConsumosFor.CONSUMO7)) <> "" Then
                    dblValor = dblValor + dblConsumo07
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO6) And Trim(CStr(objConsumosFor.CONSUMO6)) <> "" Then
                    dblValor = dblValor + dblConsumo06
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO5) And Trim(CStr(objConsumosFor.CONSUMO5)) <> "" Then
                    dblValor = dblValor + dblConsumo05
                    intConsumos = 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO4) And Trim(CStr(objConsumosFor.CONSUMO4)) <> "" Then
                    dblValor = dblValor + dblConsumo04
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO3) And Trim(CStr(objConsumosFor.CONSUMO3)) <> "" Then
                    dblValor = dblValor + dblConsumo03
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO2) And Trim(CStr(objConsumosFor.CONSUMO2)) <> "" Then
                    dblValor = dblValor + dblConsumo02
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO1) And Trim(CStr(objConsumosFor.CONSUMO1)) <> "" Then
                    dblValor = dblValor + dblConsumo01
                    intConsumos = intConsumos + 1
                End If


                If Not IsDBNull(objConsumosFor.CONSUMO0) And Trim(CStr(objConsumosFor.CONSUMO0)) <> "" Then
                    dblValor = dblValor + dblConsumo00
                    intConsumos = intConsumos + 1
                End If


            Next

            If intConsumos > 0 Then
                dblMedia = Truncate(dblValor / intConsumos, 2)
            Else
                dblMedia = 0
            End If
            ' ----- Foi Alterado para fechar com o DOS na conversão, depois voltar ao normal
            'checaMedia = (dblMedia >= adblFaixaMin And dblMedia <= adblFaixaMax)
            checaMedia = (dblMedia >= adblFaixaMin And dblMedia <= adblFaixaMax)

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function checaNis(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String) As Boolean

        Dim lstrNrNis As String
        Dim lstrEvento As String

        Dim vlist

        Dim objNis As New entidadeNis
        Dim repositorioNis As New repositorioNis

        Try

            checaNis = False

            objNis.ZONA = astrZona
            objNis.LIVRO = astrLivro
            objNis.CONTA = astrConta

            vlist = repositorioNis.Select(objNis)

            If vlist.Count > 0 Then

                For Each objNisFor As entidadeNis In vlist
                    lstrNrNis = Trim(IIf(IsDBNull(objNisFor.NIS), "", objNisFor.NIS))
                    lstrEvento = IIf(IsDBNull(objNisFor.EVENTO), "I", objNisFor.EVENTO)

                    If lstrNrNis <> "" Then
                        If lstrEvento <> "D" Then
                            checaNis = True
                        End If
                    End If

                Next

            End If



        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function VerificaBxRendaFaturamento(ByRef astrCpf As String, ByRef astrClasse As String, ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String) As Boolean

        Dim strclasse As String

        Dim vlist

        Dim objBxRendaFaturamento As New entidadeBxRendaFaturamento
        Dim repositorioBxRendaFaturamento As New repositorioBxRendaFaturamento

        Try

            VerificaBxRendaFaturamento = False

            If Len(Trim(astrCpf)) = 0 Then
                VerificaBxRendaFaturamento = False
                Exit Function
            End If

            objBxRendaFaturamento.CPF = Trim(astrCpf)
            objBxRendaFaturamento.ZONA = astrZona
            objBxRendaFaturamento.LIVRO = astrLivro
            objBxRendaFaturamento.CONTA = astrConta


            vlist = repositorioBxRendaFaturamento.Select(objBxRendaFaturamento)

            If vlist.Count > 0 Then

                For Each objBxRendaFaturamentoFor As entidadeBxRendaFaturamento In vlist

                    strclasse = IIf(IsDBNull(objBxRendaFaturamentoFor.CLASSE), "", objBxRendaFaturamentoFor.CLASSE)

                    If strclasse = "9104" And astrClasse = "9104" Then

                        objBxRendaFaturamentoFor.ZONA = astrZona
                        objBxRendaFaturamentoFor.LIVRO = astrLivro
                        objBxRendaFaturamentoFor.CONTA = astrConta
                        objBxRendaFaturamentoFor.CPF = Trim(astrCpf)
                        objBxRendaFaturamentoFor.CLASSE = astrClasse

                        lInsert(objBxRendaFaturamentoFor)

                        VerificaBxRendaFaturamento = True
                    Else
                        VerificaBxRendaFaturamento = False
                        Exit Function
                    End If

                Next

            End If

        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Function MediaMensal(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef aintNMeses As Short, Optional ByRef alngCons_id As Integer = 0, Optional ByRef alngUnid_id As Integer = 0) As Double


        Dim intDivisor As Short
        Dim dblConsMed As Double
        Dim dblConsumo11 As Double
        Dim dblConsumo10 As Double
        Dim dblConsumo09 As Double
        Dim dblConsumo08 As Double
        Dim dblConsumo07 As Double
        Dim dblConsumo06 As Double
        Dim dblConsumo05 As Double
        Dim dblConsumo04 As Double
        Dim dblConsumo03 As Double
        Dim dblConsumo02 As Double
        Dim dblConsumo01 As Double
        Dim dblConsumo00 As Double

        Dim vlist

        Dim objConsumos As New entidadeConsumos
        Dim repositorioConsumos As New repositorioConsumos

        Try

            intDivisor = 0
            dblConsMed = 0


            objConsumos.ZONA = astrZona
            objConsumos.LIVRO = astrLivro
            objConsumos.CONTA = astrConta

            vlist = repositorioConsumos.Select_3(objConsumos)

            If vlist.Count > 0 Then

                For Each objConsumosFor As entidadeConsumos In vlist

                    dblConsumo11 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO11), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO11)) = "", 0, objConsumosFor.CONSUMO11)), "*", ""))

                    dblConsumo10 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO10), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO10)) = "", 0, objConsumosFor.CONSUMO10)), "*", ""))

                    dblConsumo09 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO9), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO9)) = "", 0, objConsumosFor.CONSUMO9)), "*", ""))

                    dblConsumo08 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO8), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO8)) = "", 0, objConsumosFor.CONSUMO8)), "*", ""))

                    dblConsumo07 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO7), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO7)) = "", 0, objConsumosFor.CONSUMO7)), "*", ""))

                    dblConsumo06 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO6), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO6)) = "", 0, objConsumosFor.CONSUMO6)), "*", ""))

                    dblConsumo05 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO5), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO5)) = "", 0, objConsumosFor.CONSUMO5)), "*", ""))

                    dblConsumo04 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO4), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO4)) = "", 0, objConsumosFor.CONSUMO4)), "*", ""))

                    dblConsumo03 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO3), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO3)) = "", 0, objConsumosFor.CONSUMO3)), "*", ""))

                    dblConsumo02 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO2), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO2)) = "", 0, objConsumosFor.CONSUMO2)), "*", ""))

                    dblConsumo01 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO1), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO1)) = "", 0, objConsumosFor.CONSUMO1)), "*", ""))

                    dblConsumo00 = CDbl(Replace(IIf(IsDBNull(objConsumosFor.CONSUMO0), 0, IIf(Trim(CStr(objConsumosFor.CONSUMO0)) = "", 0, objConsumosFor.CONSUMO0)), "*", ""))

                    'Se NÃO for nulo calcula
                    If aintNMeses >= 1 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO11) And Trim(CStr(objConsumosFor.CONSUMO11)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo11
                            intDivisor = 1
                        End If

                    End If

                    If aintNMeses >= 2 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO10) And Trim(CStr(objConsumosFor.CONSUMO10)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo10
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 3 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO9) And Trim(CStr(objConsumosFor.CONSUMO9)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo09
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 4 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO8) And Trim(CStr(objConsumosFor.CONSUMO8)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo08
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 5 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO7) And Trim(CStr(objConsumosFor.CONSUMO7)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo07
                            intDivisor = intDivisor + 1
                        End If
                    End If

                    If aintNMeses >= 6 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO6) And Trim(CStr(objConsumosFor.CONSUMO6)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo06
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 7 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO5) And Trim(CStr(objConsumosFor.CONSUMO5)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo05
                            intDivisor = 1
                        End If

                    End If

                    If aintNMeses >= 8 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO4) And Trim(CStr(objConsumosFor.CONSUMO4)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo04
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 9 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO3) And Trim(CStr(objConsumosFor.CONSUMO3)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo03
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 10 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO2) And Trim(CStr(objConsumosFor.CONSUMO2)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo02
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses >= 11 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO1) And Trim(CStr(objConsumosFor.CONSUMO1)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo01
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If aintNMeses = 12 Then

                        If Not IsDBNull(objConsumosFor.CONSUMO0) And Trim(CStr(objConsumosFor.CONSUMO0)) <> "" Then
                            dblConsMed = dblConsMed + dblConsumo00
                            intDivisor = intDivisor + 1
                        End If

                    End If

                    If intDivisor > 0 Then
                        dblConsMed = dblConsMed / intDivisor
                    Else
                        dblConsMed = 0
                    End If

                    MediaMensal = Arredondar(dblConsMed, 0)

                Next

            Else

                MediaMensal = 0

                If alngUnid_id > 0 And alngCons_id > 0 Then

                    objConsumos.ZONA = astrZona
                    objConsumos.LIVRO = astrLivro
                    objConsumos.CONTA = astrConta
                    objConsumos.UNID_ID = alngUnid_id
                    objConsumos.CONS_ID = alngCons_id

                    lInsert(objConsumos)

                End If

            End If

            If intDivisor = 0 Then
                MediaMensal = 0
            End If


        Catch ex As Exception
            Exit Function
        End Try

    End Function

    Private Sub VerDelMultaJuro(ByVal astrTexto As String, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String)


        Dim intP1 As Short
        Dim intP2 As Short
        Dim intP3 As Short
        Dim intP4 As Short
        Dim strAux As String
        Dim strRef As String
        Dim dblValor As Double
        Dim dblNFMulta As Double
        Dim strMAAMulta As String

        Dim dt As New DataTable

        Dim objMultaJuros As New entidadeMultaJuros
        Dim repositorioMultaJuros As New repositorioMultaJuros

        Try

            intP1 = 1

            intP1 = InStr(intP1, astrTexto, "9080000061")

            If intP1 > 0 Then

                While intP1 <= Len(astrTexto)

                    intP1 = InStr(intP1, astrTexto, "9080000061")

                    If intP1 > 0 Then

                        intP2 = InStr(intP1, astrTexto, ";") 'acha o final do codigo

                        strAux = Mid(astrTexto, intP1, (intP2 - intP1) + 1) 'separa a parte do codigo?valor$referencia

                        '         123456789012345678901234567890123456
                        'strAux = 9080000061?0,8802$Fatura 24 12/2007;

                        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(strRef, "Fatura", "")
                        strMAAMulta = Microsoft.VisualBasic.Right(strRef, 7)
                        strRef = Microsoft.VisualBasic.Left(strRef, Len(strRef) - 7)
                        dblNFMulta = Val(strRef)

                        objMultaJuros.ZONA = astrZona
                        objMultaJuros.LIVRO = astrLivro
                        objMultaJuros.CONTA = astrConta
                        objMultaJuros.NUMNF = dblNFMulta
                        objMultaJuros.MESANO = strMAAMulta
                        objMultaJuros.ISENTO = 0

                        dt = repositorioMultaJuros.SelectCount(objMultaJuros)

                        If Convert.ToInt32(dt.Rows(0).ItemArray(0).ToString()) > 0 Then
                            lDelete(objMultaJuros)
                        End If

                        intP1 = intP2 + 1

                    Else
                        intP1 = Len(astrTexto) + 1
                    End If

                End While

            End If

        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Private Sub arredondamento(ByVal valorTotal As Double, ByVal unid_id As Double)

        Dim valorArredondado As Double
        Dim arredondamento As Double
        Dim saldo As Double
        Dim casasDecimais As Double

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try

            casasDecimais = CDbl(Microsoft.VisualBasic.Right(VB6.Format(valorTotal, "standard"), 2)) / 100

            objUCFaturamento.UNID_ID = unid_id

            vlist = repositorioUCFaturamento.Select_9(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    If IsDBNull(objUCFaturamentoFor.ARREDONDA) Or Trim(CStr(objUCFaturamentoFor.ARREDONDA)) = "" Then
                        saldo = 0#
                    Else
                        saldo = objUCFaturamentoFor.ARREDONDA
                    End If

                Next

            End If

            If casasDecimais <> 0.5 And casasDecimais <> 0# Then
                If casasDecimais > 0# And casasDecimais < 0.5 Then
                    If saldo = 0# Then
                        valorArredondado = valorTotal - casasDecimais
                        arredondamento = casasDecimais * -1
                        saldo = (saldo + arredondamento) * -1
                    Else
                        If CDbl(VB6.Format(0.5 - casasDecimais, "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(VB6.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
            If arredondamento <> 0 Then
                '----- Adiciona o item "Arredondamento" à nota fiscal ------------------------------------------
                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1

                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990041")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, VB6.Format(arredondamento, "standard"))
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

            End If

            idblTotalNota = valorArredondado
            '-----------------------------------------------------------------------------------------------

            '----- Atualiza a tabela `unidb` com o saldo restante do arredondamento -----------------------------------
            objUCFaturamento.ARREDONDA_ANT = Replace(CStr(saldo), ",", ".")
            objUCFaturamento.UNID_ID = unid_id

            lUpdate(objUCFaturamento)


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobrarSobreTaxa(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef adblaliqICMS As Double)

        Dim valor As Double
        Dim valorCicms As Double
        Dim strRef As String

        Dim vlist

        Dim objSobreTaxa As New entidadeSobreTaxa
        Dim repositorioSobreTaxa As New repositorioSobreTaxa

        Try

            objSobreTaxa.ZONA = astrZona
            objSobreTaxa.LIVRO = astrLivro
            objSobreTaxa.CONTA = astrConta
            objSobreTaxa.MESANO = VB6.Format(DTPFaturamento.Value, "mm/yyyy")

            vlist = repositorioSobreTaxa.Select_2(objSobreTaxa)

            If vlist.Count > 0 Then

                For Each objSobreTaxaFor As entidadeSobreTaxa In vlist

                    valor = CDbl(IIf(IsDBNull(objSobreTaxaFor.VALOR), 0, objSobreTaxaFor.VALOR))
                    strRef = IIf(IsDBNull(objSobreTaxaFor.REFERENCIA), "", objSobreTaxaFor.REFERENCIA)

                    idblValorIcmsST = Arredondar(valor * (adblaliqICMS / (100 - adblaliqICMS)), 2)
                    idblTotalBICMSST = valor

                    valorCicms = valor + idblValorIcmsST

                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990009")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, valorCicms) 'Replace(valor, ".", ",")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "ACR.RACION.(DECISÃO JUDICIAL)" & strRef)

                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990010")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, idblValorIcmsST) 'Replace(valor, ".", ",")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

                    If adblaliqICMS = 0 Then
                        idblTotalNota = idblTotalNota + valor
                    Else
                        idblTotalNota = idblTotalNota + valorCicms
                    End If

                    objSobreTaxa.FLAG = "'P'"
                    objSobreTaxa.ZONA = astrZona
                    objSobreTaxa.LIVRO = astrLivro
                    objSobreTaxa.CONTA = astrConta
                    objSobreTaxa.MESANO = VB6.Format(DTPFaturamento.Value, "mm/yyyy")

                    lUpdate(objSobreTaxa)


                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub MontarItensNF(ByRef aintUnidid As Integer, ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef dataVencimento As Date)

        Dim intLinha As Short
        Dim strCpfCnpj As String
        Dim strCodHash As String
        Dim stritens As String
        Dim dblValorTotal As Double
        Dim dblValor As Double
        Dim strCodBarra As String
        Dim strDvCBarra As String
        Dim strCodImagem As String

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Dim objNfTransicao As New entidadeNfTransicao
        Dim repositorioNfTransicao As New repositorioNfTransicao

        Try

            stritens = ""

            For intLinha = 0 To GradeItensTarifab.Rows - 1
                stritens = stritens & GradeItensTarifab.get_TextMatrix(intLinha, 0) & "?"
                stritens = stritens & Replace(GradeItensTarifab.get_TextMatrix(intLinha, 1), ",'", ".")
                If Len(Trim(GradeItensTarifab.get_TextMatrix(intLinha, 2))) > 0 Then
                    stritens = stritens & "$" & GradeItensTarifab.get_TextMatrix(intLinha, 2) & ";"
                Else
                    stritens = stritens & ";"
                End If
                dblValor = Val(Replace(GradeItensTarifab.get_TextMatrix(intLinha, 1), ",", "."))
                dblValorTotal = dblValorTotal + (RefazTotal(GradeItensTarifab.get_TextMatrix(intLinha, 0), dblValor))
            Next intLinha

            If dblValorTotal < 0 Then dblValorTotal = 0

            If GetConfig("agrupar.icms") = "S" Then ' danilo ICMS
                idblTotalNota = idblTotalNota
            Else
                idblTotalNota = dblValorTotal
            End If


            'Arredondamento do valor de pagamento Somente para CHESP
            If GetConfig("arredondar.total.nf") = "S" And idblTotalNota > 0 Then

                SetLixo("Inicio do Arredondamento do Valor Total as " & TimeOfDay)
                arredondamento(idblTotalNota, aintUnidid)
                SetLixo("Fim do Arredondamento do Valor Total as " & TimeOfDay)

                ' Verifica se o ultimo item é de arredondamento
                If (GradeItensTarifab.get_TextMatrix(GradeItensTarifab.Rows - 1, 0) = "0302990041") Then
                    stritens = stritens & GradeItensTarifab.get_TextMatrix(GradeItensTarifab.Rows - 1, 0) & "?"
                    stritens = stritens & Replace(GradeItensTarifab.get_TextMatrix(GradeItensTarifab.Rows - 1, 1), ",'", ".")

                    If Len(Trim(GradeItensTarifab.get_TextMatrix(GradeItensTarifab.Rows - 1, 2))) > 0 Then
                        stritens = stritens & "$" & GradeItensTarifab.get_TextMatrix(GradeItensTarifab.Rows - 1, 2) & ";"
                    Else
                        stritens = stritens & ";"
                    End If
                End If

            End If

            If valor_retencao <> 0 Then
                idblTotalLiquid = idblTotalNota - valor_retencao
            Else
                idblTotalLiquid = idblTotalNota
            End If

            'SetAvisos ("Atualizando os itens da Fatura")

            objUCFaturamento.UNID_ID = aintUnidid

            vlist = repositorioUCFaturamento.Select_9(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist
                    strCpfCnpj = IIf(IsDBNull(objUCFaturamentoFor.CPF_CNPJ), "0", objUCFaturamentoFor.CPF_CNPJ)
                Next

            End If


            strCodHash = PreparaCampo(strCpfCnpj, NUMERICO, 14, 0)
            strCodHash = strCodHash & PreparaCampo(Str(idblNumNf), NUMERICO, 9, "0")
            strCodHash = strCodHash & PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(idblTotalNota, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
            strCodHash = strCodHash & PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(idblBaseIcms, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
            strCodHash = strCodHash & PreparaCampo(Str(CDbl(Replace(Replace(Format(Arredondar(idblValorIcms, 2), "standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")

            MontaCodBarras(idblNumNf, istrMesAnoFat, idblTotalLiquid, astrZona, astrLivro, astrConta, strCodBarra, strDvCBarra, CStr(dataVencimento), strCodImagem)

            objUCFaturamento.HISTORICO = strCodHash

            vlist = repositorioUCFaturamento.Select_10(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist
                    strCodHash = objUCFaturamentoFor.HISTORICO
                Next

            End If

            objNfTransicao.ITENSSERV = stritens
            objNfTransicao.VALORTOT = idblTotalNota
            objNfTransicao.VALORLIQ = Convert.ToInt32(idblTotalLiquid)
            objNfTransicao.FLGST = "''"
            objNfTransicao.DIAS = "" 'DateDiff(dataleit, dataleitant)
            objNfTransicao.DATAPAG = "'0000-00-00'"
            objNfTransicao.CODBARRA = strCodBarra
            objNfTransicao.DVCODBARRA = strDvCBarra
            objNfTransicao.CODHASH = UCase(strCodHash)
            objNfTransicao.NUMNF = idblNumNf
            objNfTransicao.MESANO = istrMesAnoFat
            'objNfTransicao.CODBARRA_IMAGEM = strCodImagem

            lUpdate_1(objNfTransicao)

            SetLixo("Atualizado os Itens as " & TimeOfDay)

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub verificarFaturaEmAbertas(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef aintUnidb As Integer, ByRef aintConsid As Integer)

        Dim vlist

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Try

            objNf.ZONA = astrZona
            objNf.LIVRO = astrLivro
            objNf.CONTA = astrConta
            objNf.CONS_ID = aintConsid
            objNf.UNID_ID = aintUnidb
            objNf.FLGST = "''"

            vlist = repositorioNf.Select_11(objNf)

            If vlist.Count > 0 Then

                For Each objNfFor As entidadeNf In vlist

                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990316")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, objNfFor.VALORTOT)
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, objNfFor.NUMNF & " " & objNfFor.MESANO)

                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub verificarFaturasVencidas(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef aintUnidb As Integer, ByRef aintConsid As Integer)

        Dim vlist

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Try

            objNf.ZONA = astrZona
            objNf.LIVRO = astrLivro
            objNf.CONTA = astrConta
            objNf.CONS_ID = aintConsid
            objNf.UNID_ID = aintUnidb
            objNf.FLGST = "''"
            objNf.DATAVENC = DTPFaturamento.Value

            vlist = repositorioNf.Select_12(objNf)

            If vlist.Count > 0 Then

                For Each objNfFor As entidadeNf In vlist

                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302990316")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, objNfFor.VALORTOT)
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, VB6.Format(objNfFor.NUMNF, "000000000") & " " & objNfFor.MESANO & " " & objNfFor.DATAVENC)


                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobrarMultaCtaVencida(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef aintUnidb As Integer, ByRef aintConsid As Integer)


        Dim strMesRefMulta As String
        Dim strMesAnoFat As String
        Dim dtFaturamento As Date
        Dim dtRefMulta As Date
        Dim dblMulta As Double
        Dim dblJuros As Double
        Dim dblCorrM As Double
        Dim dblNrFat As Double

        Dim vlist

        Dim objMultaJuros As New entidadeMultaJuros
        Dim repositorioMultaJuros As New repositorioMultaJuros

        Try


            dtFaturamento = CDate("01/" & DTPFaturamento.Value.Month.ToString() & "/" & DTPFaturamento.Value.Year.ToString())
            dtRefMulta = System.DateTime.FromOADate(dtFaturamento.ToOADate - 1)
            strMesRefMulta = VB6.Format(dtRefMulta, "mm/yyyy")

            'Chama a Procedure para gerar as multas/juros/correções montárias
            CalculaMultaJuros(astrZona, astrLivro, astrConta, strMesRefMulta)

            objMultaJuros.ZONA = astrZona
            objMultaJuros.LIVRO = astrLivro
            objMultaJuros.CONTA = astrConta
            objMultaJuros.COBRADO = "'N'"

            vlist = repositorioMultaJuros.Select(objMultaJuros)

            If vlist.Count > 0 Then

                For Each objMultaJurosFor As entidadeMultaJuros In vlist

                    dblNrFat = IIf(IsDBNull(objMultaJurosFor.NUMNF), 0, objMultaJurosFor.NUMNF)
                    strMesAnoFat = IIf(IsDBNull(objMultaJurosFor.MESANO), 0, objMultaJurosFor.MESANO)
                    dblMulta = IIf(IsDBNull(objMultaJurosFor.VLRMULTA), 0, objMultaJurosFor.VLRMULTA)
                    dblJuros = IIf(IsDBNull(objMultaJurosFor.VLRJUROS), 0, objMultaJurosFor.VLRJUROS)
                    dblCorrM = IIf(IsDBNull(objMultaJurosFor.VLRCM), 0, objMultaJurosFor.VLRCM)

                    'Multa
                    If dblMulta <> 0 Then
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9080000061")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblMulta)
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "Fatura " & dblNrFat & " " & strMesAnoFat)
                        idblTotalNota = idblTotalNota + dblMulta
                    End If

                    'Juros
                    If dblJuros <> 0 Then
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9080000066")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblJuros)
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "Fatura " & dblNrFat & " " & strMesAnoFat)
                        idblTotalNota = idblTotalNota + dblJuros
                    End If

                    'Correção monetária
                    If dblCorrM <> 0 Then
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "9080000067")
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblCorrM)
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "Fatura " & dblNrFat & " " & strMesAnoFat)
                        idblTotalNota = idblTotalNota + dblCorrM
                    End If

                Next

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

                objMultaJuros.ZONA = astrZona
                objMultaJuros.LIVRO = astrLivro
                objMultaJuros.CONTA = astrConta
                objMultaJuros.COBRADO = "'S'"

                lUpdate(objMultaJuros)

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CobrarTaxasb(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String)

        Dim strIsento As String
        Dim dblValor As Double
        Dim strRefer As String

        Dim vlist

        Dim objTaxas As New entidadeTaxas
        Dim repositorioTaxas As New repositorioTaxas

        Try

            objTaxas.ZONA = astrZona
            objTaxas.LIVRO = astrLivro
            objTaxas.CONTA = astrConta
            objTaxas.DT_INI = DTPFaturamento.Value

            vlist = repositorioTaxas.Select_1(objTaxas)

            If vlist.Count > 0 Then

                For Each objTaxasFor As entidadeTaxas In vlist

                    strRefer = IIf(IsDBNull(objTaxasFor.REF), "", objTaxasFor.REF)
                    If Len(Trim(strRefer)) > 0 Then strRefer = "( " & strRefer & " )"
                    strIsento = IIf(IsDBNull(objTaxasFor.SIT), "N", objTaxasFor.SIT)
                    dblValor = CDbl(IIf(IsDBNull(objTaxasFor.VALOR), 0, objTaxasFor.VALOR))
                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, objTaxasFor.CODIGO)
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValor) 'Replace(dblValor, ".", ",")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, strRefer)
                    If strIsento = "N" Then
                        'idblTotalBICMS = idblTotalBICMS + dblValor
                        'idblTotalBPCOF = idblTotalBPCOF + dblValor
                    End If

                    If Mid(CStr(objTaxasFor.CODIGO), 1, 4) = "9070" Then
                        dblValor = dblValor * (-1)
                    End If

                    idblTotalNota = idblTotalNota + dblValor

                Next

            End If

            objTaxas.SIT = "'P'"
            objTaxas.ZONA = astrZona
            objTaxas.LIVRO = astrLivro
            objTaxas.CONTA = astrConta
            objTaxas.DT_INI = DTPFaturamento.Value

            lUpdate(objTaxas)

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub CobrarConvenios(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String)

        Dim strIsento As String
        Dim dblValor As Double
        Dim strRefer As String
        Dim dblResto As Double

        Dim vlist

        Dim objConvenios As New entidadeConvenios
        Dim repositorioConvenios As New repositorioConvenios

        Try

            objConvenios.ZONA = astrZona
            objConvenios.LIVRO = astrLivro
            objConvenios.CONTA = astrConta
            objConvenios.DT_INI = DTPFaturamento.Value

            vlist = repositorioConvenios.Select_1(objConvenios)

            If vlist.Count > 0 Then

                For Each objConveniosFor As entidadeConvenios In vlist

                    strRefer = IIf(IsDBNull(objConveniosFor.REF), "", objConveniosFor.REF)
                    If Len(Trim(strRefer)) > 0 Then strRefer = "( " & strRefer & " )"
                    strIsento = IIf(IsDBNull(objConveniosFor.SIT), "N", objConveniosFor.SIT)
                    dblValor = CDbl(IIf(IsDBNull(objConveniosFor.VALOR), 0, objConveniosFor.VALOR))

                    If Mid(CStr(objConveniosFor.CONVENIO), 1, 4) = "9070" Then
                        If dblValor > idblTotalNota Then
                            dblResto = dblValor - idblTotalNota
                            dblValor = idblTotalNota
                            Call InsereConvenio(dblResto, astrZona, astrLivro, astrConta, CStr(objConveniosFor.CONVENIO), Microsoft.VisualBasic.Right(DTPProxLeit.Value, 7))
                        End If
                    End If


                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, objConveniosFor.CONVENIO)
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValor) 'Replace(dblValor, ".", ",")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, strRefer)

                    If dblValor > 0 And Mid(CStr(objConveniosFor.CONVENIO), 1, 4) = "9070" Then
                        dblValor = dblValor * -1
                    End If

                    idblTotalNota = idblTotalNota + dblValor

                    System.Windows.Forms.Application.DoEvents()

                Next

            End If

            objConvenios.SIT = "'P'"
            objConvenios.ZONA = astrZona
            objConvenios.LIVRO = astrLivro
            objConvenios.CONTA = astrConta
            objConvenios.DT_INI = DTPFaturamento.Value

            lUpdate(objConvenios)


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub InsereConvenio(ByRef adblResto As Double, ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef astrConvenio As String, ByRef astrReferencia As String)


        Dim strDtIni As String
        Dim strDtFim As String
        Dim intUnid_id As Short
        Dim intCons_id As Short

        Dim dt As DataTable

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Dim objConvenios As New entidadeConvenios
        Dim repositorioConvenios As New repositorioConvenios

        Try


            strDtFim = VB6.Format("01/" & Microsoft.VisualBasic.Right(DTPProxLeit.Value, 7), "yyyy-MM-dd")
            strDtIni = VB6.Format("01/" & Microsoft.VisualBasic.Right(DTPProxLeit.Value, 7), "yyyy-MM-dd")
            strDtFim = VB6.Format(UltimoDiaMes(Mid(strDtFim, 6, 2), Microsoft.VisualBasic.Left(strDtFim, 4)) & "/" & VB6.Format("01/" & Microsoft.VisualBasic.Right(DTPProxLeit.Value, 7), "mm/yyyy"), "yyyy-MM-dd")


            objUCFaturamento.ZONA = astrZona
            objUCFaturamento.LIVRO = astrLivro
            objUCFaturamento.CONTA = astrConta
            objUCFaturamento.GRUPO = "B"

            vlist = repositorioUCFaturamento.Select_11(objUCFaturamento)

            If vlist.Count > 0 Then

                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist

                    intUnid_id = IIf(IsDBNull(objUCFaturamentoFor.UNID_ID), 0, objUCFaturamentoFor.UNID_ID)
                    intCons_id = IIf(IsDBNull(objUCFaturamentoFor.CONS_ID), 0, objUCFaturamentoFor.CONS_ID)

                    objConvenios.UNID_ID = intUnid_id
                    objConvenios.CONS_ID = intCons_id
                    objConvenios.ZONA = astrZona
                    objConvenios.LIVRO = astrLivro
                    objConvenios.CONTA = astrConta
                    objConvenios.CONVENIO = astrConvenio
                    objConvenios.VALOR = adblResto
                    objConvenios.DT_INI = strDtIni
                    objConvenios.DT_FIM = strDtFim
                    objConvenios.REF = astrReferencia

                    dt = repositorioConvenios.SelectCount(objConvenios)

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

                        objConvenios.UNID_ID = intUnid_id
                        objConvenios.CONS_ID = intCons_id
                        objConvenios.ZONA = astrZona
                        objConvenios.LIVRO = astrLivro
                        objConvenios.CONTA = astrConta
                        objConvenios.CONVENIO = astrConvenio
                        objConvenios.VALOR = adblResto
                        objConvenios.DT_INI = strDtIni
                        objConvenios.DT_FIM = strDtFim
                        objConvenios.REF = astrReferencia

                        lInsert(objConvenios)

                    End If

                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CalcConsumoQuebrado(ByRef adblconsumoLid As Double, ByRef adblConsumoFat As Double, ByRef aDtFaturamento As Date, ByRef adblaliqICMS As Double, ByRef astrClasse As String, ByRef astrUf As String, ByRef adblAliqIcms1 As Object, ByRef astrIERural As String, ByRef id As String, ByVal dataLeituraAnterior As Date, ByVal dataLeituraAtual As Date, ByRef astrFase As String, ByRef astrIsentoReativo As Object)


        Dim strSqlAux As String
        Dim strTexto As String

        Dim dblLini As Double
        Dim dblAux As Double
        Dim dblLfim As Double
        Dim dblLimi As Double
        Dim dblCons As Double
        Dim dblConsAux As Double
        Dim dblConsAcum As Double

        Dim intCtrlCod As Short
        Dim intCtrlLido As Short
        Dim dblTarifa As Double
        Dim dblValor As Double
        Dim dblValorLido As Double
        Dim dblTarifaAux As Double
        Dim dblPisCofTar As Double
        Dim dblBasePisCof As Double
        Dim dblVlrPisCof As Double
        Dim dblVALORicms As Double
        Dim dblPisCofdoIcms As Double
        Dim dblVlrConsTrib As Double
        Dim dblVlrTarTrib As Double

        Dim dblCoefPis As Double
        Dim dblCoefCof As Double
        Dim dblPisTarifa As Double
        Dim dblCofTarifa As Double
        Dim dblBasePis As Double
        Dim dblVlrPis As Double
        Dim dblBaseCof As Double
        Dim dblVlrCof As Double
        Dim dblCoefIcms As Double
        Dim dblAliqICMS As Double
        Dim dblCoefIcms1 As Double
        Dim dblAliqICMS1 As Double
        Dim dblICMSTar As Double
        Dim dblBaseIcms As Double
        Dim dblICMSTar1 As Double
        Dim dblBaseICMS1 As Double

        Dim dblDescBxRenda As Double
        Dim dblSomaValorIcms As Double
        Dim strtexto1 As Double


        Dim lngResAux As Integer
        Dim lngRes25 As Integer
        Dim lngRes12 As Integer

        'criadas por ademir
        Dim coefTribIsento As Double
        Dim coefTrib1 As Double
        Dim coefTrib2 As Double
        Dim baseICMSisenta As Double
        Dim baseICMS1 As Double
        Dim baseICMS2 As Double

        'criadas por Fernando
        Dim consumoKvarh As Double
        Dim vlrConsumoKvarh As Double

        Dim aux As String

        Dim vlist

        Dim objTarifa As New entidadeTarifa
        Dim repositorioTarifa As New repositorioTarifa

        Try

            dblCoefPis = 1 - (idblAliqPIS / 100)
            dblCoefCof = 1 - (idblAliqCOF / 100)

            intCtrlCod = 0
            intCtrlLido = 0
            dblConsAcum = 0
            dblLini = 0
            dblLfim = 0
            dblValorLido = 0
            dblAux = adblConsumoFat
            auxPisBxRenda = 0
            auxCofBxRenda = 0
            auxTotalPisBxRenda = 0
            auxPisBxRenda1 = 0
            auxCofBxRenda1 = 0
            auxTotalCofBxRenda = 0
            'dataLeituraAnterior = "11/03/2009"

            'GradeTarifa (por equanto so serve para CHESP)
            dblTarifaAux = TarifaProporcional(dataLeituraAnterior, dataLeituraAtual, "01B1011101", 3) / 1000
            'dblTarifaAux = CDbl(GradeTarifa.TextMatrix(0, 3)) 'Tarifa Residencial Normal

            If Microsoft.VisualBasic.Left(astrClasse, 4) = "9101" Or Microsoft.VisualBasic.Left(astrClasse, 4) = "9107" Then 'Rodrigo - Residencial Rural = residencial Normal
                strSqlAux = "LEFT(num,8) = '01B10111' "
            ElseIf Microsoft.VisualBasic.Left(astrClasse, 1) = "9" And Microsoft.VisualBasic.Right(astrClasse, 1) <> "1" Then
                strSqlAux = "LEFT(num,8) = '01B10211' "
            ElseIf Microsoft.VisualBasic.Left(astrClasse, 1) = "5" Then
                strSqlAux = "LEFT(num,8) = '01B20111' "
            ElseIf Microsoft.VisualBasic.Left(astrClasse, 2) = "64" Then
                strSqlAux = "LEFT(num,8) = '01B40111' "
            Else
                If CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) < 4 Then
                    strSqlAux = "LEFT(num,8) = '01B31011' "
                ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 7 Then
                    strSqlAux = "LEFT(num,8) = '01B32011' "
                ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 4 Then
                    strSqlAux = "LEFT(num,8) = '01B33011' "
                ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 8 Then
                    strSqlAux = "LEFT(num,8) = '01B34011' "
                ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 6 Then
                    strSqlAux = "LEFT(num,8) = '01B35011' "
                End If
            End If

            objTarifa.DESCRI = strSqlAux
            objTarifa.DATANOVA = dataLeituraAtual

            vlist = repositorioTarifa.Select_6(objTarifa)

            If vlist.Count > 0 Then

                auxTarifaRes = TarifaProporcional(dataLeituraAnterior, dataLeituraAtual, "01B1011101", 3) / 1000

                For Each objTarifaFor As entidadeTarifa In vlist

                    'auxTarifaRes = tarifaProporcional(dataLeituraAnterior, dataLeituraAtual, objTarifaFor.num,3) / 1000
                    'auxTarifaRes = TarifaResidencial(aDtFaturamento)

                    If dblAux > 0 Then

                        dblLfim = IIf(IsDBNull(objTarifaFor.LIMITKWH), "0", objTarifaFor.LIMITKWH)

                        '----- linha substituída pela função que retorna a tarifa proporcional ------------
                        'dblTarifa = Arredondar((IIf(IsNull(objTarifaFor.valor), 0, objTarifaFor.valor) / 1000), 5)
                        '----------------------------------------------------------------------------------

                        '----- pega tarifa proporcional ----------------------------------------------------------

                        dblTarifa = TarifaProporcional(dataLeituraAnterior, dataLeituraAtual, objTarifaFor.NUM, 3) / 1000
                        '-----------------------------------------------------------------------------------------

                        If CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 7 Then

                            dblTarifa = Arredondar(dblTarifa - (dblTarifa * (15 / 100)), 5)
                        End If

                        dblLimi = dblLfim - dblLini

                        If dblAux <= dblLimi Then
                            dblCons = dblAux

                            dblValor = Arredondar(dblAux * dblTarifa, 2)
                            dblAux = 0
                        Else
                            dblCons = dblLimi

                            dblValor = Arredondar(dblLimi * dblTarifa, 2)
                            dblAux = dblAux - dblLimi
                        End If

                        dblConsAcum = dblConsAcum + dblCons

                        'Icms
                        ' rodrigo 9101=9107
                        If CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 9 And CDbl(Microsoft.VisualBasic.Right(astrClasse, 1)) <> 1 And CDbl(Microsoft.VisualBasic.Right(astrClasse, 1)) <> 7 Then
                            If astrUf = "GO" Then
                                If dblLfim >= iintLimRes And dblLini < iintLimRes Then '160 >= 150 and 100 < 150
                                    lngResAux = iintLimRes - dblLini '150-100=50

                                    If lngResAux > dblCons Then
                                        lngRes25 = 0
                                        lngRes12 = dblCons
                                    Else
                                        lngRes25 = dblCons - lngResAux '60-50=10   '25%
                                        lngRes12 = dblCons - lngRes25 '60-10=50   '12%
                                    End If

                                    'icms, pis e cofins em cima da tarifa do residencial normal

                                    dblAliqICMS = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value,  , astrFase) '12%

                                    dblAliqICMS1 = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value,  , astrFase) '25%

                                    If dblAliqICMS <> 0 Then

                                        dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) + (dblAliqICMS / 100)), 11)

                                        dblCoefIcms1 = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) + (dblAliqICMS1 / 100)), 11)

                                        dblICMSTar = Arredondar(auxTarifaRes / dblCoefIcms, 5) '12%

                                        dblICMSTar1 = Arredondar(auxTarifaRes / dblCoefIcms1, 5) '25%

                                        dblVlrTarTrib = Truncate(dblICMSTar * (dblAliqICMS / 100), 5)

                                        dblVlrTarTrib = Arredondar(dblVlrTarTrib * (1 + (idblAliqPIS / 100) + (idblAliqCOF / 100)), 5)

                                        dblBaseIcms = Arredondar(lngRes12 * dblICMSTar, 2) ' / (1 - (dblAliqICMS / 100)) 'Base ICMS 12%

                                        dblBaseICMS1 = Arredondar(lngRes25 * dblICMSTar1, 2) ' / (1 - (dblAliqICMS1 / 100)) 'Base ICMS 25%

                                        idblTotalBICMS = idblTotalBICMS + dblBaseIcms 'Acumula o Valor p/Base de ICMS 12%
                                        idblTotalBICMS1 = idblTotalBICMS1 + dblBaseICMS1 'Acumula o Valor p/Base de ICMS 25%
                                    End If

                                    'pis e cofins em cima da tarifa do baixa renda

                                    dblCoefIcms = Truncate(1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100)), 11)

                                    dblCoefIcms1 = Truncate(1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100)), 11)

                                    dblICMSTar = Arredondar(dblTarifa / dblCoefIcms, 5) '12%

                                    dblICMSTar1 = Arredondar(dblTarifa / dblCoefIcms1, 5) '25%
                                    dblVlrTarTrib = dblVlrTarTrib + dblICMSTar

                                    auxPisBxRenda = Arredondar((lngRes12 * dblICMSTar) * (idblAliqPIS / 100), 2)

                                    auxCofBxRenda = Arredondar((lngRes12 * dblICMSTar) * (idblAliqCOF / 100), 2)

                                    auxPisBxRenda1 = Arredondar((lngRes25 * dblICMSTar1) * (idblAliqPIS / 100), 2)

                                    auxCofBxRenda1 = Arredondar((lngRes25 * dblICMSTar1) * (idblAliqCOF / 100), 2)

                                    auxTotalPisBxRenda = auxTotalPisBxRenda + auxPisBxRenda + auxPisBxRenda1
                                    auxTotalCofBxRenda = auxTotalCofBxRenda + auxCofBxRenda + auxCofBxRenda1
                                Else

                                    dblAliqICMS = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value,    , astrFase)

                                    If dblAliqICMS <> 0 Then

                                        dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) + (dblAliqICMS / 100)), 11)

                                        dblICMSTar = Arredondar(auxTarifaRes / dblCoefIcms, 5) '12%

                                        dblVlrTarTrib = Truncate(dblICMSTar * (dblAliqICMS / 100), 5)

                                        dblVlrTarTrib = Arredondar(dblVlrTarTrib * (1 + (idblAliqPIS / 100) + (idblAliqCOF / 100)), 5)

                                        dblBaseIcms = Arredondar(dblCons * dblICMSTar, 2) 'Base ICMS 12%
                                        idblTotalBICMS = idblTotalBICMS + dblBaseIcms
                                    End If


                                    dblCoefIcms = Truncate(1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100)), 11)

                                    dblICMSTar = Arredondar(dblTarifa / dblCoefIcms, 5) '12%
                                    dblVlrTarTrib = dblVlrTarTrib + dblICMSTar

                                    auxPisBxRenda = Arredondar((dblCons * dblICMSTar) * (idblAliqPIS / 100), 2)

                                    auxCofBxRenda = Arredondar((dblCons * dblICMSTar) * (idblAliqCOF / 100), 2)
                                    auxTotalPisBxRenda = auxTotalPisBxRenda + auxPisBxRenda
                                    auxTotalCofBxRenda = auxTotalCofBxRenda + auxCofBxRenda
                                End If
                            Else
                                If dblLfim >= iintLimRes And dblLini < iintLimRes Then '160 >= 150 and 100 < 150
                                    lngResAux = iintLimRes - dblLini '150-100=50
                                    lngRes25 = dblCons - lngResAux '60-50=10   '25%
                                    If lngRes25 < 0 Then lngRes25 = 0
                                    lngRes12 = dblCons - lngRes25 '60-10=50   '12%

                                    If astrUf = "RS" Then

                                        dblAliqICMS = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value) '12%

                                        dblAliqICMS1 = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value) '25%
                                    Else

                                        dblAliqICMS = Aliquota_ICMS(astrUf, CDbl(iintLimRes), astrClasse, DTPFaturamento.Value,    , astrFase) '12%

                                        dblAliqICMS1 = Aliquota_ICMS(astrUf, CDbl(iintLimRes) + 1, astrClasse, DTPFaturamento.Value,    , astrFase) '25%
                                    End If


                                    dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100))), 11)

                                    dblCoefIcms1 = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS1 / 100))), 11)

                                    dblICMSTar = Arredondar(dblTarifa / dblCoefIcms, 5) '12%

                                    dblICMSTar1 = Arredondar(dblTarifa / dblCoefIcms1, 5) '25%

                                    dblBaseIcms = Arredondar(lngRes12 * dblICMSTar, 5) / (1 - (dblAliqICMS / 100)) 'Base ICMS 12%

                                    dblBaseICMS1 = Arredondar(lngRes25 * dblICMSTar1, 5) / (1 - (dblAliqICMS1 / 100)) 'Base ICMS 25%

                                    idblTotalBICMS = idblTotalBICMS + dblBaseIcms 'Acumula o Valor p/Base de ICMS 12%
                                    idblTotalBICMS1 = idblTotalBICMS1 + dblBaseICMS1 'Acumula o Valor p/Base de ICMS 25%
                                Else
                                    If astrUf = "RS" Then

                                        dblAliqICMS = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value)
                                    Else

                                        dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value,  , astrFase)
                                    End If


                                    dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100))), 11)

                                    dblICMSTar = Arredondar(dblTarifa / dblCoefIcms, 5) '12%

                                    dblBaseIcms = Arredondar(dblCons * dblICMSTar, 5) / (1 - (dblAliqICMS / 100)) 'Base ICMS 12%
                                    If dblLfim >= iintLimRes Then
                                        idblTotalBICMS1 = idblTotalBICMS1 + dblBaseIcms
                                    Else
                                        idblTotalBICMS = idblTotalBICMS + dblBaseIcms
                                    End If
                                End If
                            End If
                        ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 9 And CDbl(Microsoft.VisualBasic.Right(astrClasse, 1)) = 1 Then
                            If dblConsAcum >= iintLimRes Then '167 >= 150
                                If astrUf = "RS" Then
                                    If dblConsAcum > 50 Then
                                        lngRes25 = 0
                                        lngRes12 = dblConsAcum


                                        dblAliqICMS = Aliquota_ICMS(astrUf, CDbl(9999999), astrClasse, DTPFaturamento.Value) '12%
                                        dblAliqICMS1 = dblAliqICMS
                                    End If
                                ElseIf astrUf = "GO" Then
                                    lngRes25 = 0 'DANILO  '167-150=17 '25%
                                    lngRes12 = dblConsAcum - 0
                                    If adblconsumoLid <= 50 Then

                                        dblAliqICMS = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value,  , astrFase) '12%
                                    Else

                                        dblAliqICMS = Aliquota_ICMS(astrUf, adblConsumoFat, astrClasse, DTPFaturamento.Value,  , astrFase)
                                    End If

                                    dblAliqICMS1 = 0 'aliquota_ICMS(astrUf, adblConsumoLid, astrClasse, DTPFaturamento.Value) '25% 'DANILO
                                    '            ElseIf astrUf = "GO" Then
                                    '              'Danilo
                                    '              lngRes25 = 0 '167-150=17 '25%
                                    '              lngRes12 = dblConsAcum - 0
                                    '              If adblconsumoLid <= 50 Then
                                    '                dblAliqICMS = aliquota_ICMS(astrUf, 50, astrClasse, DTPFaturamento.Value) '12%
                                    '              Else
                                    '                dblAliqICMS = aliquota_ICMS(astrUf, 99999999, astrClasse, DTPFaturamento.Value)
                                    '              End If
                                    '              dblAliqICMS1 = 0
                                Else
                                    lngRes25 = dblConsAcum - iintLimRes '167-150=17 '25%
                                    lngRes12 = iintLimRes '=150   '12%


                                    dblAliqICMS = Aliquota_ICMS(astrUf, CDbl(iintLimRes), astrClasse, DTPFaturamento.Value,  , astrFase) '12%

                                    dblAliqICMS1 = Aliquota_ICMS(astrUf, CDbl(iintLimRes) + 1, astrClasse, DTPFaturamento.Value,  , astrFase) '25%
                                End If



                                dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100))), 11)

                                dblCoefIcms1 = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS1 / 100))), 11)

                                dblICMSTar = Arredondar((dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100)), 5) '12%

                                dblICMSTar1 = Arredondar((dblTarifa / dblCoefIcms1) / (1 - (dblAliqICMS1 / 100)), 5) '25%

                                dblBaseIcms = Arredondar(lngRes12 * dblICMSTar, 2) 'Base ICMS 12%

                                dblBaseICMS1 = Arredondar(lngRes25 * dblICMSTar1, 2) 'Base ICMS 25%

                                idblTotalBICMS = idblTotalBICMS + dblBaseIcms 'Acumula o Valor p/Base de ICMS 12%
                                idblTotalBICMS1 = idblTotalBICMS1 + dblBaseICMS1 'Acumula o Valor p/Base de ICMS 25%
                            Else

                                dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value,  , astrFase)

                                '            If astrUf = "GO" Then
                                '              If adblconsumoLid <= 50 Then
                                '                dblAliqICMS = aliquota_ICMS(astrUf, 50, astrClasse, DTPFaturamento.Value) '12%
                                '              Else
                                '                dblAliqICMS = aliquota_ICMS(astrUf, 99999999, astrClasse, DTPFaturamento.Value)
                                '              End If
                                '            Else
                                '              dblAliqICMS = aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value)
                                '            End If


                                dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100))), 11)

                                dblICMSTar = Arredondar((dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100)), 5) '12%

                                dblBaseIcms = Arredondar(dblCons * dblICMSTar, 2) 'Base ICMS 12%
                                idblTotalBICMS = idblTotalBICMS + dblBaseIcms
                            End If
                        ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 1)) = 5 Then
                            If dblConsAcum >= iintLimRur Then '600 >= 500
                                lngRes25 = dblConsAcum - iintLimRur '600-500=100 '25%
                                lngRes12 = iintLimRur '=500   '12%

                                If astrUf = "GO" Then
                                    If adblconsumoLid <= 50 Then

                                        dblAliqICMS = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value,  , astrIERural)

                                        dblAliqICMS1 = Aliquota_ICMS(astrUf, adblconsumoLid, astrClasse, DTPFaturamento.Value,  , astrIERural)
                                    Else

                                        dblAliqICMS = Aliquota_ICMS(astrUf, adblConsumoFat, astrClasse, DTPFaturamento.Value,  , astrIERural) '12%

                                        dblAliqICMS1 = Aliquota_ICMS(astrUf, adblConsumoFat, astrClasse, DTPFaturamento.Value,  , astrIERural) '25%
                                    End If
                                    'UPGRADE_WARNING: Couldn't resolve default property of object adblAliqIcms1. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
                                    adblAliqIcms1 = dblAliqICMS
                                Else

                                    dblAliqICMS = Aliquota_ICMS(astrUf, CDbl(iintLimRur), astrClasse, DTPFaturamento.Value,  , astrIERural) '12%

                                    dblAliqICMS1 = Aliquota_ICMS(astrUf, CDbl(iintLimRur) + 1, astrClasse, DTPFaturamento.Value, astrIERural) '25%
                                End If


                                dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100))), 11)

                                dblCoefIcms1 = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS1 / 100))), 11)

                                dblICMSTar = Arredondar((dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100)), 5) '12%

                                dblICMSTar1 = Arredondar((dblTarifa / dblCoefIcms1) / (1 - (dblAliqICMS1 / 100)), 5) '25%

                                dblBaseIcms = Arredondar(lngRes12 * dblICMSTar, 2) 'Base ICMS 12%

                                dblBaseICMS1 = Arredondar(lngRes25 * dblICMSTar1, 2) 'Base ICMS 25%

                                idblTotalBICMS = idblTotalBICMS + dblBaseIcms 'Acumula o Valor p/Base de ICMS 12%
                                idblTotalBICMS1 = idblTotalBICMS1 + dblBaseICMS1 'Acumula o Valor p/Base de ICMS 25%
                            Else

                                dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value,  , astrIERural)

                                dblCoefIcms = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100))), 11)

                                dblICMSTar = Arredondar((dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100)), 5) '12%

                                dblBaseIcms = Arredondar(dblCons * dblICMSTar, 2) 'Base ICMS 12%
                                idblTotalBICMS = idblTotalBICMS + dblBaseIcms
                            End If
                        ElseIf CDbl(Microsoft.VisualBasic.Left(astrClasse, 2)) = 62 Then
                            If strIsentoICMS = "N" Then

                                dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value)

                                dblCoefIcms = Truncate(1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100) + (adblaliqICMS / 100)), 11)

                                dblICMSTar = Arredondar(dblTarifa / dblCoefIcms, 5)

                                dblBaseIcms = Arredondar(dblCons * dblICMSTar, 2)
                                idblTotalBICMS = idblTotalBICMS + dblBaseIcms
                            Else

                                dblCoefIcms = Truncate(1 - ((idblAliqPIS / 100) + (idblAliqCOF / 100)), 11)

                                dblICMSTar = Arredondar((dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100)), 5) '12%

                                dblBaseIcms = Arredondar(dblCons * dblICMSTar, 2) 'Base ICMS 12%
                                idblTotalBICMS = idblTotalBICMS + dblBaseIcms
                            End If
                        Else

                            dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value,  , astrFase)
                            dblCoefIcms = 1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100)))
                            dblICMSTar = (dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100))
                            dblBaseIcms = dblCons * dblICMSTar

                            idblTotalBICMS = Arredondar(idblTotalBICMS + dblBaseIcms, 2)
                        End If

                        dblLini = dblLfim
                        strFP = CStr(1)
                        '----- Energia reativa -----
                        If dblAux = 0 Then
                            If strFP < CStr(0.92) Then
                                If CDbl(strFP) <> 0 Then

                                    vlrBaseConsumoReativo = dblCons * dblTarifa

                                    aux = CStr(0.92 / CDbl(strFP))
                                    aux = CStr(CDbl(aux) - 1)

                                    vlrConsumoKvarh = Arredondar(vlrBaseConsumoReativo * CDbl(aux), 2)

                                    If astrIsentoReativo = "N" Then
                                        If astrUf = "GO" Then

                                            dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value, astrIERural, astrFase)
                                            dblCoefIcms = 1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100)))
                                            dblICMSTar = (dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100))
                                            dblBaseIcms = (dblCons * dblICMSTar) * CDbl(aux)

                                            idblTotalBICMS = Arredondar(idblTotalBICMS + dblBaseIcms, 2)
                                        ElseIf astrUf = "RS" Then

                                            dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value)
                                            dblCoefIcms = 1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100)))
                                            dblICMSTar = (dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100))
                                            dblBaseIcms = (dblCons * dblICMSTar) * CDbl(aux)

                                            idblTotalBICMS = Arredondar(idblTotalBICMS + dblBaseIcms, 2)
                                        ElseIf astrUf = "SC" Then

                                            dblAliqICMS = Aliquota_ICMS(astrUf, dblConsAcum, astrClasse, DTPFaturamento.Value)
                                            dblCoefIcms = 1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) / (1 - (dblAliqICMS / 100)))
                                            dblICMSTar = (dblTarifa / dblCoefIcms) / (1 - (dblAliqICMS / 100))
                                            dblBaseIcms = (dblCons * dblICMSTar) * CDbl(aux)

                                            idblTotalBICMS = Arredondar(idblTotalBICMS + dblBaseIcms, 2)
                                        End If


                                        idblTotalNota = Arredondar(idblTotalNota + vlrConsumoKvarh, 2)
                                    End If
                                End If
                            End If
                        End If


                        'rodrigo 9101 = 9107
                        If istrSigla = "CHESP" Then
                            If Microsoft.VisualBasic.Left(astrClasse, 1) = "9" And Microsoft.VisualBasic.Right(astrClasse, 1) <> "1" And Microsoft.VisualBasic.Right(astrClasse, 1) <> "7" Then ' And dblAliqICMS <> 0 Then
                                If dblAliqICMS = 0 Then

                                    strTexto = "( " & dblCons & " x " & FormatNumber(dblICMSTar, 5) & " ) = " & VB6.Format(Arredondar(dblCons * dblICMSTar, 2), "standard") 'strTexto = "( " & dblCons & " x " & dblVlrTarTrib & " ) = " & Arredondar(dblCons * dblVlrTarTrib, 2)

                                    strtexto1 = CDbl(VB6.Format(Arredondar(dblCons * dblICMSTar, 2), "standard"))
                                Else

                                    strTexto = "( " & dblCons & " x " & FormatNumber(dblVlrTarTrib, 5) & " ) = " & VB6.Format(Arredondar(dblCons * dblVlrTarTrib, 2), "standard")

                                    strtexto1 = CDbl(VB6.Format(Arredondar(dblCons * dblVlrTarTrib, 2), "standard"))
                                End If
                            Else

                                strTexto = "( " & dblCons & " x " & FormatNumber(dblICMSTar, 5) & " ) = " & VB6.Format(Arredondar(dblCons * dblICMSTar, 2), "standard") '& Format(idblTotalBICMS + idblTotalBICMS1, "standard")

                                strtexto1 = CDbl(VB6.Format(Arredondar(dblCons * dblICMSTar, 2), "standard"))
                            End If
                        Else
                            strTexto = "( " & dblCons & " x " & FormatNumber(dblTarifa, 5) & " ) = " & VB6.Format(dblValor, "standard")
                            strtexto1 = CDbl(VB6.Format(dblValor, "standard"))
                        End If
                        '****************************************************************************************
                        'strtexto = left(strtexto,len(strtexto

                        If intCtrlLido = 0 Then
                            If adblconsumoLid < adblConsumoFat Then
                                If istrSigla = "EFLUL" Then
                                    dblConsAux = adblconsumoLid

                                    dblValorLido = Arredondar(adblConsumoFat * dblTarifa, 2)
                                    intCtrlLido = 1
                                Else
                                    dblConsAux = adblconsumoLid

                                    dblValorLido = Arredondar(dblConsAux * dblTarifa, 2)
                                    intCtrlLido = 1
                                End If
                            Else
                                dblValorLido = dblValor
                                dblConsAux = dblCons
                            End If

                            'Consumo Lido Qtde
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "030201008" & intCtrlCod)
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblConsAux)
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1

                            'Consumo Lido Valor
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "030202008" & intCtrlCod)
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValorLido)
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "( " & adblconsumoLid & " x " & FormatNumber(dblTarifa, 5) & " )")
                            GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                        End If

                        'Consumo Faturado Qtde
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "030201009" & intCtrlCod)
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblCons)
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1

                        'Consumo Faturado Valor
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "030202009" & intCtrlCod)

                        If GetConfig("agrupar.icms") = "S" Then
                            '9107 = 9101 rodrigo
                            If Microsoft.VisualBasic.Left(astrClasse, 1) = "9" And Microsoft.VisualBasic.Right(astrClasse, 1) <> "1" And Microsoft.VisualBasic.Right(astrClasse, 1) <> "7" Then

                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, Arredondar(dblCons * dblVlrTarTrib, 2))
                            Else

                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, Arredondar(dblBaseIcms + dblBaseICMS1, 2))
                            End If
                        Else
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblValor)
                        End If

                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, strTexto)
                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1




                        'Consumo Reativo Valor
                        If astrIsentoReativo = "N" Then
                            If vlrConsumoKvarh > 0 Then
                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020012")
                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, vlrConsumoKvarh)
                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                                'danilo icms pra chesp
                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020112")
                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, Arredondar(vlrConsumoKvarh / (1 - ((dblAliqICMS + idblAliqPIS + idblAliqCOF) / 100)), 2))
                                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                            End If
                        End If


                        'Tarifa
                        GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, objTarifaFor.NUM)

                        If GetConfig("agrupar.icms") = "S" Then
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblVlrTarTrib)
                        Else
                            GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblTarifa)
                        End If

                        GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1

                        If dblAliqICMS = 0 Then
                            idblTotalBPis = idblTotalBPis + (dblCons * dblICMSTar)
                        Else
                            If astrUf = "RS" Then
                                idblTotalBPis = idblTotalBPis + (dblCons * dblTarifa)
                            Else
                                idblTotalBPis = idblTotalBPis + (dblCons * dblVlrTarTrib)
                            End If
                        End If


                        dblSomaValorIcms = dblSomaValorIcms + strtexto1

                        'Acumula os valores da fatura para calculo
                        idblTotalNota = Arredondar(idblTotalNota + dblValor, 2) 'Acumula o Valor da Consumo Puro

                        'Acumula os valores da fatura para base de calculo de CIP - HIDROPAN
                        idblTotalVlrBaseCip = Arredondar(idblTotalVlrBaseCip + dblValor, 2)

                        intCtrlCod = intCtrlCod + 1


                    End If

                    System.Windows.Forms.Application.DoEvents()

                Next

                'danilo consumo chesp
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302020190")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblSomaValorIcms) 'Arredondar(dblValor / (1 - ((dblAliqICMS + idblAliqPIS + idblAliqCOF) / 100)), 2)
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "") 'strTexto
                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1



                If astrClasse = "9104" Or astrClasse = "9105" Or astrClasse = "9106" Then

                    dblDescBxRenda = Truncate(1 - (((idblAliqPIS / 100) + (idblAliqCOF / 100)) + (dblAliqICMS / 100)), 11)
                    dblDescBxRenda = (dblTarifaAux / dblDescBxRenda) * adblConsumoFat
                    dblDescBxRenda = Arredondar(dblDescBxRenda - dblSomaValorIcms, 2)

                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0302090005")
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblDescBxRenda)
                    GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")
                    GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1

                End If

                If GradeItensTarifab.Rows > 1 Then
                    GradeItensTarifab.RemoveItem(GradeItensTarifab.Rows - 1)
                End If

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CalcIlumPub(ByRef aintCidade As Short, ByRef astrClas As String, ByRef adblConsumo As Double, Optional ByRef Zona As String = "", Optional ByRef Livro As String = "", Optional ByRef Conta As String = "", Optional ByRef adblConsumoLido As Double = 0, Optional ByVal astrCodEnd As String = "")

        Dim strTipo As String
        Dim strClas As String
        Dim intClas As Short
        Dim lngFxIni As Integer
        Dim lngFxFim As Integer
        Dim dblIlum As Double
        Dim dblCalcIlum As Double
        Dim dblConsumo As Double

        Dim vlist

        Dim objCip As New entidadeCip
        Dim repositorioCip As New repositorioCip

        Try

            If aintCidade = 2 And istrSigla = "CHESP" Then
                dblConsumo = getUltConsumo(Zona, Livro, Conta)
            Else
                dblConsumo = adblConsumo
            End If

            Dim strM1 As String
            Dim strM2 As String
            Dim strM3 As String
            Dim strM4 As String

            If istrSigla = "CHESP" And aintCidade = 3 Then

                strM1 = "016;017;028;039;044;045;052;053;066;070;082;091;094;119;122;125;130;131;135;136;"
                strM2 = "048;050;065;085;"
                strM3 = "007;031;071;108;"
                strM4 = "011;019;024;055;098;132;"

                If Microsoft.VisualBasic.Left(astrClas, 1) = "9" And dblConsumo > 80 Then
                    If InStr(1, strM1, Mid(astrCodEnd, 9, 3)) > 0 Then
                        dblCalcIlum = 4
                    ElseIf InStr(1, strM2, Mid(astrCodEnd, 9, 3)) > 0 Then
                        dblCalcIlum = 6
                    ElseIf InStr(1, strM3, Mid(astrCodEnd, 9, 3)) > 0 Then
                        dblCalcIlum = 7
                    ElseIf InStr(1, strM4, Mid(astrCodEnd, 9, 3)) > 0 Then
                        dblCalcIlum = 9
                    End If
                ElseIf Microsoft.VisualBasic.Left(astrClas, 1) <> "9" Then
                    If dblConsumo <= 180 And InStr(1, strM1 & strM2 & strM3 & strM4, Mid(astrCodEnd, 9, 3)) > 0 Then
                        dblCalcIlum = 9
                    Else
                        If InStr(1, strM1, Mid(astrCodEnd, 9, 3)) > 0 Then
                            dblCalcIlum = 20
                        ElseIf InStr(1, strM2, Mid(astrCodEnd, 9, 3)) > 0 Then
                            dblCalcIlum = 25
                        ElseIf InStr(1, strM3, Mid(astrCodEnd, 9, 3)) > 0 Then
                            dblCalcIlum = 30
                        ElseIf InStr(1, strM4, Mid(astrCodEnd, 9, 3)) > 0 Then
                            dblCalcIlum = 35
                        End If
                    End If
                End If

            Else

                strClas = Mid(astrClas, 1, 2)

                If CDbl(Mid(strClas, 1, 1)) <> 6 Then
                    intClas = Val(Mid(strClas, 1, 1))
                Else
                    intClas = Val(strClas)
                End If

                objCip.CIDADE = aintCidade
                objCip.CLASSE = intClas
                objCip.FAIXA_INI = adblConsumo
                objCip.FAIXA_FIM = adblConsumo

                vlist = repositorioCip.Select(objCip)

                If vlist.Count > 0 Then

                    For Each objCipFor As entidadeCip In vlist

                        strTipo = IIf(IsDBNull(objCipFor.TIPO), "F", objCipFor.TIPO)
                        dblIlum = IIf(IsDBNull(objCipFor.VALOR), 0, objCipFor.VALOR)
                        lngFxIni = IIf(IsDBNull(objCipFor.FAIXA_INI), 0, objCipFor.FAIXA_INI)
                        lngFxFim = IIf(IsDBNull(objCipFor.FAIXA_FIM), 0, objCipFor.FAIXA_FIM)

                        'caso for percentual
                        If UCase(strTipo) = "P" Then
                            If dblConsumo > lngFxFim Then
                                If istrSigla = "COORSEL" Then
                                    dblCalcIlum = Arredondar(lngFxFim * (dblIlum / 100), 2)
                                Else
                                    dblCalcIlum = Arredondar((lngFxFim * idblTarCons) * (dblIlum / 100), 2)
                                End If
                            Else
                                If istrSigla = "COORSEL" Then
                                    dblCalcIlum = Arredondar(dblConsumo * (dblIlum / 100), 2)
                                ElseIf istrSigla = "EFLJCL" Then
                                    If (adblConsumoLido < 50 And Microsoft.VisualBasic.Left(astrClas, 1) = "9") Or Microsoft.VisualBasic.Left(astrClas, 2) = "61" Then
                                        dblCalcIlum = 0
                                    Else
                                        dblCalcIlum = Arredondar(idblTotalVlrBaseCip * (dblIlum / 100), 2)
                                        If dblCalcIlum > 20 Then dblCalcIlum = 20
                                    End If
                                Else
                                    dblCalcIlum = Arredondar(idblTotalNota * (dblIlum / 100), 2)
                                End If
                            End If
                        ElseIf UCase(strTipo) = "F" Then
                            dblCalcIlum = Arredondar(dblIlum, 2) 'caso for valor
                        End If

                    Next

                Else
                    dblCalcIlum = 0
                End If


            End If


            If dblCalcIlum <> 0 Then
                GradeItensTarifab.Rows = GradeItensTarifab.Rows + 1
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 0, "0301000003")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 1, dblCalcIlum) 'Replace(dblCalcIlum, ".", ",")
                GradeItensTarifab.set_TextMatrix(GradeItensTarifab.Rows - 1, 2, "")

                idblTotalNota = idblTotalNota + dblCalcIlum
            End If

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub ComponentesFatura(ByVal Id_Unid As Integer, ByVal Id_Consumidor As Integer)

        Dim strTarifa As String
        Dim strCodigo As String
        Dim stritens As String
        Dim strclasse 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 vlist

        Dim vlist_1

        Dim objNfTransicao As New entidadeNfTransicao
        Dim repositorioNfTransicao As New repositorioNfTransicao

        Dim objComposicao As New entidadeComposicao
        Dim repositorioComposicao As New repositorioComposicao

        Try

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

            objNfTransicao.CONS_ID = Id_Consumidor
            objNfTransicao.UNID_ID = Id_Unid
            objNfTransicao.MESANO = istrMesAnoFat

            vlist = repositorioNfTransicao.Select_5(objNfTransicao)

            If vlist.Count > 0 Then

                For Each objNfTransicaoFor As entidadeNfTransicao In vlist

                    strTarifa = IIf(IsDBNull(objNfTransicaoFor.TA), "", objNfTransicaoFor.TA)
                    strclasse = IIf(IsDBNull(objNfTransicaoFor.CODCLAS), "", objNfTransicaoFor.CODCLAS)
                    stritens = IIf(IsDBNull(objNfTransicaoFor.ITENSSERV), "", objNfTransicaoFor.ITENSSERV)

                    If CDbl(Microsoft.VisualBasic.Left(strclasse, 1)) = 9 And CDbl(Microsoft.VisualBasic.Right(strclasse, 1)) <> 1 Then strTarifa = Microsoft.VisualBasic.Left(strTarifa, 5) & 2

                    objComposicao.TA = strTarifa
                    objComposicao.MESANO = istrMesAnoFat

                    vlist_1 = repositorioComposicao.Select(objComposicao)

                    If vlist_1.Count > 0 Then

                        For Each objComposicaoFor As entidadeComposicao In vlist


                            strCodigo = IIf(IsDBNull(objComposicaoFor.CODIGO), "", objComposicaoFor.CODIGO)
                            dblPEnergia = IIf(IsDBNull(objComposicaoFor.ENERGIA), 0, objComposicaoFor.ENERGIA)
                            dblPTransmissao = IIf(IsDBNull(objComposicaoFor.TRANSMISSAO), 0, objComposicaoFor.TRANSMISSAO)
                            dblPDistribuicao = IIf(IsDBNull(objComposicaoFor.DISTRIBUICAO), 0, objComposicaoFor.DISTRIBUICAO)
                            dblPEncSetoriais = IIf(IsDBNull(objComposicaoFor.ENC_SETORIAIS), 0, objComposicaoFor.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

                        Next

                    End If

                Next

            End If

            If dblVEnergia + dblVTransmissao + dblVDistribuicao + dblVEncSetoriais <> 0 Then

                objNfTransicao.CONS_ID = Id_Consumidor
                objNfTransicao.UNID_ID = Id_Unid
                objNfTransicao.MESANO = istrMesAnoFat
                objNfTransicao.ITENSSERV = "0302090001?" & Replace(Arredondar(dblVEnergia, 2), ",", ".") & ";0302090002?" & Replace(Arredondar(dblVTransmissao, 2), ",", ".") & ";0302090003?" & Replace(Arredondar(dblVDistribuicao, 2), ",", ".") & ";0302090004?" & Replace(Arredondar(dblVEncSetoriais, 2), ",", ".") & ";"

                lUpdate(objNfTransicao)

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Function lInsert(ByRef objNfTransicao As entidadeNfTransicao) As Boolean
        Dim repositorioNfTransicao As New repositorioNfTransicao
        Try

            repositorioNfTransicao.Insert(objNfTransicao)

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

    Private Function lInsert(ByRef objBxRendaFaturamento As entidadeBxRendaFaturamento) As Boolean
        Dim repositorioBxRendaFaturamento As New repositorioBxRendaFaturamento
        Try

            repositorioBxRendaFaturamento.Insert(objBxRendaFaturamento)

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

    Private Function lInsert(ByRef objConsumos As entidadeConsumos) As Boolean
        Dim repositorioConsumos As New repositorioConsumos
        Try

            repositorioConsumos.Insert_2(objConsumos)

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

    Private Function lInsert(ByRef objConvenios As entidadeConvenios) As Boolean
        Dim repositorioConvenios As New repositorioConvenios
        Try

            repositorioConvenios.Insert_1(objConvenios)

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

    Private Function lDelete(ByRef objMultaJuros As entidadeMultaJuros) As Boolean
        Dim repositorioMultaJuros As New repositorioMultaJuros
        Try

            repositorioMultaJuros.Delete(objMultaJuros)

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

    Private Function lDelete(ByRef objTempItemFatura As entidadeTempItemFatura) As Boolean
        Dim repositorioTempItemFatura As New repositorioTempItemFatura
        Try

            repositorioTempItemFatura.Delete(objTempItemFatura)

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

    Private Function lDelete(ByRef objTempItemFaturaB As entidadeTempItemFaturaB) As Boolean
        Dim repositorioTempItemFaturaB As New repositorioTempItemFaturaB
        Try

            repositorioTempItemFaturaB.Delete(objTempItemFaturaB)

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

    Private Function lUpdate(ByRef objConvenios As entidadeConvenios) As Boolean
        Dim repositorioConvenios As New repositorioConvenios
        Try

            repositorioConvenios.Update_1(objConvenios)

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

    Private Function lUpdate(ByRef objTaxas As entidadeTaxas) As Boolean
        Dim repositorioTaxas As New repositorioTaxas
        Try

            repositorioTaxas.Update_1(objTaxas)

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

    Private Function lUpdate(ByRef objMultaJuros As entidadeMultaJuros) As Boolean
        Dim repositorioMultaJuros As New repositorioMultaJuros
        Try

            repositorioMultaJuros.Update(objMultaJuros)

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

    Private Function lUpdate(ByRef objUCFaturamento As entidadeUCFaturamento) As Boolean
        Dim repositorioUCFaturamento As New repositorioUCFaturamento
        Try

            repositorioUCFaturamento.Update_8(objUCFaturamento)

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

    Private Function lUpdate(ByRef objNfTransicao As entidadeNfTransicao) As Boolean
        Dim repositorioNfTransicao As New repositorioNfTransicao
        Try

            repositorioNfTransicao.Update_1(objNfTransicao)

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

    Private Function lUpdate_1(ByRef objNfTransicao As entidadeNfTransicao) As Boolean
        Dim repositorioNfTransicao As New repositorioNfTransicao
        Try

            repositorioNfTransicao.Update_2(objNfTransicao)

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

    Private Function lUpdate_2(ByRef objNfTransicao As entidadeNfTransicao) As Boolean
        Dim repositorioNfTransicao As New repositorioNfTransicao
        Try

            repositorioNfTransicao.Update_3(objNfTransicao)

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

    Private Function lUpdate_3(ByRef objNfTransicao As entidadeNfTransicao) As Boolean
        Dim repositorioNfTransicao As New repositorioNfTransicao
        Try

            repositorioNfTransicao.Update_4(objNfTransicao)

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

    Private Function lUpdate(ByRef objSobreTaxa As entidadeSobreTaxa) As Boolean
        Dim repositorioSobreTaxa As New repositorioSobreTaxa
        Try

            repositorioSobreTaxa.Update(objSobreTaxa)

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



#End Region


End Class