Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports System.Collections.Generic
Imports fatd_faturamento.ENTIDADE
Imports fatd_faturamento.BLL.Repositorio
Imports System.Configuration
Imports CrystalDecisions.CrystalReports.Engine
Friend Class frmDeclaracaoQuitacao
	Inherits System.Windows.Forms.Form
	Dim gstrDataBase As String = moduleGlobal.vMySqlDataBase
	Private objAtualizaBancoDados As New entidadeAtualizaBancoDados
	Private repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados
	Private sNomeRelatorio As String
	Private sNomeEmpresa As String
	Private sEnderecoEmpresa As String
	Private sCepEmpresa As String
	Private sCidadeEmpresa As String
	Private sUFempresa As String
	Private sBairroEmpresa As String
	Private sFoneEmpresa As String
	Private sWebEmpresa As String
	Private sCpfCnpj As String
	Private sIE As String
	Private dt As DataTable
	Private dt1 As DataTable
	Private dt2 As DataTable
	Private dtinterno As DataTable
	Private Limagem As Byte()
	Private bQuitacao As Boolean

	Private Sub chkCortados_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkCortados.CheckStateChanged
		Try
			If Me.chkLigados.CheckState = 0 And Me.chkDesligados.CheckState = 0 Then
				Me.chkCortados.CheckState = System.Windows.Forms.CheckState.Checked
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkCortados_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub chkDesligados_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkDesligados.CheckStateChanged
		Try
			If Me.chkLigados.CheckState = 0 And Me.chkCortados.CheckState = 0 Then
				Me.chkDesligados.CheckState = System.Windows.Forms.CheckState.Checked
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkDesligados_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub chkFaturas_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkFaturas.CheckStateChanged
		Try
			Me.chkLigados.Enabled = (Me.chkFaturas.CheckState = 0)
			Me.chkCortados.Enabled = (Me.chkFaturas.CheckState = 0)
			Me.chkDesligados.Enabled = (Me.chkFaturas.CheckState = 0)
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkFaturas_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub chkLigados_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkLigados.CheckStateChanged
		Try
			If Me.chkCortados.CheckState = 0 And Me.chkDesligados.CheckState = 0 Then
				Me.chkLigados.CheckState = System.Windows.Forms.CheckState.Checked
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkLigados_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub chkRota_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkRota.CheckStateChanged
		Try
			If Me.chkRota.CheckState = 1 Then
				Me.lsvRotas.Enabled = True
				Call CarregaRotas()
			Else
				lsvRotas.Enabled = False
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkRota_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub chkZlc_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkZLC.CheckStateChanged
		Try
			Me.txtZona.Enabled = (chkZLC.CheckState = 1)
			Me.txtLivro.Enabled = (chkZLC.CheckState = 1)
			Me.txtConta.Enabled = (chkZLC.CheckState = 1)
			Me.txtConsId.Enabled = (chkZLC.CheckState = 1)
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkZlc_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click
		Call Me.Close()
	End Sub
	Private Sub cmdImprimir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImprimir.Click
		Try
			Dim lstrCriterio As String
			Call GravaTemp()
			sNomeRelatorio = "rptDeclaracaoDebito"

			Call sDadosEmpresa(Limagem, sNomeEmpresa, sEnderecoEmpresa, sCepEmpresa, sCidadeEmpresa, sUFempresa, sBairroEmpresa, sFoneEmpresa, sWebEmpresa, sCpfCnpj, sIE)

			Call lPrint(sNomeRelatorio)
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdImprimir_Click" & "", "Aviso de 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
		Dim ldteBase As Date
		Try
			ldteBase = Date.Now

			If Year(dtpAno.Value) = Year(ldteBase) Then
				Call MsgBox("Ano selecionado não pode ser o ano em exercício!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
			Else
				Me.cmdProcessar.Enabled = False
				Me.cmdImprimir.Enabled = False
				Call MontaGrande(0)
				Call MontaGrande(1)
				Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
				Call EncheGrade()
				Call AjustaDeclaracaoDebito()
				Me.Cursor = System.Windows.Forms.Cursors.Default
				Me.cmdProcessar.Enabled = True
				Me.cmdImprimir.Enabled = True
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdProcessar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub MontaGrande(ByVal aintAux As Short)

		Dim lsiItens As System.Windows.Forms.ListViewItem
		Dim clhColunas As System.Windows.Forms.ColumnHeader
		Dim clhColunas_Faturas As System.Windows.Forms.ColumnHeader
		Dim clhColunas_Pedentes As System.Windows.Forms.ColumnHeader

		Try
			If aintAux = 0 Then

				lsvDia.Items.Clear()
				lsvDia.Columns.Clear()

				If lsvDia.Columns.Count <= 1 Then
					clhColunas = lsvDia.Columns.Add("", "Seq.", CInt(VB6.TwipsToPixelsX(1900)))
					clhColunas = lsvDia.Columns.Add("", "Cod.Id.", CInt(VB6.TwipsToPixelsX(3200)))
					clhColunas = lsvDia.Columns.Add("", "Zona", CInt(VB6.TwipsToPixelsX(1100)))
					clhColunas = lsvDia.Columns.Add("", "Lvro", CInt(VB6.TwipsToPixelsX(1200)))
					clhColunas = lsvDia.Columns.Add("", "Conta", CInt(VB6.TwipsToPixelsX(2500)))
					clhColunas = lsvDia.Columns.Add("", "Rota/Seq.", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "Nome", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "uf", CInt(VB6.TwipsToPixelsX(1000)))

					clhColunas = lsvDia.Columns.Add("", "cep", CInt(VB6.TwipsToPixelsX(1900)))
					clhColunas = lsvDia.Columns.Add("", "cidade", CInt(VB6.TwipsToPixelsX(3200)))
					clhColunas = lsvDia.Columns.Add("", "distrito", CInt(VB6.TwipsToPixelsX(1100)))
					clhColunas = lsvDia.Columns.Add("", "bairro", CInt(VB6.TwipsToPixelsX(1200)))
					clhColunas = lsvDia.Columns.Add("", "end", CInt(VB6.TwipsToPixelsX(2500)))
					clhColunas = lsvDia.Columns.Add("", "num", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "complemento", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "quadra", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "lote", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "uf_ent", CInt(VB6.TwipsToPixelsX(1900)))
					clhColunas = lsvDia.Columns.Add("", "cep_ent", CInt(VB6.TwipsToPixelsX(3200)))
					clhColunas = lsvDia.Columns.Add("", "cid_ent", CInt(VB6.TwipsToPixelsX(1100)))
					clhColunas = lsvDia.Columns.Add("", "dis_ent", CInt(VB6.TwipsToPixelsX(1200)))
					clhColunas = lsvDia.Columns.Add("", "bai_ent", CInt(VB6.TwipsToPixelsX(2500)))
					clhColunas = lsvDia.Columns.Add("", "end_ent", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "num_ent", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "cpl_ent", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "qua_ent", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "lot_ent", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "cpf", CInt(VB6.TwipsToPixelsX(1900)))
					clhColunas = lsvDia.Columns.Add("", "rg", CInt(VB6.TwipsToPixelsX(3200)))
					clhColunas = lsvDia.Columns.Add("", "insc", CInt(VB6.TwipsToPixelsX(1100)))
					clhColunas = lsvDia.Columns.Add("", "fase", CInt(VB6.TwipsToPixelsX(1200)))
					clhColunas = lsvDia.Columns.Add("", "tensao", CInt(VB6.TwipsToPixelsX(2500)))
					clhColunas = lsvDia.Columns.Add("", "medidor", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "agrupa", CInt(VB6.TwipsToPixelsX(1000)))
					clhColunas = lsvDia.Columns.Add("", "ano", CInt(VB6.TwipsToPixelsX(1000)))

				End If

				lsvFaturas.Items.Clear()
				lsvFaturas.Columns.Clear()

				clhColunas_Faturas = lsvDia.Columns.Add("", "MêsAno", CInt(VB6.TwipsToPixelsX(1900)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "od.Id.", CInt(VB6.TwipsToPixelsX(3200)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Zona", CInt(VB6.TwipsToPixelsX(1100)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Livro", CInt(VB6.TwipsToPixelsX(1200)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Conta", CInt(VB6.TwipsToPixelsX(2500)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Numnf", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Valor", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Sit", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Venc", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Faturas = lsvDia.Columns.Add("", "Pag", CInt(VB6.TwipsToPixelsX(1000)))

			Else

				lsvPendentes.Items.Clear()
				lsvPendentes.Columns.Clear()

				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "MêsAno", CInt(VB6.TwipsToPixelsX(1900)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "od.Id.", CInt(VB6.TwipsToPixelsX(3200)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Zona", CInt(VB6.TwipsToPixelsX(1100)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Livro", CInt(VB6.TwipsToPixelsX(1200)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Conta", CInt(VB6.TwipsToPixelsX(2500)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Numnf", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Valor", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Sit", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Venc", CInt(VB6.TwipsToPixelsX(1000)))
				clhColunas_Pedentes = lsvPendentes.Columns.Add("", "Pag", CInt(VB6.TwipsToPixelsX(1000)))
			End If

			System.Windows.Forms.Application.DoEvents()

		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontaGrande" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub EncheGrade()
		Dim lblnExisteDivida As Boolean
		Dim lblnAux As Boolean
		Dim llngRow As Integer
		'Identificação
		Dim ldblNfA As Double
		Dim ldblNNf As Double
		Dim ldblVlr As Double
		Dim lstrMAn As String
		Dim ldtePag As Date
		Dim ldteVec As Date
		Dim llngIdC As Integer
		Dim llngIdU As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim lstrGTa As String
		Dim lstrFlg As String
		Dim lstrRot As String
		Dim lstrNom As String
		'Endereço
		Dim lstrUf As String
		Dim lstrCep As String
		Dim lstrCid As String
		Dim lstrDis As String
		Dim lstrBai As String
		Dim lstrEnd As String
		Dim lstrNum As String
		Dim lstrCpl As String
		Dim lstrQua As String
		Dim lstrLot As String
		'Endereço de Entrega
		Dim lstrUfE As String
		Dim lstrCepE As String
		Dim lstrCidE As String
		Dim lstrDisE As String
		Dim lstrBaiE As String
		Dim lstrEnde As String
		Dim lstrNumE As String
		Dim lstrCplE As String
		Dim lstrQuaE As String
		Dim lstrLote As String
		'Documentos
		Dim lstrCpfCnpj As String
		Dim lstrRg As String
		Dim lstrInsc As String
		'Medição
		Dim lstrMedi As String
		Dim lstrFase As String
		Dim lstrTens As String
		'Outros
		Dim lstrAgrupa As String
		'Comandos
		Dim ldteIni As Date
		Dim ldteFim As Date
		Dim lintLin As Short
		Dim lstrFRt As String
		Dim lstrAux As String
		Dim lstrSql As String

		Try

			Me.lblInfo.Text = " Buscando as unidades aguarde.... "
			Call Me.lblInfo.Refresh()

			ldteIni = CDate("01/01/" & Year(dtpAno.Value))
			ldteFim = CDate("31/12/" & Year(dtpAno.Value))

			lstrAux = ""
			lstrFRt = ""
			If Me.chkRota.CheckState = 1 Then
				With Me.lsvRotas
					If .Items.Count > 0 Then
						If .Items.Item(1).Checked = False Then
							For lintLin = 2 To .Items.Count - 1
								If .Items.Item(lintLin).Checked = True Then
									lstrAux = lstrAux & """" & .Items.Item(lintLin).Text & ""","
								End If
							Next lintLin
						End If
					End If
				End With
			End If
			If Len(Trim(lstrAux)) > 0 Then
				lstrFRt = " AND MID(`uc`.`rota`, 1, 4) IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
			End If
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `uc`.`rota`,         " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`zona`,         " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`livro`,        " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`conta`,        " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`cons_id`,      " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`id`,      " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`nome`,         " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`uf`,           " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`cep`,          " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`cidade`,       " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`distrito`,     " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`bairro`,       " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`end`,          " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`numero`,       " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`complement`,   " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`quadra`,       " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`lote`,         " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`uf_entrega`,   " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`cep_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`cid_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`dis_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`bai_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`end_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`num_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`compl_entrega`," & vbCrLf
			lstrSql = lstrSql & "       `uc`.`qua_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`lot_entrega`,  " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`cpf_cnpj`,     " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`rg`,           " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`insc`,         " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`fase`,         " & vbCrLf
			lstrSql = lstrSql & "       `uc`.`tensao`,      " & vbCrLf
			If Me.opbGrupoB.Checked Then
				lstrSql = lstrSql & "       `uc`.`num` AS `medidor`, " & vbCrLf
				lstrSql = lstrSql & "       `uc`.`agrupa` AS `agrupa` " & vbCrLf
			Else
				lstrSql = lstrSql & "       `uc`.`eletr` AS `medidor`, " & vbCrLf
				lstrSql = lstrSql & "       0            AS `agrupa`   " & vbCrLf
			End If
			lstrSql = lstrSql & "  FROM `uc_faturamento` AS `uc` " & vbCrLf
			lstrSql = lstrSql & " WHERE 1 = 1 "
			If Me.chkZLC.CheckState = 1 Then
				lstrSql = lstrSql & "   AND `uc`.`zona`  = """ & Me.txtZona.Text & """ "
				lstrSql = lstrSql & "   AND `uc`.`livro` = """ & Me.txtLivro.Text & """ "
				lstrSql = lstrSql & "   AND `uc`.`conta` = """ & Me.txtConta.Text & """ "
			End If
			If Me.chkFaturas.CheckState = 0 Then
				lstrSql = lstrSql & vbCrLf & "   AND `uc`.`situacao` IN("
				If Me.chkLigados.CheckState = 1 Then
					lstrSql = lstrSql & "'L',"
				End If
				If Me.chkCortados.CheckState = 1 Then
					lstrSql = lstrSql & "'C',"
				End If
				If Me.chkDesligados.CheckState = 1 Then
					lstrSql = lstrSql & "'D' "
				End If
				lstrSql = VB.Left(lstrSql, Len(lstrSql) - 1) & ")"
			End If
			lstrSql = lstrSql & " AND LEFT(`uc`.`grupo`, 1) = " & If(opbGrupoB.Checked, "'B'", "'A'")
			lstrSql = lstrSql & " AND NOT EXISTS(SELECT * FROM declaracao_debito db WHERE db.zona = uc.zona AND db.livro = uc.livro AND db.conta = uc.conta AND db.cons_id = uc.cons_id AND db.ano = " & VB6.Format(Me.dtpAno.Value, "yyyy") & ")"
			lstrSql = lstrSql & lstrFRt & " ORDER BY `rota` ASC, `zona` ASC, `livro` ASC, `conta` ASC "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			If dt.Rows.Count <> 0 Then
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, dt.Rows.Count)
				For Each row As DataRow In dt.Rows
					'Identificação
					lstrRot = Trim(IIf(IsDBNull(row("rota")), "", row("rota")))
					lstrZon = Trim(IIf(IsDBNull(row("zona")), "", row("zona")))
					lstrLiv = Trim(IIf(IsDBNull(row("livro")), "", row("livro")))
					lstrCon = Trim(IIf(IsDBNull(row("conta")), "", row("conta")))
					llngIdC = CInt(IIf(IsDBNull(row("cons_id")), 0, row("cons_id")))
					llngIdU = CInt(IIf(IsDBNull(row("id")), 0, row("id")))
					'If gstrEmpresa_Sigla = "EFLUL" Then
					'  lstrRot = Format(Right(lstrRot, 6), "00000000")
					'End If
					lstrNom = Trim(IIf(IsDBNull(row("nome")), "", row("nome")))
					'Endereço
					lstrUf = Trim(IIf(IsDBNull(row("uf")), "", row("uf")))
					lstrCep = Trim(IIf(IsDBNull(row("cep")), "", row("cep")))
					lstrCid = Trim(IIf(IsDBNull(row("cidade")), "", row("cidade")))
					lstrDis = Trim(IIf(IsDBNull(row("distrito")), "", row("distrito")))
					lstrBai = Trim(IIf(IsDBNull(row("bairro")), "", row("bairro")))
					lstrEnd = Trim(IIf(IsDBNull(row("end")), "", row("end")))
					lstrNum = Trim(IIf(IsDBNull(row("numero")), "", row("numero")))
					lstrCpl = Trim(IIf(IsDBNull(row("complement")), "", row("complement")))
					lstrQua = Trim(IIf(IsDBNull(row("quadra")), "", row("quadra")))
					lstrLot = Trim(IIf(IsDBNull(row("lote")), "", row("lote")))
					'Entrega
					lstrUfE = Trim(IIf(IsDBNull(row("uf_entrega")), "", row("uf_entrega")))
					lstrCepE = Trim(IIf(IsDBNull(row("cep_entrega")), "", row("cep_entrega")))
					lstrCidE = Trim(IIf(IsDBNull(row("cid_entrega")), "", row("cid_entrega")))
					lstrDisE = Trim(IIf(IsDBNull(row("dis_entrega")), "", row("dis_entrega")))
					lstrBaiE = Trim(IIf(IsDBNull(row("bai_entrega")), "", row("bai_entrega")))
					lstrEnde = Trim(IIf(IsDBNull(row("end_entrega")), "", row("end_entrega")))
					lstrNumE = Trim(IIf(IsDBNull(row("num_entrega")), "", row("num_entrega")))
					lstrCplE = Trim(IIf(IsDBNull(row("compl_entrega")), "", row("compl_entrega")))
					lstrQuaE = Trim(IIf(IsDBNull(row("qua_entrega")), "", row("qua_entrega")))
					lstrLote = Trim(IIf(IsDBNull(row("lot_entrega")), "", row("lot_entrega")))
					'Documentos
					lstrCpfCnpj = Trim(IIf(IsDBNull(row("cpf_cnpj")), "", row("cpf_cnpj")))
					lstrRg = Trim(IIf(IsDBNull(row("rg")), "", row("rg")))
					lstrInsc = Trim(IIf(IsDBNull(row("insc")), "", row("insc")))
					'Medição
					lstrFase = Trim(IIf(IsDBNull(row("fase")), "", row("fase")))
					lstrTens = Trim(IIf(IsDBNull(row("tensao")), "", row("tensao")))
					lstrMedi = Trim(IIf(IsDBNull(row("medidor")), "", row("medidor")))
					lstrAgrupa = Trim(IIf(IsDBNull(row("agrupa")), "", row("agrupa")))
					lblnExisteDivida = False


					lstrSql = ""
					lstrSql = lstrSql & "SELECT cons_id "
					lstrSql = lstrSql & "  FROM `nf` USE INDEX(keyflgst, keyzona, keylivro, keyconta, keycons) "
					lstrSql = lstrSql & " WHERE `nf`.`flgst` NOT IN('P','C') "
					lstrSql = lstrSql & "   AND `nf`.`cons_id` = " & llngIdC & " "
					lstrSql = lstrSql & "   AND `nf`.`zona` = '" & lstrZon & "'"
					lstrSql = lstrSql & "   AND `nf`.`livro` = '" & lstrLiv & "' "
					lstrSql = lstrSql & "   AND `nf`.`conta` = '" & lstrCon & "' "
					'lstrSql = lstrSql & "   AND `nf`.`anomes_fat` BETWEEN"
					lstrSql = lstrSql & "   AND (`nf`.`datavenc` BETWEEN '" & VB6.Format(ldteIni, "yyyy-MM-dd") & "' AND '" & VB6.Format(ldteFim, "yyyy-MM-dd") & "') "
					lstrSql = lstrSql & " LIMIT 0, 1 "
					objAtualizaBancoDados.QUERY_NAME = lstrSql
					dt1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

					If dt1.Rows.Count <> 0 Then
						For Each row1 As DataRow In dt1.Rows
							lblnExisteDivida = True
							'Close()
						Next
					Else
						'Close()
					End If

					dt1 = Nothing

					If Not lblnExisteDivida Then
						lstrSql = ""
						lstrSql = lstrSql & "SELECT "
						lstrSql = lstrSql & "       `nfp`.`numnf`,    " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`mesano`,   " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`mesano_ref`, " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`datavenc`, " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`datapag`,  " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`datast`,   " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`valortot`, " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`valorliq`, " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`ta`,       " & vbCrLf
						lstrSql = lstrSql & "       `nfp`.`flgst`     " & vbCrLf
						lstrSql = lstrSql & "  FROM `nf` AS `nfp` USE INDEX(keyzona, keylivro, keyconta)  " & vbCrLf
						lstrSql = lstrSql & "  WHERE (`nfp`.`datavenc` BETWEEN '" & VB6.Format(ldteIni, "yyyy-MM-dd") & "' AND '" & VB6.Format(ldteFim, "yyyy-MM-dd") & "') "
						'lstrSql = lstrSql & " WHERE `nfp`.`datavenc` <= '" & VB6.Format(ldteFim, "yyyy-MM-dd") & "' " & vbCrLf
						lstrSql = lstrSql & "   AND (`nfp`.`flgst` <> 'C' OR (`nfp`.`flgst` = 'C' AND `nfp`.`datast` > '" & VB6.Format(ldteFim, "yyyy-MM-dd") & "')) " & vbCrLf
						lstrSql = lstrSql & "   AND `nfp`.`zona`  = '" & lstrZon & "' " & vbCrLf
						lstrSql = lstrSql & "   AND `nfp`.`livro` = '" & lstrLiv & "' " & vbCrLf
						lstrSql = lstrSql & "   AND `nfp`.`conta` = '" & lstrCon & "' " & vbCrLf

						If Me.opbGrupoA.Checked Then
							lstrSql = lstrSql & "   AND `nfp`.`grupo` = 'A' " & vbCrLf
						ElseIf Me.opbGrupoB.Checked Then
							lstrSql = lstrSql & "   AND `nfp`.`grupo` = 'B' " & vbCrLf
						End If

						lstrSql = lstrSql & " ORDER BY `mesano_ref` ASC "
						objAtualizaBancoDados.QUERY_NAME = lstrSql
						dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

						If dt2.Rows.Count > 0 Then
							Call BarraProgresso((Me.ProgressBarF), (Me.lblPrecF), (Me.lblInfoF), 0, dt2.Rows.Count)

							For Each row2 As DataRow In dt2.Rows
								lstrFlg = Trim(IIf(IsDBNull(row2("flgst")), "", row2("flgst")))
								lstrGTa = Trim(IIf(IsDBNull(row2("ta")), "01B1", row2("ta")))
								ldblNNf = CDbl(IIf(IsDBNull(row2("numnf")), 0, row2("numnf")))
								lstrMAn = Trim(IIf(IsDBNull(row2("mesano")), "", row2("mesano")))
								ldblVlr = CDbl(IIf(IsDBNull(row2("valorliq")), 0, row2("valorliq")))
								If ldblVlr <= 0 Then
									ldblVlr = CDbl(IIf(IsDBNull(row2("valortot")), 0, row2("valortot")))
								End If
								ldtePag = CDate(IIf(IsDBNull(row2("datapag")), "1900-01-01", row2("datapag")))
								ldteVec = CDate(IIf(IsDBNull(row2("datavenc")), "1900-01-01", row2("datavenc")))
								lblnAux = False
								If JaExisteReg(llngIdC, lstrZon, lstrLiv, lstrCon, Year(ldteVec), 1, ldblNNf, lstrMAn) = False Then
									If Me.chkFaturas.CheckState = 1 Then

										Call JaExisteGrade_Quitacao(0, llngIdC, lstrZon, lstrLiv, lstrCon, 0, "")
										If bQuitacao Then
											lblnAux = True
										End If

										Call JaExisteGrade_Quitacao(1, llngIdC, lstrZon, lstrLiv, lstrCon, 0, VB.Right(lstrMAn, 4))
										If bQuitacao Then
											lblnAux = True
										Else
											lblnAux = ExisteFat(lstrZon, lstrLiv, lstrCon)
										End If

									Else
										lblnAux = True
									End If
									If lblnAux Then
										If lstrFlg = "" Or lstrFlg = "R" Then

											'[ Adiciona na Grade dos Pendentes ]
											Call JaExisteGrade_Quitacao(0, llngIdC, lstrZon, lstrLiv, lstrCon, 0, "")
											If bQuitacao = False Then
												With Me.lsvPendentes
													.Items.Add(llngIdC)
													.Items.Item(.Items.Count - 1).SubItems.Add(llngIdC)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrZon)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrLiv)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCon)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrRot)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrNom)
												End With
											End If

										Else

											'[ Adiciona na Grade dos Em Dia ]
											Call JaExisteGrade_Quitacao(1, llngIdC, lstrZon, lstrLiv, lstrCon, 0, CStr(Year(ldteVec)))
											If bQuitacao = False Then

												With Me.lsvDia
													.Items.Add(llngIdC)
													.Items.Item(.Items.Count - 1).SubItems.Add(llngIdC)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrZon)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrLiv)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCon)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrRot)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrNom)
													'	'Endereço
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrUf)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCep)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCid)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrDis)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrBai)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrEnd)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrNum)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCpl)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrQua)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrLot)
													'Entrega
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrUfE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCepE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCidE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrDisE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrBaiE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrEnde)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrNumE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCplE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrQuaE)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrLote)
													'Documentos
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCpfCnpj)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrRg)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrInsc)
													'Medição
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrFase)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrTens)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrMedi)
													'Outros
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrAgrupa)
													.Items.Item(.Items.Count - 1).SubItems.Add(Year(ldteVec))
												End With
											End If

											Call JaExisteGrade_Quitacao(2, llngIdC, lstrZon, lstrLiv, lstrCon, ldblNNf, lstrMAn)
											If bQuitacao = False Then
												With Me.lsvFaturas
													.Items.Add(lstrMAn)
													.Items.Item(.Items.Count - 1).SubItems.Add(llngIdC)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrZon)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrLiv)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrCon)
													.Items.Item(.Items.Count - 1).SubItems.Add(ldblNNf)
													.Items.Item(.Items.Count - 1).SubItems.Add(ldblVlr)
													.Items.Item(.Items.Count - 1).SubItems.Add(lstrFlg)
													.Items.Item(.Items.Count - 1).SubItems.Add(ldteVec)
													.Items.Item(.Items.Count - 1).SubItems.Add(ldtePag)
												End With

											End If 'JaExiteGrade
										End If 'flgst
									End If 'lblAUx
								End If 'Existe Fatura
								Call BarraProgresso((Me.ProgressBarF), (Me.lblPrecF), (Me.lblInfoF), 1,  , " faturas")
							Next
						Else
						End If
						dt2 = Nothing
					End If

					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1,  , " unidades")
					Call ValidaDadosGrade()
					Call GravaDeclaracao()
				Next
			Else
				'Close()
			End If

			dt = Nothing

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

	Private Sub ValidaDadosGrade()
		Dim llngRow As Integer
		Dim llngIdC As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Try

			'[ Remove da Grade dos Em Dia os que estao na Grade dos Pendentes ]
			'With Me.mfgPendentes
			'	If .Rows > 1 Then
			'		.Col = 5
			'		.Sort = MSFlexGridLib.SortSettings.flexSortGenericAscending
			'		Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 0, .Rows - 1)
			'		For llngRow = 1 To .Rows - 1
			'			.set_TextMatrix(llngRow, 0, llngRow)
			'			llngIdC = CInt(.get_TextMatrix(.Rows - 1, 1))
			'			lstrZon = .get_TextMatrix(.Rows - 1, 2)
			'			lstrLiv = .get_TextMatrix(.Rows - 1, 3)
			'			lstrCon = .get_TextMatrix(.Rows - 1, 4)
			'			Call Retira(llngIdC, lstrZon, lstrLiv, lstrCon)
			'			Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 1,  , " validação")
			'		Next llngRow
			'	End If
			'End With

			With Me.lsvPendentes
				If .Items.Count > 0 Then
					Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 0, .Items.Count - 1)
					For llngRow = 0 To .Items.Count - 1
						.Items.Item(llngRow).SubItems.Add(llngRow)
						llngIdC = CInt(.Items.Item(llngRow - 1).SubItems.Item(1).Text)
						lstrZon = .Items.Item(llngRow - 1).SubItems.Item(2).Text
						lstrLiv = .Items.Item(llngRow - 1).SubItems.Item(3).Text
						lstrCon = .Items.Item(llngRow - 1).SubItems.Item(4).Text

						If llngIdC > 0 Then
							Call Retira(llngIdC, lstrZon, lstrLiv, lstrCon)
							Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 1,  , " validação")
						End If

					Next llngRow
				End If
			End With

			'With Me.mfgEmDia
			'	If .Rows > 1 Then
			'		.Col = 5
			'		.Sort = MSFlexGridLib.SortSettings.flexSortGenericAscending
			'		For llngRow = 1 To .Rows - 1
			'			.set_TextMatrix(llngRow, 0, llngRow)
			'		Next llngRow
			'	End If
			'End With

			With Me.lsvDia
				If .Items.Count > 0 Then
					For llngRow = 0 To .Items.Count - 1
						.Items.Item(llngRow).SubItems.Add(llngRow)
					Next llngRow
				End If
			End With

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

	'[ Função para verificar se a unidade consumidora já esta na Grade dos Pendentes ]
	'Private Function JaExisteGrade(ByVal amfgAux As AxMSFlexGridLib.AxMSFlexGrid, ByVal alngIdC As Integer, ByVal astrZon As String, ByVal astrLiv As String, ByVal astrCon As String, Optional ByVal adblNNf As Double = 0, Optional ByVal astrMAn As String = "") As Boolean
	'	Dim llngIdC As Integer
	'	Dim lstrZon As String
	'	Dim lstrLiv As String
	'	Dim lstrCon As String
	'	Dim ldblNNf As Double
	'	Dim lstrMAn As String
	'	Dim llngRow As Integer
	'	Dim lstrCons_id As String
	'	Try
	'		JaExisteGrade = False
	'		With amfgAux
	'			For llngRow = 1 To .Rows - 1
	'				llngIdC = CInt(.get_TextMatrix(llngRow, 1))
	'				lstrZon = .get_TextMatrix(llngRow, 2)
	'				lstrLiv = .get_TextMatrix(llngRow, 3)
	'				lstrCon = .get_TextMatrix(llngRow, 4)
	'				If Len(Trim(astrMAn)) > 0 Then
	'					If Len(Trim(astrMAn)) = 7 Then
	'						lstrMAn = .get_TextMatrix(llngRow, 0)
	'						ldblNNf = CDbl(.get_TextMatrix(llngRow, 5))
	'						If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon And lstrMAn = astrMAn And ldblNNf = adblNNf Then
	'							JaExisteGrade = True
	'							llngRow = .Rows - 1
	'						End If
	'					ElseIf Len(Trim(astrMAn)) = 4 Then
	'						lstrMAn = .get_TextMatrix(llngRow, 34)
	'						If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon And lstrMAn = astrMAn Then
	'							JaExisteGrade = True
	'							llngRow = .Rows - 1
	'						End If
	'					End If
	'				Else
	'					If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon Then
	'						JaExisteGrade = True
	'						llngRow = .Rows - 1
	'					End If
	'				End If
	'			Next llngRow
	'		End With
	'	Catch ex As Exception
	'		MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: JaExisteGrade" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
	'		Exit Function
	'	End Try
	'End Function

	'[OK]
	'[ Função para retirar a unidade consumidora da Grade dos Em Dia ]
	Private Sub Retira(ByVal alngIdC As Integer, ByVal astrZon As String, ByVal astrLiv As String, ByVal astrCon As String)
		Dim llngIdC As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim llngRow As Integer
		Dim llngTot As Integer
		Dim lstrCons_id As String
		Try

			With Me.lsvDia
				llngTot = .Items.Count - 1
				For llngRow = 1 To llngTot
					llngIdC = CInt(.Items.Item(llngRow).SubItems.Item(1).Text)
					lstrZon = .Items.Item(llngRow).SubItems.Item(2).Text
					lstrLiv = .Items.Item(llngRow).SubItems.Item(3).Text
					lstrCon = .Items.Item(llngRow).SubItems.Item(4).Text

					If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon Then
						If .Items.Count > 1 Then
							If .Items.Count > 2 Then
								.Items.Item(llngRow).Remove()
								'Call  '.RemoveItem(llngRow)
							Else
								Call MontaGrande(0)
							End If
						End If
						llngRow = llngTot
					End If
				Next llngRow
			End With


			With Me.lsvFaturas
				llngTot = .Items.Count - 1
				For llngRow = 1 To llngTot
					llngIdC = CInt(.Items.Item(llngRow).SubItems.Item(1).Text)
					lstrZon = .Items.Item(llngRow).SubItems.Item(2).Text
					lstrLiv = .Items.Item(llngRow).SubItems.Item(3).Text
					lstrCon = .Items.Item(llngRow).SubItems.Item(4).Text
					If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon Then
						If .Items.Count > 1 Then
							If .Items.Count > 2 Then
								.Items.Item(llngRow).Remove()
								'''Call .RemoveItem(llngRow)
							Else
								Call MontaGrande(0)
							End If
						End If
						llngRow = llngTot
					End If
				Next llngRow
			End With


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

	'[OK]
	Private Sub frmDeclaracaoQuitacao_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
		Try
			Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
			If KeyAscii = System.Windows.Forms.Keys.Escape Then
				Call cmdFechar_Click(cmdFechar, New System.EventArgs())
			ElseIf KeyAscii = System.Windows.Forms.Keys.Return Then
				TabEnter(KeyAscii, eventArgs)
			End If
			eventArgs.KeyChar = Chr(KeyAscii)
			If KeyAscii = 0 Then
				eventArgs.Handled = True
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmDeclaracaoQuitacao_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub frmDeclaracaoQuitacao_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Try
			Dim lstrSql As String

			Me.dtpAno.Value = Date.Now
			Me.dtpFaturas.Text = Me.dtpAno.Value

			Call MontaGrande(0)
			Call MontaGrande(1)
			Call MontalstRota()
			Call sCriaTabelaAuxiliar()

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

	End Sub

	'[OK]
	Private Sub lsvRotas_ItemCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ItemCheckEventArgs) Handles lsvRotas.ItemCheck
		Dim aListItem As System.Windows.Forms.ListViewItem = lsvRotas.Items(eventArgs.Index)
		Dim lintLinhas As Short
		Try
			With Me.lsvRotas
				If aListItem.Text = "Todas as rotas" Then
					If .Items.Item(1).Checked = True Then
						For lintLinhas = 1 To .Items.Count - 1
							.Items.Item(lintLinhas).Checked = True
						Next lintLinhas
					ElseIf .Items.Item(1).Checked = False Then
						For lintLinhas = 1 To .Items.Count - 1
							.Items.Item(lintLinhas).Checked = False
						Next lintLinhas
					End If
				Else
					If aListItem.Checked = False Then
						.Items.Item(1).Checked = False
					End If
				End If
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lsvRotas_ItemCheck" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'[OK]
	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 o Erro: " & Err.Description & " - Rotina: txtZona_Enter" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'[OK]
	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 o Erro: " & Err.Description & " - Rotina: txtLivro_Enter" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'[OK]
	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 o Erro: " & Err.Description & " - Rotina: txtConta_Enter" & "", "Aviso de 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
			With Me.txtZona
				.Text = VB6.Format(.Text, "000")
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtZona_Leave" & "", "Aviso de 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
			With Me.txtLivro
				.Text = VB6.Format(.Text, "00")
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtLivro_Leave" & "", "Aviso de 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
			With Me.txtConta
				.Text = VB6.Format(.Text, "000000")
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtConta_Leave" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub MontalstRota()
		Try
			With Me.lsvRotas
				Call .Items.Clear()
				Call .Columns.Clear()
				If .Columns.Count <= 1 Then
					Call .Columns.Add("", "Rota", CInt(VB6.TwipsToPixelsX(1800)))
					Call .Columns.Add("Grupo", CInt(VB6.TwipsToPixelsX(650)), System.Windows.Forms.HorizontalAlignment.Center)
				End If
				Call .Items.Add("Todas as rotas")
				Call .Items.Item(.Items.Count - 1).SubItems.Add("T")
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontalstRota" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try

	End Sub
	Private Sub CarregaRotas()
		Dim lstrRot As String
		Dim lstrGru As String
		Dim lstrSql As String
		Dim strataRota As String


		Try
			' ----- Monta as colunas na ListView de rotas
			Call MontalstRota()
			' ----- Busca as rotas
			lstrSql = ""
			lstrSql = lstrSql & "SELECT DISTINCT `rota` AS `rotagrupo`, MID(`u`.`ta`,3,1) AS `grupo` "
			lstrSql = lstrSql & "  FROM `uc_faturamento` AS `u` USE INDEX(idx_rota) "
			lstrSql = lstrSql & " WHERE `u`.situacao = ""L"" "
			lstrSql = lstrSql & " UNION "
			lstrSql = lstrSql & "SELECT DISTINCT `rota` AS `rotagrupo`, MID(`u`.`ta`,3,1) AS `grupo`  "
			lstrSql = lstrSql & "  FROM `uc_faturamento` AS `u` USE INDEX(idx_rota, idx_zona, idx_livro, idx_conta)   "
			lstrSql = lstrSql & " WHERE `u`.situacao = ""L"" "
			lstrSql = lstrSql & " GROUP BY 1, 2 "
			lstrSql = lstrSql & " ORDER BY 2 ASC, 1 ASC"
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


			If dt.Rows.Count <> 0 Then
				For Each row As DataRow In dt.Rows
					strataRota = IIf(IsDBNull(row("rotagrupo")), "0", row("rotagrupo"))
					strataRota = Mid(strataRota, 1, 4)

					lstrRot = VB6.Format(IIf(IsDBNull(strataRota), "0", strataRota), "0000")
					lstrGru = UCase(Trim(IIf(IsDBNull(row("grupo")), "B", row("grupo"))))
					With Me.lsvRotas
						Call .Items.Add(lstrRot)
						Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrGru)
					End With
				Next
			Else
				'Close()
			End If

			dt = Nothing

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

	End Sub

	Private Sub GravaDeclaracao()
		Dim lintIns As Short
		Dim lstrIns As String
		Dim lstrIn1 As String
		Dim llngRow As Integer

		Try
			With Me.lsvDia
				If .Items.Count > 0 Then
					Me.lblInfoG.Text = " Gravando as declarações aguarde... "
					Call Me.lblInfoG.Refresh()
					lintIns = 0
					lstrIns = ""
					lstrIn1 = ""
					lstrIns = lstrIns & "INSERT INTO `declaracao_debito` ( "
					'Identificação
					lstrIns = lstrIns & "`ano`, "
					lstrIns = lstrIns & "`cons_id`, "
					lstrIns = lstrIns & "`zona`, "
					lstrIns = lstrIns & "`livro`, "
					lstrIns = lstrIns & "`conta`, "
					lstrIns = lstrIns & "`rota`, "
					lstrIns = lstrIns & "`nome`, "
					'Endereço
					lstrIns = lstrIns & "`uf`, "
					lstrIns = lstrIns & "`cep`, "
					lstrIns = lstrIns & "`cidade`, "
					lstrIns = lstrIns & "`distrito`, "
					lstrIns = lstrIns & "`bairro`, "
					lstrIns = lstrIns & "`end`, "
					lstrIns = lstrIns & "`numero`, "
					lstrIns = lstrIns & "`comple`, "
					lstrIns = lstrIns & "`quadra`, "
					lstrIns = lstrIns & "`lote`, "
					'Entrega
					lstrIns = lstrIns & "`uf_entrega`, "
					lstrIns = lstrIns & "`cep_entrega`, "
					lstrIns = lstrIns & "`cid_entrega`, "
					lstrIns = lstrIns & "`dis_entrega`, "
					lstrIns = lstrIns & "`bai_entrega`, "
					lstrIns = lstrIns & "`end_entrega`, "
					lstrIns = lstrIns & "`num_entrega`, "
					lstrIns = lstrIns & "`compl_entrega`, "
					lstrIns = lstrIns & "`qua_entrega`, "
					lstrIns = lstrIns & "`lot_entrega`, "
					'Documentos
					lstrIns = lstrIns & "`cpf`, "
					lstrIns = lstrIns & "`rg`, "
					lstrIns = lstrIns & "`insc`, "
					'Medição
					lstrIns = lstrIns & "`fase`, "
					lstrIns = lstrIns & "`tensao`, "
					lstrIns = lstrIns & "`medidor`, "
					'Outros
					lstrIns = lstrIns & "`agrupa` "
					lstrIns = lstrIns & ") VALUES "
					Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 0, .Items.Count - 1)


					For llngRow = 0 To .Items.Count - 1

						If JaExisteReg(CInt(.Items.Item(llngRow).SubItems.Item(1).Text), .Items.Item(llngRow).SubItems.Item(2).Text, .Items.Item(llngRow).SubItems.Item(3).Text, .Items.Item(llngRow).SubItems.Item(4).Text, CShort(.Items.Item(llngRow).SubItems.Item(34).Text), 0) = False Then
							lintIns = lintIns + 1
							'Identificação
							lstrIn1 = lstrIn1 & "( " & CInt(.Items.Item(llngRow).SubItems.Item(34).Text) & ", "
							lstrIn1 = lstrIn1 & CInt(.Items.Item(llngRow).SubItems.Item(1).Text) & ", " 'cons_id
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(2).Text & """, " 'zona
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(3).Text & """, " 'livro
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(4).Text & """, " 'conta
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(5).Text & """, " 'rota
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(6).Text & """, " 'nome
							'Endereço
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(7).Text & """, " 'uf
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(8).Text & """, " 'cep
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(9).Text & """, " 'cidade
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(10).Text & """, " 'distrito
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(11).Text & """, " 'bairro
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(12).Text & """, " 'end
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(13).Text & """, " 'numero
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(14).Text & """, " 'comple
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(15).Text & """, " 'quadra
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(16).Text & """, " 'lote
							'Entrega
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(17).Text & """, " 'uf
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(18).Text & """, " 'cep
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(19).Text & """, " 'cidade
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(20).Text & """, " 'distrito
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(21).Text & """, " 'bairro
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(22).Text & """, " 'end
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(23).Text & """, " 'numero
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(24).Text & """, " 'comple
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(25).Text & """, " 'quadra
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(26).Text & """, " 'lote
							'Documento
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(27).Text & """, " 'cpf
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(28).Text & """, " 'rg
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(29).Text & """, " 'insc
							'Medição
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(30).Text & """, " 'fase
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(31).Text & """, " 'tensao
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(32).Text & """, " 'medidor
							'Outros
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(33).Text & """), " 'agrupa

							If lintIns = 300 Then

								objAtualizaBancoDados.QUERY_NAME = lstrIns & VB.Left(lstrIn1, Len(lstrIn1) - 2)
								repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

								lstrIn1 = ""
								lintIns = 0
							Else
								lstrIn1 = lstrIn1 & vbCrLf
							End If

						End If
						Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 1)
					Next llngRow

					If Len(Trim(lstrIn1)) > 0 Then
						objAtualizaBancoDados.QUERY_NAME = lstrIns & VB.Left(lstrIn1, Len(lstrIn1) - 4)
						repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
					End If

				End If
			End With

			With Me.lsvFaturas
				If .Items.Count > 1 Then
					Me.lblInfoG.Text = " Gravando as faturas aguarde... "
					Call Me.lblInfoG.Refresh()
					lintIns = 0
					lstrIns = ""
					lstrIn1 = ""
					lstrIns = lstrIns & "INSERT INTO `declaracao_debito_faturas` ( "
					'Identificação
					lstrIns = lstrIns & "`numnf`, "
					lstrIns = lstrIns & "`mesano`, "
					lstrIns = lstrIns & "`ano`, "
					lstrIns = lstrIns & "`datavenc`, "
					lstrIns = lstrIns & "`datapag`, "
					lstrIns = lstrIns & "`valor`, "
					lstrIns = lstrIns & "`cons_id`, "
					lstrIns = lstrIns & "`zona`, "
					lstrIns = lstrIns & "`livro`, "
					lstrIns = lstrIns & "`conta` "
					lstrIns = lstrIns & ") VALUES "
					Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 0, .Items.Count - 1)
					For llngRow = 1 To .Items.Count - 1
						If JaExisteReg(CInt(.Items.Item(llngRow).SubItems.Item(1).Text), .Items.Item(llngRow).SubItems.Item(2).Text, .Items.Item(llngRow).SubItems.Item(3).Text, .Items.Item(llngRow).SubItems.Item(4).Text, CShort(VB.Right(.Items.Item(llngRow).SubItems.Item(0).Text, 4)), 1, CDbl(.Items.Item(llngRow).SubItems.Item(5).Text), .Items.Item(llngRow).SubItems.Item(0).Text) = False Then
							lintIns = lintIns + 1
							'Identificação
							lstrIn1 = lstrIn1 & "( " & CDbl(.Items.Item(llngRow).SubItems.Item(5).Text) & ", " 'numnf
							lstrIn1 = lstrIn1 & CInt(VB.Right(.Items.Item(llngRow).SubItems.Item(0).Text, 4) & VB.Left(.Items.Item(llngRow).SubItems.Item(0).Text, 2)) & ", " 'mesano
							'lstrIn1 = lstrIn1 & CLng(Right(.TextMatrix(llngRow, 0), 4)) & ", "  'ano
							lstrIn1 = lstrIn1 & Year(dtpAno.Value) & ", " 'ano
							lstrIn1 = lstrIn1 & """" & VB6.Format(.Items.Item(llngRow).SubItems.Item(8).Text, "yyyy-MM-dd") & """, " 'datavenc
							lstrIn1 = lstrIn1 & """" & VB6.Format(.Items.Item(llngRow).SubItems.Item(9).Text, "yyyy-MM-dd") & """, " 'datapag
							lstrIn1 = lstrIn1 & Replace(CStr(CDbl(.Items.Item(llngRow).SubItems.Item(6).Text)), ",", ".") & ", " 'valor
							lstrIn1 = lstrIn1 & CInt(.Items.Item(llngRow).SubItems.Item(1).Text) & ", " 'cons_id
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(2).Text & """, " 'zona
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(3).Text & """, " 'livro
							lstrIn1 = lstrIn1 & """" & .Items.Item(llngRow).SubItems.Item(4).Text & """), " 'conta
							If lintIns = 300 Then
								objAtualizaBancoDados.QUERY_NAME = lstrIns & VB.Left(lstrIn1, Len(lstrIn1) - 2)
								repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

								lstrIn1 = ""
								lintIns = 0
							Else
								lstrIn1 = lstrIn1 & vbCrLf
							End If
						End If
						Call BarraProgresso((Me.ProgressBarG), (Me.lblPercG), (Me.lblInfoG), 1)
					Next llngRow
					If Len(Trim(lstrIn1)) > 0 Then
						objAtualizaBancoDados.QUERY_NAME = lstrIns & VB.Left(lstrIn1, Len(lstrIn1) - 4)
						repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
					End If
				End If
			End With

			Call MontaGrande(0)
			Call MontaGrande(1)

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

	Private Sub GravaTemp()
		Dim lintLin As Short
		Dim llngIdC As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim lintSql As Short
		Dim lstrSql As String
		Dim lstrSq1 As String
		Dim llngRow As Integer
		Dim lstrAux As String
		Dim lstrFRt As String
		Dim repositorioAtualizaBD As New repositorioAtualizaBancoDados
		Dim objAtualizaBD As New entidadeAtualizaBancoDados

		Try
			lstrSql = ""
			lstrSql = lstrSql & "DELETE FROM `AUX_REL_DECLARACAO_DEBITO` "
			'lstrSql = lstrSql & "      WHERE `temp_declaracao_debito`.`ano`        = " & CInt(Year(dtpAno.Value)) & " " & vbCrLf
			'lstrSql = lstrSql & "        AND `temp_declaracao_debito`.`nm_usuario` = """ & vUsuario.LOGIN & """ "
			objAtualizaBD.QUERY_NAME = lstrSql
			repositorioAtualizaBD.Execute(objAtualizaBD)

			lstrSql = ""
			lstrSql = lstrSql & "DELETE FROM `AUX_REL_DECLARACAO_DEBITO_FATURAS` "
			'lstrSql = lstrSql & "      WHERE `temp_declaracao_debito`.`ano`        = " & CInt(Year(dtpAno.Value)) & " " & vbCrLf
			'lstrSql = lstrSql & "        AND `temp_declaracao_debito`.`nm_usuario` = """ & vUsuario.LOGIN & """ "
			objAtualizaBD.QUERY_NAME = lstrSql
			repositorioAtualizaBD.Execute(objAtualizaBD)

			lstrAux = ""
			lstrFRt = ""
			If Me.chkRota.CheckState = 1 Then
				With Me.lsvRotas
					If .Items.Count > 0 Then
						If .Items.Item(1).Checked = False Then
							For lintLin = 2 To .Items.Count - 1
								If .Items.Item(lintLin).Checked = True Then
									lstrAux = lstrAux & """" & .Items.Item(lintLin).Text & ""","
								End If
							Next lintLin
						End If
					End If
				End With
			End If
			If Len(Trim(lstrAux)) > 0 Then
				lstrFRt = " AND MID(`declaracao_debito`.`rota`, 1, 4) IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
			End If
			lstrSql = ""
			lstrSql = lstrSql & "INSERT INTO AUX_REL_DECLARACAO_DEBITO "
			lstrSql = lstrSql & "SELECT '" & My.Computer.Name & "',"
			lstrSql = lstrSql & "       `declaracao_debito`.`CONS_ID`, "
			lstrSql = lstrSql & "       `declaracao_debito`.`ZONA`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`LIVRO`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`CONTA`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`ANO`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`ROTA`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`NOME`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`UF`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`CEP`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`CIDADE`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`DISTRITO`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`BAIRRO`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`END`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`NUMERO`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`COMPLE`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`QUADRA`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`LOTE`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`CPF`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`RG`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`INSC`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`FASE`,   "
			lstrSql = lstrSql & "       `declaracao_debito`.`TENSAO`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`MEDIDOR`,    "
			lstrSql = lstrSql & "       `declaracao_debito`.`AGRUPA`    "
			lstrSql = lstrSql & "  FROM `declaracao_debito` "
			lstrSql = lstrSql & " WHERE `declaracao_debito`.`ano`  = " & CInt(Year(dtpAno.Value)) & " " & vbCrLf

			If chkZLC.CheckState = 1 Then
				lstrSql = lstrSql & " AND `declaracao_debito`.`zona`  = """ & Me.txtZona.Text & """"
				lstrSql = lstrSql & " AND `declaracao_debito`.`livro` = """ & Me.txtLivro.Text & """"
				lstrSql = lstrSql & " AND `declaracao_debito`.`conta` = """ & Me.txtConta.Text & """ "
				If IsNumeric(Me.txtConsId.Text) Then
					lstrSql = lstrSql & " AND `declaracao_debito`.`cons_id` = " & Me.txtConsId.Text & " "
				End If
			End If

			lstrSql = lstrSql & " AND EXISTS(SELECT * FROM `uc_faturamento` "
			lstrSql = lstrSql & "             WHERE `uc_faturamento`.`zona` = `declaracao_debito`.`zona` "
			lstrSql = lstrSql & "               AND `uc_faturamento`.`livro` = `declaracao_debito`.`livro` "
			lstrSql = lstrSql & "               AND `uc_faturamento`.`conta` = `declaracao_debito`.`conta` )"
			'lstrSql = lstrSql & "               AND `uc_faturamento`.`grupo` =  '" & IIf(Me.opbGrupoA.Checked, "A", "B") & "') "
			lstrSql = lstrSql & lstrFRt
			objAtualizaBD.QUERY_NAME = lstrSql
			repositorioAtualizaBD.Execute(objAtualizaBD)


			lstrSql = ""
			lstrSql = lstrSql & "INSERT INTO AUX_REL_DECLARACAO_DEBITO_FATURAS "
			lstrSql = lstrSql & "SELECT '" & My.Computer.Name & "',"
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`numnf`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`mesano`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`ano`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`datavenc`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`datapag`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`valor`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`cons_id`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`zona`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`livro`, "
			lstrSql = lstrSql & "       `declaracao_debito_faturas`.`conta` "
			lstrSql = lstrSql & "  FROM `declaracao_debito_faturas` "
			lstrSql = lstrSql & " WHERE `declaracao_debito_faturas`.`ano`  = " & CInt(Year(dtpAno.Value)) & " " & vbCrLf
			If chkZLC.CheckState = 1 Then
				lstrSql = lstrSql & " AND `declaracao_debito_faturas`.`zona`  = """ & Me.txtZona.Text & """"
				lstrSql = lstrSql & " AND `declaracao_debito_faturas`.`livro` = """ & Me.txtLivro.Text & """"
				lstrSql = lstrSql & " AND `declaracao_debito_faturas`.`conta` = """ & Me.txtConta.Text & """ "
				If IsNumeric(Me.txtConsId.Text) Then
					lstrSql = lstrSql & " AND `declaracao_debito_faturas`.`cons_id` = " & Me.txtConsId.Text & " "
				End If
			End If
			lstrSql = lstrSql & " AND EXISTS(SELECT * FROM `uc_faturamento` "
			lstrSql = lstrSql & "             WHERE `uc_faturamento`.`zona` = `declaracao_debito_faturas`.`zona` "
			lstrSql = lstrSql & "               AND `uc_faturamento`.`livro` = `declaracao_debito_faturas`.`livro` "
			lstrSql = lstrSql & "               AND `uc_faturamento`.`conta` = `declaracao_debito_faturas`.`conta` )"
			'lstrSql = lstrSql & "               AND `uc_faturamento`.`grupo` =  '" & IIf(Me.opbGrupoA.Checked, "A", "B") & "') "
			lstrSql = lstrSql & lstrFRt
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

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

	Private Function JaExisteReg(ByVal alngIdC As Integer, ByVal astrZon As String, ByVal astrLiv As String, ByVal astrCon As String, ByVal aintAno As Short, ByVal aintTab As Short, Optional ByVal adblNumNf As Double = 0, Optional ByVal astrMesAno As String = "") As Boolean
		Dim llngIdC As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim lstrSql As String

		Try
			JaExisteReg = False
			lstrSql = ""
			If aintTab = 0 Then
				lstrSql = lstrSql & "SELECT `cons_id`, `zona`, `livro`, `conta`, `ano` "
				lstrSql = lstrSql & "  FROM `declaracao_debito` "
				lstrSql = lstrSql & " WHERE `declaracao_debito`.`cons_id` = " & alngIdC
				lstrSql = lstrSql & "   AND `declaracao_debito`.`zona`    = """ & astrZon & """ "
				lstrSql = lstrSql & "   AND `declaracao_debito`.`livro`   = """ & astrLiv & """ "
				lstrSql = lstrSql & "   AND `declaracao_debito`.`conta`   = """ & astrCon & """ "
				lstrSql = lstrSql & "   AND `declaracao_debito`.`ano`     = " & aintAno & " "
			Else
				lstrSql = lstrSql & "SELECT `numnf`, `mesano`, `cons_id`, `zona`, `livro`, `conta`, `ano` "
				lstrSql = lstrSql & "  FROM `declaracao_debito_faturas` "
				lstrSql = lstrSql & " WHERE `declaracao_debito_faturas`.`numnf`  = " & adblNumNf
				lstrSql = lstrSql & "   AND `declaracao_debito_faturas`.`mesano` = " & CInt(VB.Right(astrMesAno, 4) & VB.Left(astrMesAno, 2)) & " "
			End If
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dtinterno = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


			If dtinterno.Rows.Count <> 0 Then
				For Each row As DataRow In dtinterno.Rows
					JaExisteReg = True
				Next
				'Close()
			Else
				'Close()
			End If

			dtinterno = Nothing

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

	End Function

	Private Function ExisteFat(ByVal astrZon As String, ByVal astrLiv As String, ByVal astrCon As String) As Boolean
		Dim llngIdC As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim lstrSql As String

		Try

			ExisteFat = False
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `mesano`, `mesano_ref`, `numnf` "
			lstrSql = lstrSql & "  FROM `nftransicao` "
			lstrSql = lstrSql & " WHERE `nftransicao`.`zona`   = """ & astrZon & """ "
			lstrSql = lstrSql & "   AND `nftransicao`.`livro`  = """ & astrLiv & """ "
			lstrSql = lstrSql & "   AND `nftransicao`.`conta`  = """ & astrCon & """ "
			lstrSql = lstrSql & "   AND `nftransicao`.`mesano_ref` = """ & VB6.Format(Me.dtpFaturas.Value, "yyyymm") & """ "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			If dt.Rows.Count <> 0 Then
				For Each row As DataRow In dt.Rows
					ExisteFat = True
				Next
			Else
				'Close()
			End If

			dt = Nothing

			If ExisteFat = False Then
				lstrSql = ""
				lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `mesano`, `mesano_ref`, `numnf` "
				lstrSql = lstrSql & "  FROM `nf` "
				lstrSql = lstrSql & " WHERE `nf`.`zona`   = """ & astrZon & """ "
				lstrSql = lstrSql & "   AND `nf`.`livro`  = """ & astrLiv & """ "
				lstrSql = lstrSql & "   AND `nf`.`conta`  = """ & astrCon & """ "
				lstrSql = lstrSql & "   AND `nf`.`mesano_ref` = """ & VB6.Format(Me.dtpFaturas.Value, "yyyymm") & """ "
				objAtualizaBancoDados.QUERY_NAME = lstrSql
				dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

				If dt2.Rows.Count <> 0 Then
					For Each row As DataRow In dt2.Rows
						ExisteFat = True
					Next
				Else
					'Close()
				End If

				dt2 = Nothing

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

	End Function

	Private Sub AjustaDeclaracaoDebito()
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim llngCId As Integer
		Dim ldteMenor As Date
		Dim ldteMaior As Date
		Dim lstrSql As String

		Try
			Me.lblInfo.Text = " Ajustando declaração de débitos"
			Call Me.lblInfo.Refresh()
			lstrSql = "SELECT ano,cons_id,zona,livro,conta, min(datavenc) menor_mes, max(datavenc) maior_mes FROM declaracao_debito_faturas WHERE ano = " & VB6.Format(Me.dtpAno.Value, "yyyy") & " GROUP BY ano,cons_id,zona,livro,conta "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			If dt.Rows.Count <> 0 Then
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, dt.Rows.Count)
				For Each row As DataRow In dt.Rows
					lstrZon = IIf(IsDBNull(row("zona")), "", row("zona"))
					lstrLiv = IIf(IsDBNull(row("livro")), "", row("livro"))
					lstrCon = IIf(IsDBNull(row("conta")), "", row("conta"))
					llngCId = IIf(IsDBNull(row("cons_id")), "", row("cons_id"))
					ldteMenor = CDate(IIf(IsDBNull(row("menor_mes")), "1900-01-01", row("menor_mes")))
					ldteMaior = CDate(IIf(IsDBNull(row("maior_mes")), "1900-01-01", row("maior_mes")))

					lstrSql = "UPDATE declaracao_debito SET "
					lstrSql = lstrSql & " datavenc_menor = '" & VB6.Format(ldteMenor, "yyyy-MM-dd") & "', "
					lstrSql = lstrSql & " datavenc_maior = '" & VB6.Format(ldteMaior, "yyyy-MM-dd") & "' "
					lstrSql = lstrSql & " WHERE ano = " & VB6.Format(Me.dtpAno.Value, "yyyy") & " "
					lstrSql = lstrSql & "   AND cons_id = " & llngCId & " "
					lstrSql = lstrSql & "   AND zona = '" & lstrZon & "' "
					lstrSql = lstrSql & "   AND livro = '" & lstrLiv & "' "
					lstrSql = lstrSql & "   AND conta = '" & lstrCon & "' "
					objAtualizaBancoDados.QUERY_NAME = lstrSql
					repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
				Next
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
			Else
				'Close()
			End If

			dt = Nothing

			Me.lblInfo.Text = " Finalizado"
			Me.lblPerc.Text = "100 %"

			Call Me.lblPerc.Refresh()
			Call Me.lblInfo.Refresh()

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

		Dim dt As DataTable
		Dim dt1 As DataTable


		Dim dt_1 As DataTable
		Dim dt_2 As DataTable
		Dim dt_3 As DataTable

		Dim dc As DataColumn
		Dim ds As DataSet

		Dim lstrsql As String
		Dim ldteBase As String

		Try
			Dim rpt As New ReportDocument()

			If vNomeRPT = "rptDeclaracaoDebito" Then

				' CABEÇALHO
				dt_2 = New DataTable()
				dt_2.Columns.Add("NM_USUARIO", GetType(String))
				dt_2.Columns.Add("ANO", GetType(String))
				dt_2.Columns.Add("CONS_ID", GetType(String))
				dt_2.Columns.Add("ZONA", GetType(String))
				dt_2.Columns.Add("LIVRO", GetType(String))
				dt_2.Columns.Add("CONTA", GetType(String))
				dt_2.Columns.Add("ROTA", GetType(String))
				dt_2.Columns.Add("NOME", GetType(String))
				dt_2.Columns.Add("UF", GetType(String))
				dt_2.Columns.Add("CEP", GetType(String))
				dt_2.Columns.Add("CIDADE", GetType(String))
				dt_2.Columns.Add("DISTRITO", GetType(String))
				dt_2.Columns.Add("BAIRRO", GetType(String))
				dt_2.Columns.Add("END", GetType(String))
				dt_2.Columns.Add("NUMERO", GetType(String))
				dt_2.Columns.Add("COMPLE", GetType(String))
				dt_2.Columns.Add("QUADRA", GetType(String))
				dt_2.Columns.Add("LOTE", GetType(String))
				dt_2.Columns.Add("CPF", GetType(String))
				dt_2.Columns.Add("RG", GetType(String))
				dt_2.Columns.Add("INSCR", GetType(String))
				dt_2.Columns.Add("FASE", GetType(String))
				dt_2.Columns.Add("TENSAO", GetType(String))
				dt_2.Columns.Add("MEDIDOR", GetType(String))
				dt_2.Columns.Add("AGRUPA", GetType(String))
				dt_2.Columns.Add("IMAGEM", GetType(Byte()))

				dt_3 = New DataTable()
				dt_3.Columns.Add("NM_USUARIO", GetType(String))
				dt_3.Columns.Add("NUMNF", GetType(String))
				dt_3.Columns.Add("MESANO", GetType(String))
				dt_3.Columns.Add("ANO", GetType(String))
				dt_3.Columns.Add("DATAVENC", GetType(String))
				dt_3.Columns.Add("DATAPAG", GetType(String))
				dt_3.Columns.Add("VALOR", GetType(String))
				dt_3.Columns.Add("CONS_ID", GetType(String))
				dt_3.Columns.Add("ZONA", GetType(String))
				dt_3.Columns.Add("LIVRO", GetType(String))
				dt_3.Columns.Add("CONTA", GetType(String))

				ds = New DataSet

				lstrsql = ""
				lstrsql = "SELECT * FROM AUX_REL_DECLARACAO_DEBITO WHERE NM_USUARIO = '" & My.Computer.Name & "'"
				objAtualizaBancoDados.QUERY_NAME = lstrsql
				dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

				If dt.Rows.Count > 0 Then
					For Each dr_1 As DataRow In dt.Rows

						dt_2.Rows.Add(dr_1("NM_USUARIO"),
										  dr_1("ANO"),
										  dr_1("CONS_ID"),
										  dr_1("ZONA"),
										  dr_1("LIVRO"),
										  dr_1("CONTA"),
										  dr_1("ROTA"),
										  dr_1("NOME"),
										  dr_1("UF"),
										  dr_1("CEP"),
										  dr_1("CIDADE"),
										  dr_1("DISTRITO"),
										  dr_1("BAIRRO"),
										  dr_1("END"),
										  dr_1("NUMERO"),
										  dr_1("COMPLE"),
										  dr_1("QUADRA"),
										  dr_1("LOTE"),
										  dr_1("CPF"),
										  dr_1("RG"),
										  dr_1("INSCR"),
										  dr_1("FASE"),
										  dr_1("TENSAO"),
										  dr_1("MEDIDOR"),
										  dr_1("AGRUPA"),
										  Limagem)
					Next dr_1
				End If

				lstrsql = ""
				lstrsql = "SELECT * FROM AUX_REL_DECLARACAO_DEBITO_FATURAS WHERE NM_USUARIO = '" & My.Computer.Name & "' AND ANO = '" & Year(dtpAno.Value) & "'"
				objAtualizaBancoDados.QUERY_NAME = lstrsql
				dt1 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

				If dt1.Rows.Count > 0 Then
					For Each dr_1 As DataRow In dt1.Rows

						dt_3.Rows.Add(dr_1("NM_USUARIO"),
										  dr_1("NUMNF"),
										  dr_1("MESANO"),
										  dr_1("ANO"),
										  dr_1("DATAVENC"),
										  dr_1("DATAPAG"),
										  dr_1("VALOR"),
										  dr_1("CONS_ID"),
										  dr_1("ZONA"),
										  dr_1("LIVRO"),
										  dr_1("CONTA"))
					Next dr_1
				End If


				ds.Tables.Add(dt_2)
				ds.Tables(0).TableName = "REL_DECLARACAO_DEBITO"

				ds.Tables.Add(dt_3)
				ds.Tables(1).TableName = "REL_DECLARACAO_DEBITO_FATURAS"

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

					rpt = New rptDeclaracaoDebito

					rpt.SetDataSource(ds)
					rpt.SetParameterValue("nomeempresa", sNomeEmpresa)
					rpt.SetParameterValue("enderecoempresa", sEnderecoEmpresa)
					rpt.SetParameterValue("cepempresa", sCepEmpresa)
					rpt.SetParameterValue("ufempresa", sUFempresa)
					rpt.SetParameterValue("cidadeempresa", sCidadeEmpresa)
					rpt.SetParameterValue("bairroempresa", sBairroEmpresa)
					rpt.SetParameterValue("foneempresa", sFoneEmpresa)
					rpt.SetParameterValue("websiteempresa", sWebEmpresa)
					rpt.SetParameterValue("sCpfCnpj", sCpfCnpj)
					rpt.SetParameterValue("IE", sIE)

					frmViewRelatorios.rpt = rpt

					frmViewRelatorios.CRViewer.Zoom((100))
					frmViewRelatorios.Text = "Relatório de Quitação de Débitos"
					frmViewRelatorios.ShowDialog()

					dt = Nothing
					dt1 = Nothing

				End If


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

	End Sub
	Private Sub sCriaTabelaAuxiliar()
		Try
			Dim lstrsql As String

			lstrsql = ""
			lstrsql = "DROP TABLE IF EXISTS `AUX_REL_DECLARACAO_DEBITO`"
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

			lstrsql = ""
			lstrsql = lstrsql & "CREATE TABLE IF NOT EXISTS `AUX_REL_DECLARACAO_DEBITO` (" & vbCrLf
			lstrsql = lstrsql & "  `NM_USUARIO`        varchar(20) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `ANO`               varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `CONS_ID`           varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `ZONA`              varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `LIVRO`             varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `CONTA`             varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `ROTA`              varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `NOME`              varchar(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `UF`                varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `CEP`               varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `CIDADE`            varchar(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `DISTRITO`          varchar(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `BAIRRO`            varchar(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `END`               varchar(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `NUMERO`            varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `COMPLE`            varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `QUADRA`            varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `LOTE`              varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `CPF`               varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `RG`                varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `INSCR`              varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `FASE`              varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `TENSAO`            varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `MEDIDOR`           varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `AGRUPA`            varchar(20) DEFAULT NULL) "
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)


			lstrsql = ""
			lstrsql = "DROP TABLE IF EXISTS `AUX_REL_DECLARACAO_DEBITO_FATURAS`"
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

			lstrsql = ""
			lstrsql = lstrsql & "CREATE TABLE IF NOT EXISTS `AUX_REL_DECLARACAO_DEBITO_FATURAS` (" & vbCrLf
			lstrsql = lstrsql & "  `nm_usuario`        varchar(20) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `numnf`             varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `mesano`            varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `ano`               varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `datavenc`          varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `datapag`           varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `valor`             varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `cons_id`           varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `zona`              varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `livro`             varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `conta`             varchar(12) DEFAULT NULL) "
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

			lstrsql = ""
			lstrsql = lstrsql & "CREATE TABLE IF NOT EXISTS `declaracao_debito` ( " & vbCrLf
			lstrsql = lstrsql & " `ano`           INTEGER(4)   DEFAULT '0',  " & vbCrLf
			'Identificação
			lstrsql = lstrsql & " `cons_id`       INTEGER      DEFAULT '0',  " & vbCrLf
			lstrsql = lstrsql & " `zona`          CHAR(3)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `livro`         CHAR(2)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `conta`         VARCHAR(6)   DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `rota`          VARCHAR(9)   DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `nome`          VARCHAR(70)  DEFAULT NULL, " & vbCrLf
			'Endereço
			lstrsql = lstrsql & " `uf`            CHAR(2)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `cep`           VARCHAR(15)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `cidade`        VARCHAR(60)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `distrito`      VARCHAR(60)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `bairro`        VARCHAR(60)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `end`           VARCHAR(70)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `numero`        VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `comple`        VARCHAR(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `quadra`        VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `lote`          VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			'Entrega
			lstrsql = lstrsql & " `uf_entrega`    CHAR(2)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `cep_entrega`   VARCHAR(15)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `cid_entrega`   VARCHAR(60)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `dis_entrega`   VARCHAR(60)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `bai_entrega`   VARCHAR(60)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `end_entrega`   VARCHAR(70)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `num_entrega`   VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `compl_entrega` VARCHAR(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `qua_entrega`   VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `lot_entrega`   VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			'Documentos
			lstrsql = lstrsql & " `cpf`           VARCHAR(20)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `rg`            VARCHAR(25)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `insc`          VARCHAR(25)  DEFAULT NULL, " & vbCrLf
			'Medição
			lstrsql = lstrsql & " `fase`          CHAR(1)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `tensao`        VARCHAR(10)  DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `medidor`       VARCHAR(18)  DEFAULT NULL, " & vbCrLf
			'Outros
			lstrsql = lstrsql & " `agrupa`        VARCHAR(5)  DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  PRIMARY KEY  (`ano`,`cons_id`,`zona`,`livro`,`conta`) " & vbCrLf
			lstrsql = lstrsql & ") ENGINE=InnoDB DEFAULT CHARSET=latin1; "
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

			lstrsql = ""
			lstrsql = lstrsql & "CREATE TABLE IF NOT EXISTS `declaracao_debito_faturas` ( " & vbCrLf
			lstrsql = lstrsql & " `numnf`         DOUBLE        NOT NULL DEFAULT '0'," & vbCrLf
			lstrsql = lstrsql & " `mesano`        INTEGER(6)    NOT NULL DEFAULT '0', " & vbCrLf
			lstrsql = lstrsql & " `ano`           INTEGER(4)    NOT NULL DEFAULT '0', " & vbCrLf
			lstrsql = lstrsql & " `datavenc`      DATE          DEFAULT '1900-01-01'," & vbCrLf
			lstrsql = lstrsql & " `datapag`       DATE          DEFAULT '1900-01-01'," & vbCrLf
			lstrsql = lstrsql & " `valor`         DECIMAL(14,2) DEFAULT NULL,        " & vbCrLf
			'Identificação
			lstrsql = lstrsql & " `cons_id`       INTEGER       DEFAULT '0',         " & vbCrLf
			lstrsql = lstrsql & " `zona`          CHAR(3)       DEFAULT NULL,        " & vbCrLf
			lstrsql = lstrsql & " `livro`         CHAR(2)       DEFAULT NULL,        " & vbCrLf
			lstrsql = lstrsql & " `conta`         VARCHAR(6)    DEFAULT NULL,        " & vbCrLf
			lstrsql = lstrsql & "  PRIMARY KEY  (`numnf`,`mesano`, `ano`), " & vbCrLf
			lstrsql = lstrsql & "          KEY `keyano`   (`ano`),"
			lstrsql = lstrsql & "          KEY `keycons`  (`cons_id`),"
			lstrsql = lstrsql & "          KEY `keyzona`  (`zona`),"
			lstrsql = lstrsql & "          KEY `keylivro` (`livro`),"
			lstrsql = lstrsql & "          KEY `keyconta` (`conta`)"
			lstrsql = lstrsql & ") ENGINE=InnoDB DEFAULT CHARSET=latin1; "
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

			lstrsql = ""
			lstrsql = lstrsql & "CREATE TABLE IF NOT EXISTS `temp_declaracao_debito` ( " & vbCrLf
			lstrsql = lstrsql & " `nm_usuario`    VARCHAR(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `ano`           INTEGER(4)   DEFAULT '0',  " & vbCrLf
			'Identificação
			lstrsql = lstrsql & " `cons_id`       INTEGER      DEFAULT '0',  " & vbCrLf
			lstrsql = lstrsql & " `zona`          CHAR(3)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `livro`         CHAR(2)      DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & " `conta`         VARCHAR(6)   DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  PRIMARY KEY  (`nm_usuario`,`ano`,`cons_id`,`zona`,`livro`,`conta`) " & vbCrLf
			lstrsql = lstrsql & ") ENGINE=InnoDB DEFAULT CHARSET=latin1; "
			objAtualizaBancoDados.QUERY_NAME = lstrsql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)


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

	Private Sub JaExisteGrade_Quitacao(ByVal iGrid As Integer, ByVal alngIdC As Integer, ByVal astrZon As String, ByVal astrLiv As String, ByVal astrCon As String, Optional ByVal adblNNf As Double = 0, Optional ByVal astrMAn As String = "")
		Dim llngIdC As Integer
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim ldblNNf As Double
		Dim lstrMAn As String
		Dim llngRow As Integer
		Dim lstrCons_id As String
		Dim i As Integer
		Dim squalgrid As ListView


		Try
			bQuitacao = False

			If iGrid = 0 Then
				squalgrid = lsvPendentes
			ElseIf iGrid = 1 Then
				squalgrid = lsvDia
			Else
				squalgrid = lsvFaturas
			End If

			With squalgrid
				For i = 0 To .Items.Count - 1
					llngIdC = .Items.Item(i).SubItems.Item(1).Text
					lstrZon = .Items.Item(i).SubItems.Item(2).Text
					lstrLiv = .Items.Item(i).SubItems.Item(3).Text
					lstrCon = .Items.Item(i).SubItems.Item(4).Text
					If Len(Trim(astrMAn)) > 0 Then
						If Len(Trim(astrMAn)) = 7 Then
							lstrMAn = .Items.Item(i).Text
							ldblNNf = .Items.Item(i).SubItems.Item(5).Text
							If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon And lstrMAn = astrMAn And ldblNNf = adblNNf Then
								bQuitacao = True
								i = .Items.Count - 1
							End If
						ElseIf Len(Trim(astrMAn)) = 4 Then
							lstrMAn = .Items.Item(i).SubItems.Item(34).Text
							If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon And lstrMAn = astrMAn Then
								bQuitacao = True
								i = .Items.Count - 1
							End If
						End If
					Else
						If llngIdC = alngIdC And lstrZon = astrZon And lstrLiv = astrLiv And lstrCon = astrCon Then
							bQuitacao = True
							i = .Items.Count - 1
						End If
					End If
				Next

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




End Class