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 frmReaviso
	Inherits System.Windows.Forms.Form

	Dim gstrNmEstacao As String = vUsuario.LOGIN
	Dim gstrDataBase As String = vMySqlDataBase
	Private objAtualizaBancoDados As New entidadeAtualizaBancoDados
	Private repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados
	Private dt As DataTable
	Private dt2 As DataTable
	Private dt3 As DataTable
	Private sNomeRelatorio As String
	Private Limagem As Byte()
	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 sTerminouExecucao As Boolean = False
	Public sExecutaAutomatico As Boolean = False
	Private Sub lsvBancos_ItemCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ItemCheckEventArgs) Handles lsvBancos.ItemCheck
		'Dim aListItem As System.Windows.Forms.ListViewItem = lsvBancos.Items(eventArgs.Index)
		'Dim lintLinha As Short
		'Try
		'	With Me.lsvBancos
		'		Select Case aListItem.Text
		'			'Case "Todos os Bancos"
		'			'	If .Items.Item(1).Checked = True Then
		'			'		For lintLinha = 4 To .Items.Count - 1
		'			'			.Items.Item(lintLinha).Checked = True
		'			'		Next lintLinha
		'			'	ElseIf .Items.Item(1).Checked = False Then
		'			'		For lintLinha = 4 To .Items.Count - 1
		'			'			.Items.Item(lintLinha).Checked = False
		'			'		Next lintLinha
		'			'	End If
		'			'	.Items.Item(2).Checked = False
		'			'	.Items.Item(3).Checked = False
		'			Case "Somente Arrecadação"
		'				For lintLinha = 4 To .Items.Count - 1
		'					If .Items.Item(lintLinha).SubItems(2).Text = "N" Then
		'						.Items.Item(lintLinha).Checked = True
		'					Else
		'						.Items.Item(lintLinha).Checked = False
		'					End If
		'				Next lintLinha
		'				'.Items.Item(1).Checked = False
		'				'.Items.Item(3).Checked = False
		'			Case "Somente Débito Automático"
		'				For lintLinha = 4 To .Items.Count - 1
		'					If .Items.Item(lintLinha).SubItems(2).Text = "D" Then
		'						.Items.Item(lintLinha).Checked = True
		'					Else
		'						.Items.Item(lintLinha).Checked = False
		'					End If
		'				Next lintLinha
		'				'.Items.Item(1).Checked = False
		'				'.Items.Item(2).Checked = False
		'			Case Else
		'				If aListItem.Checked = False Then
		'					.Items.Item(1).Checked = False
		'				End If
		'		End Select
		'	End With
		'Catch ex As Exception
		'	MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lsvBancos_ItemCheck" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
		'	Exit Sub
		'End Try
	End Sub

	Private Sub mfgDados_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mfgDados.DblClick
		Dim lintCol As Short
		Dim llngReg As Integer
		Dim llngLinha As Integer
		Try
			With Me.mfgDados
				.Redraw = False
				If .RowSel > 0 Then
					If .Rows > 2 Then
						Me.mfgNaoEntrou.Rows = Me.mfgNaoEntrou.Rows + 1
						Me.mfgNaoEntrou.set_TextMatrix(Me.mfgNaoEntrou.Rows - 1, 0, Me.mfgNaoEntrou.Rows - 1)
						For lintCol = 1 To 14
							Me.mfgNaoEntrou.set_TextMatrix(Me.mfgNaoEntrou.Rows - 1, lintCol, .get_TextMatrix(.RowSel, lintCol))
						Next lintCol
						llngReg = .RowSel
						.RemoveItem((.RowSel))
						For llngLinha = llngReg To .Rows - 1
							.set_TextMatrix(llngLinha, 0, llngLinha)
						Next llngLinha
					Else
						.Rows = 1
					End If
				End If
				.Redraw = True
				Me.lblInfo.Text = " Procesado: " & .Rows - 1 & " de " & (.Rows - 1) + (Me.mfgNaoEntrou.Rows - 1)
				Call Me.lblInfo.Refresh()
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: mfgDados_DblClick" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub opbIndividual_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
		Try
			If eventSender.Checked Then
				Me.txtZona.Enabled = Me.opbIndividual.Checked = True
				Me.txtLivro.Enabled = Me.opbIndividual.Checked = True
				Me.txtConta.Enabled = Me.opbIndividual.Checked = True
				Me.cmdBuscaUc.Enabled = Me.opbIndividual.Checked = True
				Me.lsvRotas.Enabled = Me.opbRota.Checked = True
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: opbIndividual_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub opbRota_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbRota.CheckedChanged
		Try
			If eventSender.Checked Then
				Me.lsvRotas.Enabled = Me.opbRota.Checked = True
				Me.txtZona.Enabled = Me.opbIndividual.Checked = True
				Me.txtLivro.Enabled = Me.opbIndividual.Checked = True
				Me.txtConta.Enabled = Me.opbIndividual.Checked = True
				Me.cmdBuscaUc.Enabled = Me.opbIndividual.Checked = True
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: opbRota_CheckedChanged" & "", "Aviso de 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)
		Try
			With 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 txtConta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
		txtConta.Text = VB6.Format(txtConta.Text, "000000")
	End Sub

	Private Sub txtLivro_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
		Try
			With 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

	Private Sub txtLivro_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
		txtLivro.Text = VB6.Format(txtLivro.Text, "00")
	End Sub

	Private Sub txtValor_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtValor.Enter
		Try
			With Me.txtValor
				.SelectionStart = 0
				.SelectionLength = Len(.Text)
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtValor_Enter" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub txtValor_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtValor.KeyPress
		Try
			Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
			If KeyAscii = System.Windows.Forms.Keys.Return Then
				TabEnter(KeyAscii, eventArgs)
			ElseIf KeyAscii <> System.Windows.Forms.Keys.Back And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9) Then
				If KeyAscii = System.Windows.Forms.Keys.Delete Then
					KeyAscii = System.Windows.Forms.Keys.Snapshot
				End If
				If KeyAscii <> System.Windows.Forms.Keys.Snapshot Then
					KeyAscii = 0
				Else
					If InStr(1, Me.txtValor.Text, ",") > 0 Then
						KeyAscii = 0
					End If
				End If
			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: txtValor_KeyPress" & "", "Aviso de 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)
		Try
			With 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

	Private Sub txtZona_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
		txtZona.Text = VB6.Format(txtZona.Text, "000")
	End Sub

	Private Sub frmReaviso_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 Me.Close()
			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: frmReaviso_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub frmReaviso_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Try
			Me.cmdProcessar.Enabled = False
			Me.cmdImprimir.Enabled = False
			Me.lblInfo.Text = " "
			Call Me.lblInfo.Refresh()
			Me.dtpReaviso.Value = VB6.Format(Date.Now, "dd/mm/yyyy hh:mm:ss")
			Me.dtpVecto.Value = VB6.Format(Date.Now, "dd/mm/yyyy hh:mm:ss")
			Call MontaGrid()
			Call CarregaRotas()
			Call CarregaBancos()
			Call sCriaTabelaAuxiliar()
			If sExecutaAutomatico = True Then
				Dim f As New frmAguarde
				f.lbMensagem.Text = "Processando Reavisos"
				f.Show(Me)
				Call ExecutaAutomatico()
				Me.cmdFechar.Enabled = True
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmReaviso_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub ExecutaAutomatico()
		Try

			With Me.lsvRotas
				For k As Integer = 0 To .Items.Count - 1
					.Items.Item(k).Checked = True
				Next k
			End With

			Call ExecuteFiltrar()

			If sTerminouExecucao = True Then
				Call ExecuteProcessar()
				Call AtualizaTabelaExecucaoAutomatica()
			End If

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

	Private Sub AtualizaTabelaExecucaoAutomatica()
		Dim lstrSql As String
		Try
			lstrSql = "SELECT * "
			lstrSql += "FROM execucao_automatica "
			lstrSql += "WHERE funcao = 'REAVISO' "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)
			If dt.Rows.Count > 0 Then
				For Each row As DataRow In dt.Rows
					lstrSql = "UPDATE execucao_automatica SET "
					lstrSql += "data_execucao = '" & Format(Date.Now(), "yyyy-MM-dd") & "' "
					lstrSql += "WHERE id = '" & CLng(IIf(IsDBNull(row.Item("id")), "0", row.Item("id"))) & "' "
					objAtualizaBancoDados.QUERY_NAME = lstrSql
					repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
				Next
			Else
				lstrSql = "INSERT INTO execucao_automatica (funcao, data_execucao) VALUES ("
				lstrSql += "'REAVISO', "
				lstrSql += "'" & Format(Date.Now(), "yyyy-MM-dd") & "') "
				objAtualizaBancoDados.QUERY_NAME = lstrSql
				repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)
			End If

		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmReaviso_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub ExecuteFiltrar()
		Try
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.cmdProcessar.Enabled = False
			Me.cmdImprimir.Enabled = False
			Me.cmdFechar.Enabled = False
			Me.cmdFiltrar.Enabled = False
			Call LigDes(False)
			Me.lblInfo.Text = " Aguarde, buscando faturas vencidas com os filtros selecionados acima..."
			Call Me.lblInfo.Refresh()
			System.Windows.Forms.Application.DoEvents()
			Call CarregarGrid()
			Call LigDes(True)
			Me.cmdFiltrar.Enabled = True
			Me.cmdFechar.Enabled = True
			Me.cmdProcessar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default
			sTerminouExecucao = True
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdFiltrar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub ExecuteProcessar()
		Try
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.cmdFiltrar.Enabled = False
			Me.cmdFechar.Enabled = False
			Me.cmdImprimir.Enabled = False
			Me.cmdProcessar.Enabled = False
			Call LigDes(False)
			Me.lblInfo.Text = " Aguarde, processando..."
			Call Me.lblInfo.Refresh()
			System.Windows.Forms.Application.DoEvents()
			Call ProcessarReaviso()
			Call LigDes(True)
			Me.cmdProcessar.Enabled = True
			Me.cmdFiltrar.Enabled = True
			Me.cmdImprimir.Enabled = True
			Me.cmdFechar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default
		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 cmdFiltrar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFiltrar.Click
		Try
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.cmdProcessar.Enabled = False
			Me.cmdImprimir.Enabled = False
			Me.cmdFechar.Enabled = False
			Me.cmdFiltrar.Enabled = False
			Call LigDes(False)
			Me.lblInfo.Text = " Aguarde, buscando faturas vencidas com os filtros selecionados acima..."
			Call Me.lblInfo.Refresh()
			System.Windows.Forms.Application.DoEvents()
			Call CarregarGrid()
			Call LigDes(True)
			Me.cmdFiltrar.Enabled = True
			Me.cmdFechar.Enabled = True
			Me.cmdProcessar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default
			sTerminouExecucao = True
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdFiltrar_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
		Try
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.cmdFiltrar.Enabled = False
			Me.cmdFechar.Enabled = False
			Me.cmdImprimir.Enabled = False
			Me.cmdProcessar.Enabled = False
			Call LigDes(False)
			Me.lblInfo.Text = " Aguarde, processando..."
			Call Me.lblInfo.Refresh()
			System.Windows.Forms.Application.DoEvents()
			Call ProcessarReaviso()
			Call LigDes(True)
			Me.cmdProcessar.Enabled = True
			Me.cmdFiltrar.Enabled = True
			Me.cmdImprimir.Enabled = True
			Me.cmdFechar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default
			'  If MsgBox("Deseja imprimir os reavisos?", vbQuestion + vbYesNoCancel, "Fatwin") = vbYes Then
			'    Call cmdImprimir_Click
			'  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 cmdImprimir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImprimir.Click
		Try
			Dim lstrCriterio As String
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.cmdFiltrar.Enabled = False
			Me.cmdFechar.Enabled = False
			Me.cmdImprimir.Enabled = False
			Me.cmdProcessar.Enabled = False
			Call LigDes(False)

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

			If Me.chkModelo2.CheckState = System.Windows.Forms.CheckState.Checked Then
				sNomeRelatorio = "rptReavisoEflul_grupo_A"
			Else
				sNomeRelatorio = "rptReavisoEflul"
			End If

			Call lPrint(sNomeRelatorio)

			Call LigDes(True)
			Me.cmdProcessar.Enabled = True
			Me.cmdFiltrar.Enabled = True
			Me.cmdImprimir.Enabled = True
			Me.cmdFechar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default

		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 cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click
		Call Me.Close()
	End Sub

	Private Sub ProcessarReaviso()
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrRota As String
		Dim lstrSequencia As String
		Dim lstrClasse As String
		Dim lstrNome As String
		Dim ldblNumNf As Double
		Dim lstrMesAno As String
		Dim llngConsId As Integer
		Dim llngUnidId As Integer
		Dim lstrGrTar As String
		Dim lstrSituacao As String
		Dim lstrMedidor As String
		Dim ldblValor As Double
		Dim lstrEndereco As String
		Dim ldteVecto As Date
		Dim ldtePrazo As Date
		Dim ldtePedidoPrazo As Date
		Dim ldteReaviso As Date
		Dim lstrCodBarra As String
		Dim lstrDvCodBarra As String
		Dim lintLinha As Short
		Dim llngOrdImp As Integer
		Dim llngDiasNr As Integer
		Dim llngDiasBx As Integer
		Dim lstrApSaude As String
		Dim lstrSql As String

		Try
			Call AjustaOrdemGrid()
			llngDiasNr = CInt(GetConfig("reaviso.prazo.normal.dias"))
			llngDiasBx = CInt(GetConfig("reaviso.prazo.tsee.dias"))

			'Exclui os registros da tabela temporária desse usuario
			lstrSql = "DELETE FROM AUX_REL_REAVISO WHERE nm_usuario = '" & My.Computer.Name & "'"
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

			lintLinha = 1
			With Me.mfgDados
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, .Rows - 1)
				While lintLinha < .Rows

					If Me.ProgressBar.Value = 592 Then
						Dim para = "aqui"
					End If

					lstrZona = Mid(.get_TextMatrix(lintLinha, 1), 1, 3)
					lstrLivro = Mid(.get_TextMatrix(lintLinha, 1), 5, 2)
					lstrConta = Mid(.get_TextMatrix(lintLinha, 1), 8, 6)
					lstrRota = Replace(.get_TextMatrix(lintLinha, 2), ".", "")
					lstrNome = Trim(.get_TextMatrix(lintLinha, 3))
					lstrClasse = Trim(.get_TextMatrix(lintLinha, 17))
					lstrApSaude = Trim(.get_TextMatrix(lintLinha, 18))
					ldteVecto = CDate(.get_TextMatrix(lintLinha, 4))
					ldblNumNf = CDbl(.get_TextMatrix(lintLinha, 5))
					lstrMesAno = Trim(.get_TextMatrix(lintLinha, 6))
					llngConsId = CInt(.get_TextMatrix(lintLinha, 7))
					llngUnidId = CInt(.get_TextMatrix(lintLinha, 8))
					lstrGrTar = .get_TextMatrix(lintLinha, 9)
					lstrEndereco = .get_TextMatrix(lintLinha, 11)
					lstrMedidor = .get_TextMatrix(lintLinha, 12)
					ldblValor = CDbl(IIf(.get_TextMatrix(lintLinha, 13) = "", 0, .get_TextMatrix(lintLinha, 13)))
					lstrSituacao = Trim(.get_TextMatrix(lintLinha, 14)) 'P = prazo, V = sem prazo(a vista)
					llngOrdImp = CInt(.get_TextMatrix(lintLinha, 15))
					ldtePedidoPrazo = CDate(IIf(.get_TextMatrix(lintLinha, 16) = "00/00/0000", 0, .get_TextMatrix(lintLinha, 16)))
					ldteReaviso = Me.dtpReaviso.Value
					ldtePrazo = System.DateTime.FromOADate(ldteReaviso.ToOADate + 15)
					lstrSequencia = .get_TextMatrix(lintLinha, 19)

					lstrSql = ""
					If Not ExisteReaviso(ldblNumNf, lstrMesAno) Then
						lstrSql = lstrSql & "INSERT INTO `concorte`("
						lstrSql = lstrSql & "`zona`,"
						lstrSql = lstrSql & "`livro`,"
						lstrSql = lstrSql & "`conta`,"
						lstrSql = lstrSql & "`rota`,"
						lstrSql = lstrSql & "`codclas`,"
						lstrSql = lstrSql & "`nome`,"
						lstrSql = lstrSql & "`numnf`,"
						lstrSql = lstrSql & "`mesano`,"
						lstrSql = lstrSql & "`datareav`,"
						lstrSql = lstrSql & "`prazoreav`,"
						lstrSql = lstrSql & "`sit`,"
						lstrSql = lstrSql & "`cons_id`,"
						lstrSql = lstrSql & "`unid_id`,"
						lstrSql = lstrSql & "`ta`,"
						'lstrSql = lstrSql & "`codbarra`,"
						'lstrSql = lstrSql & "`dvcodbarra`,"
						lstrSql = lstrSql & "`situacao`,"
						lstrSql = lstrSql & "`endereco`,"
						lstrSql = lstrSql & "`medidor`,"
						lstrSql = lstrSql & "`datavenc`,"
						lstrSql = lstrSql & "`valor`, "
						lstrSql = lstrSql & "`ap_saude`, "
						lstrSql = lstrSql & "`ordimp`, `dataprazo`) VALUES("
						lstrSql = lstrSql & "'" & lstrZona & "', "
						lstrSql = lstrSql & "'" & lstrLivro & "', "
						lstrSql = lstrSql & "'" & lstrConta & "', "
						lstrSql = lstrSql & "'" & lstrRota & "', "
						lstrSql = lstrSql & "'" & lstrClasse & "', "
						lstrSql = lstrSql & "'" & lstrNome & "', "
						lstrSql = lstrSql & " " & ldblNumNf & ", "
						lstrSql = lstrSql & "'" & lstrMesAno & "', "
						lstrSql = lstrSql & "'" & VB6.Format(ldteReaviso, "yyyy-MM-dd") & "', "
						lstrSql = lstrSql & "'" & VB6.Format(ldtePrazo, "yyyy-MM-dd") & "', "
						lstrSql = lstrSql & "'R', "
						lstrSql = lstrSql & " " & llngConsId & ", "
						lstrSql = lstrSql & " " & llngUnidId & ", "
						lstrSql = lstrSql & "'" & lstrGrTar & "', "
						'lstrSql = lstrSql & " calculacodbar(" & ldblNumNf & ",""" & lstrMesAno & """), "
						'lstrSql = lstrSql & " calculadvcodbarra(codbarra), "
						lstrSql = lstrSql & "'" & lstrSituacao & "', "

						If lstrEndereco.Contains("""") Then
							lstrSql = lstrSql & "'" & lstrEndereco & "', "
						Else
							lstrSql = lstrSql & """" & lstrEndereco & """, "
						End If

						'lstrSql = lstrSql & "'" & lstrEndereco & "', "
						lstrSql = lstrSql & "'" & lstrMedidor & "', "
						lstrSql = lstrSql & "'" & VB6.Format(ldteVecto, "yyyy-MM-dd") & "', "
						lstrSql = lstrSql & " " & Replace(CStr(ldblValor), ",", ".") & ", "
						lstrSql = lstrSql & " " & IIf(lstrApSaude = "N", 0, 1) & ", "
						lstrSql = lstrSql & " " & llngOrdImp & ", '" & VB6.Format(ldtePedidoPrazo, "yyyy-MM-dd") & "') "
						'Chamar funcao para atualizar o historico da UC
						Call AtualizaHistoricoUnidade(llngUnidId, Mid(lstrGrTar, 3, 1), "EMITIDO REAVISO DA FATURA: " & ldblNumNf & " " & lstrMesAno & " EM: " & Format(ldteReaviso, "dd/mm/yyyy"))
					Else
						' ----- Monta o Update
						lstrSql = lstrSql & "UPDATE `concorte` "
						lstrSql = lstrSql & "   SET `concorte`.`prazoreav` = '" & VB6.Format(ldtePrazo, "yyyy-MM-dd") & "', "
						lstrSql = lstrSql & "       `concorte`.`datareav`  = '" & VB6.Format(ldteReaviso, "yyyy-MM-dd") & "', "
						lstrSql = lstrSql & "       `concorte`.`dataprazo`  = '" & VB6.Format(ldtePedidoPrazo, "yyyy-MM-dd") & "', "
						lstrSql = lstrSql & "       `concorte`.`ordimp`  = " & llngOrdImp & " "
						lstrSql = lstrSql & " WHERE `concorte`.`zona`  = '" & lstrZona & "' "
						lstrSql = lstrSql & "   AND `concorte`.`livro` = '" & lstrLivro & "' "
						lstrSql = lstrSql & "   AND `concorte`.`conta` = '" & lstrConta & "' "
						lstrSql = lstrSql & "   AND `concorte`.`numnf` = " & ldblNumNf & " "
						lstrSql = lstrSql & "   AND `concorte`.`mesano` = '" & lstrMesAno & "' "
						Call AtualizaHistoricoUnidade(llngUnidId, Mid(lstrGrTar, 3, 1), "REEMITIDO REAVISO DA FATURA: " & ldblNumNf & " " & lstrMesAno & " EM: " & Format(ldteReaviso, "dd/mm/yyyy"))
					End If
					objAtualizaBancoDados.QUERY_NAME = lstrSql
					repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

					'tempreaviso
					lstrSql = ""
					'lstrSql = lstrSql & "INSERT INTO `tempreaviso`("
					lstrSql = lstrSql & "INSERT INTO `AUX_REL_REAVISO`("
					lstrSql = lstrSql & "`nm_usuario`,"
					lstrSql = lstrSql & "`zona`,"
					lstrSql = lstrSql & "`livro`,"
					lstrSql = lstrSql & "`conta`,"
					lstrSql = lstrSql & "`rota`,"
					lstrSql = lstrSql & "`sequencia`,"
					lstrSql = lstrSql & "`nome`,"
					lstrSql = lstrSql & "`numnf`,"
					lstrSql = lstrSql & "`mesano`,"
					lstrSql = lstrSql & "`DATAREAV`,"
					lstrSql = lstrSql & "`sit`,"
					lstrSql = lstrSql & "`cons_id`,"
					lstrSql = lstrSql & "`unid_id`,"
					lstrSql = lstrSql & "`ta`,"
					lstrSql = lstrSql & "`situacao`,"
					lstrSql = lstrSql & "`endereco`,"
					lstrSql = lstrSql & "`medidor`,"
					lstrSql = lstrSql & "`DATAVENC`,"
					lstrSql = lstrSql & "`valor`, "
					lstrSql = lstrSql & "`ordimp`,"
					lstrSql = lstrSql & "`codclas`,"
					lstrSql = lstrSql & "`dias`) VALUES("
					lstrSql = lstrSql & "'" & My.Computer.Name & "', "
					lstrSql = lstrSql & "'" & lstrZona & "', "
					lstrSql = lstrSql & "'" & lstrLivro & "', "
					lstrSql = lstrSql & "'" & lstrConta & "', "
					lstrSql = lstrSql & "'" & lstrRota & "', "
					lstrSql = lstrSql & "'" & lstrSequencia & "', "
					lstrSql = lstrSql & "'" & lstrNome & "', "
					lstrSql = lstrSql & " " & ldblNumNf & ", "
					lstrSql = lstrSql & "'" & lstrMesAno & "', "
					lstrSql = lstrSql & "'" & VB6.Format(ldteReaviso, "dd/MM/yyyy") & "', "
					lstrSql = lstrSql & "'R', "
					lstrSql = lstrSql & " " & llngConsId & ", "
					lstrSql = lstrSql & " " & llngUnidId & ", "
					lstrSql = lstrSql & "'" & lstrGrTar & "', "
					lstrSql = lstrSql & "'" & lstrSituacao & "', "

					If lstrEndereco.Contains("""") Then
						lstrSql = lstrSql & "'" & lstrEndereco & "', "
					Else
						lstrSql = lstrSql & """" & lstrEndereco & """, "
					End If

					'lstrSql = lstrSql & "'" & lstrEndereco & "', "
					lstrSql = lstrSql & "'" & lstrMedidor & "', "
					lstrSql = lstrSql & "'" & VB6.Format(ldteVecto, "dd/MM/yyyy") & "', "
					lstrSql = lstrSql & " " & Replace(CStr(ldblValor), ",", ".") & ", "
					lstrSql = lstrSql & " " & llngOrdImp & ", "
					lstrSql = lstrSql & "'" & lstrClasse & "', "
					If lstrClasse = "9102" Or lstrClasse = "9104" Or lstrClasse = "9105" Or lstrClasse = "9106" Then
						lstrSql = lstrSql & " " & llngDiasBx & ") "
					Else
						lstrSql = lstrSql & " " & llngDiasNr & ") "
					End If
					objAtualizaBancoDados.QUERY_NAME = lstrSql
					repositorioAtualizaBancoDados.Execute(objAtualizaBancoDados)

					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
					lintLinha = lintLinha + 1
					System.Windows.Forms.Application.DoEvents()
				End While
			End With

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

	Private Sub CarregarGrid()
		'Dados unidade consumidora
		Dim lstrCc As String
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrRota As String
		Dim lstrClasse As String
		Dim lstrNome As String
		Dim lstrNomeC As String
		Dim ldblNumNf As Double
		Dim lstrMesAno As String
		Dim llngConsId As Integer
		Dim llngUnidId As Integer
		Dim llngSeq As Integer
		Dim lstrGrTar As String
		Dim lstrSituacao As String
		Dim lstrPagoGov As String
		Dim lstrVipComercial As String
		Dim lstrSitPrazo As String
		Dim lstrMedidor As String
		Dim lstrApSaude As String
		Dim ldblValorLiq As Double
		Dim ldblValorTot As Double
		Dim lintEntrega As Short
		Dim lstrEndereco As String
		Dim lstrEndEntrega As String
		Dim lstrNumEntrega As String
		Dim lstrBaiEntrega As String
		Dim lstrComEntrega As String
		Dim lstrDisEntrega As String
		Dim lstrCidEntrega As String
		Dim lstrQuaEntrega As String
		Dim lstrLotEntrega As String
		Dim lstrEndUc As String
		Dim lstrNumUc As String
		Dim lstrBaiUc As String
		Dim lstrComUc As String
		Dim lstrDisUc As String
		Dim lstrCidUc As String
		Dim lstrQuaUc As String
		Dim lstrLotUc As String
		'Controle das datas
		Dim lintToler As Short
		Dim ldteVecto As Date
		Dim ldtePrazo As Date
		'Filtros e selects
		Dim lstrMensagem As String
		Dim lintLinha As Short
		Dim lstrAux As String
		Dim lstrSqlFiA As String
		Dim lstrSqlFiB As String
		Dim lstrSqlUc As String
		Dim lstrSqlC As String
		Dim lstrSqlNf As String

		Try
			ldteVecto = Me.dtpVecto.Value
			Call MontaGrid()

			lintToler = CShort(GetConfig("reaviso.tolerancia.dias"))
			If lintToler < 0 Then lintToler = 0
			ldteVecto = System.DateTime.FromOADate(ldteVecto.ToOADate - lintToler)

			lstrAux = "  "
			lstrSqlFiA = ""
			'lstrSqlFiB = ""
			' ----- Filtra Por Rota
			If Me.opbRota.Checked Then
				With Me.lsvRotas
					If .Items.Count > 0 Then
						'If .Items.Item(1).Checked = False Then
						For lintLinha = 0 To .Items.Count - 1
							If .Items.Item(lintLinha).Checked = True Then
								lstrAux = lstrAux & "'" & .Items.Item(lintLinha).Text & "',"
							End If
						Next lintLinha
						'End If
					End If
				End With
			End If

			If Len(Trim(lstrAux)) > 0 Then
				'lstrSqlFiB = " AND MID(`unidb`.`rota`,1,4) IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
				lstrSqlFiA = " AND MID(`uc_faturamento`.`rota`,1,4) IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
			End If
			lstrSqlNf = ""
			lstrSqlNf = lstrSqlNf & "SELECT "
			lstrSqlNf = lstrSqlNf & "       `nf`.`numnf`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`mesano`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`mesano_ref`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`datavenc`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`dataprazo`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`valorliq`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`valortot`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`zona`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`livro`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`conta`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`cons_id`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`unid_id`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`rota`, "
			lstrSqlNf = lstrSqlNf & "       `nf`.`codclas`, "
			lstrSqlNf = lstrSqlNf & "       `uc`.`sequencia` "
			lstrSqlNf = lstrSqlNf & "  FROM `nf` "
			lstrSqlNf = lstrSqlNf & "  LEFT JOIN `uc_faturamento` `uc` ON `uc`.`id` = `nf`.`unid_id`"
			lstrSqlNf = lstrSqlNf & "  WHERE `nf`.`flgst`    <> 'C' "
			lstrSqlNf = lstrSqlNf & "  AND `nf`.`datavenc` <= '" & VB6.Format(ldteVecto, "yyyy-MM-dd") & "' "
			lstrSqlNf = lstrSqlNf & "  AND (`nf`.`datapag` = '0000-00-00' OR `nf`.`datapag` IS NULL OR `nf`.`datapag` = '1900-01-01') "
			If Me.chkIncluirGrupoA.CheckState = 0 Then
				lstrSqlNf = lstrSqlNf & "   AND `nf`.`grupo` <> 'A' "
			End If
			If Me.txtValor.Text <> "" Then
				If CDbl(IIf(IsNumeric(Me.txtValor.Text), Me.txtValor.Text, 0)) > 0 Then
					lstrSqlNf = lstrSqlNf & "   AND `nf`.`valorliq` > " & Replace(Me.txtValor.Text, ",", ".") & ""
				End If
			End If
			lstrSqlNf = lstrSqlNf & "   AND EXISTS(SELECT * "
			lstrSqlNf = lstrSqlNf & "                FROM `uc_faturamento` "
			lstrSqlNf = lstrSqlNf & "               WHERE `uc_faturamento`.`id` = `nf`.`unid_id` "
			lstrSqlNf = lstrSqlNf & "                 AND `uc_faturamento`.`cons_id` = `nf`.`cons_id` "
			lstrSqlNf = lstrSqlNf & lstrSqlFiA & ")" '& " UNION "
			'lstrSqlNf = lstrSqlNf & "              SELECT * "
			'lstrSqlNf = lstrSqlNf & "                FROM `unida` "
			'lstrSqlNf = lstrSqlNf & "               WHERE `unida`.`unid_id` = `nf`.`unid_id` "
			'lstrSqlNf = lstrSqlNf & "                 AND `unida`.`cons_id` = `nf`.`cons_id` "
			'lstrSqlNf = lstrSqlNf & lstrSqlFiA & ") "

			' ----- Filtro Banco
			lstrAux = "  "
			With Me.lsvBancos
				If .Items.Item(1).Checked = False Then
					For lintLinha = 4 To .Items.Count - 1
						If .Items.Item(lintLinha).Checked = True Then
							lstrAux = lstrAux & "'" & VB6.Format(CStr(.Items.Item(lintLinha).SubItems(3).Text), "000") & "', "
						End If
					Next lintLinha
				End If
			End With
			lstrAux = Trim(lstrAux)

			If Len(Trim(lstrAux)) > 0 Then
				lstrSqlNf = lstrSqlNf & " AND `nf`.`banco_fatur` IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
			End If
			If Me.chkIncluirJudice.CheckState = 0 Then
				lstrSqlNf = lstrSqlNf & " AND `nf`.`flgst` <> ""J"" "
			End If
			If Me.chkIncluirReserva.CheckState = 0 Then
				lstrSqlNf = lstrSqlNf & " AND `nf`.`flgst` <> ""R"" "
			End If
			If Me.chkIncluirPublico.CheckState = 0 Then
				lstrSqlNf = lstrSqlNf & " AND LEFT(TRIM(`nf`.`codclas`), 2) NOT IN (""61"",""62"",""63"") "
			End If
			If Me.chkIncluirIlumPub.CheckState = 0 Then
				lstrSqlNf = lstrSqlNf & " AND LEFT(TRIM(`nf`.`codclas`), 2) <> ""64"" "
			End If
			If Me.chkIncluirConsProp.CheckState = 0 Then
				lstrSqlNf = lstrSqlNf & " AND LEFT(TRIM(`nf`.`codclas`), 1) <> ""8"" "
			End If
			If Me.opbIndividual.Checked Then
				lstrSqlNf = lstrSqlNf & " AND `nf`.`zona`  = '" & Me.txtZona.Text & "' "
				lstrSqlNf = lstrSqlNf & " AND `nf`.`livro` = '" & Me.txtLivro.Text & "' "
				lstrSqlNf = lstrSqlNf & " AND `nf`.`conta` = '" & Me.txtConta.Text & "' "
			End If
			'lstrSqlNf = lstrSqlNf & " AND `nf`.`anomes_fat` = 202304"

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

			If dt.Rows.Count <> 0 Then
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, dt.Rows.Count)
				Me.lblInfo.Text = " Aguarde, processando..."
				Call Me.lblInfo.Refresh()
				Me.mfgDados.Redraw = False
				Me.mfgNaoEntrou.Redraw = False

				For Each row As DataRow In dt.Rows
					ldblNumNf = IIf(IsDBNull(row("numnf")), 0, row("numnf"))
					lstrMesAno = Trim(IIf(IsDBNull(row("mesano")), "00/0000", row("mesano")))
					ldteVecto = CDate(VB6.Format(Trim(IIf(IsDBNull(row("datavenc")), "1900-01-01", row("datavenc"))), "dd/mm/yyyy"))
					ldtePrazo = CDate(VB6.Format(Trim(IIf(IsDBNull(row("dataprazo")), "1900-01-01", row("dataprazo"))), "dd/mm/yyyy"))
					ldblValorLiq = IIf(IsDBNull(row("valorliq")), 0, row("valorliq"))
					ldblValorTot = IIf(IsDBNull(row("valortot")), 0, row("valortot"))
					lstrZona = VB6.Format(Trim(IIf(IsDBNull(row("zona")), "0", row("zona"))), "000")
					lstrLivro = VB6.Format(Trim(IIf(IsDBNull(row("livro")), "0", row("livro"))), "00")
					lstrConta = VB6.Format(Trim(IIf(IsDBNull(row("conta")), "0", row("conta"))), "000000")
					llngConsId = IIf(IsDBNull(row("cons_id")), 0, row("cons_id"))
					llngUnidId = IIf(IsDBNull(row("unid_id")), 0, row("unid_id"))
					llngSeq = IIf(IsDBNull(row("sequencia")), 0, row("sequencia"))
					lstrRota = Trim(IIf(IsDBNull(row("rota")), "0", row("rota")))
					lstrClasse = Trim(IIf(IsDBNull(row("codclas")), "0", row("codclas")))
					lstrSitPrazo = IIf(ldtePrazo > ldteVecto, "P", "V")
					lstrMensagem = ""

					If ExisteReaviso(ldblNumNf, lstrMesAno, (Me.dtpReaviso.Value), lstrMensagem) = False Then
						'Pega os dados do consumidor
						lstrSqlC = ""
						lstrSqlC = lstrSqlC & "SELECT `consum`.`nome` "
						lstrSqlC = lstrSqlC & "  FROM `consum` "
						lstrSqlC = lstrSqlC & " WHERE `consum`.`consreg` = " & llngConsId
						objAtualizaBancoDados.QUERY_NAME = lstrSqlC
						dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

						If dt2.Rows.Count <> 0 Then
							For Each row1 As DataRow In dt2.Rows
								lstrNomeC = Trim(IIf(IsDBNull(row1("nome")), "", row1("nome")))
							Next
						End If

						lstrMensagem = ""
						lstrSqlUc = ""
						lstrSqlUc = lstrSqlUc & "SELECT "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`zona`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`livro`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`conta`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`id`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`cons_id`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`rota`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`sequencia`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`nome`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`ta`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`situacao`, "
						'lstrSqlUc = lstrSqlUc & "       `unidb`.`pagto_governo`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`vip_comercial`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`num` AS `medidor`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`cc`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`end_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`num_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`compl_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`bai_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`dis_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`cid_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`qua_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`lot_entrega`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`end`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`numero`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`complement`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`bairro`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`distrito`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`cidade`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`quadra`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`lote`, "
						lstrSqlUc = lstrSqlUc & "       `uc_faturamento`.`ap_saude` "
						lstrSqlUc = lstrSqlUc & "  FROM `uc_faturamento` "
						lstrSqlUc = lstrSqlUc & " WHERE `uc_faturamento`.`zona`      = '" & lstrZona & "' "
						lstrSqlUc = lstrSqlUc & "   AND `uc_faturamento`.`livro`     = '" & lstrLivro & "' "
						lstrSqlUc = lstrSqlUc & "   AND `uc_faturamento`.`conta`     = '" & lstrConta & "' "
						lstrSqlUc = lstrSqlUc & "   AND `uc_faturamento`.`id`   = " & llngUnidId & " "
						lstrSqlUc = lstrSqlUc & "   AND `uc_faturamento`.`cons_id`   = " & llngConsId & " "
						'Rotas
						lstrSqlUc = lstrSqlUc & lstrSqlFiB
						objAtualizaBancoDados.QUERY_NAME = lstrSqlUc
						dt3 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


						If dt3.Rows.Count <> 0 Then
							For Each row3 As DataRow In dt3.Rows
								lstrCc = Trim(IIf(IsDBNull(row3("cc")), "", row3("cc")))
								lstrRota = Trim(IIf(IsDBNull(row3("rota")), "0", row3("rota")))
								llngSeq = IIf(IsDBNull(row3("sequencia")), 0, row3("sequencia"))
								lstrNome = Trim(IIf(IsDBNull(row3("nome")), "", row3("nome")))
								'Se o nome do consumidor for diferente ao nome da unidade consumidora, isto quer dizer que o reaviso pertence ao consumidor anterior
								'Verificar com a EFLUL se é isso que eles precisam se nao é so comentar o IF abaixo
								If lstrNome <> lstrNomeC Then
									If Me.chkGambiarra.CheckState = 1 Then
										lstrNome = lstrNomeC
									End If
								End If
								lstrGrTar = Trim(IIf(IsDBNull(row3("ta")), "01B1", row3("ta")))
								lstrSituacao = Trim(IIf(IsDBNull(row3("situacao")), "L", row3("situacao")))
								'lstrPagoGov = Trim(IIf(IsNull(row3("pagto_governo")), "N", row3("pagto_governo")))
								lstrVipComercial = Trim(IIf(IsDBNull(row3("vip_comercial")), "N", row3("vip_comercial")))
								lstrMedidor = Trim(IIf(IsDBNull(row3("medidor")), "", row3("medidor")))
								lstrApSaude = Trim(IIf(IsDBNull(row3("ap_saude")), "N", row3("ap_saude")))
								If lstrApSaude = "" Then lstrApSaude = "N"
								lintEntrega = CShort(IIf(IsDBNull(row3("entrega")), "0", row3("entrega")))
								lstrEndEntrega = Trim(IIf(IsDBNull(row3("end_entrega")), "", row3("end_entrega")))
								lstrNumEntrega = Trim(IIf(IsDBNull(row3("num_entrega")), "", row3("num_entrega")))
								lstrBaiEntrega = Trim(IIf(IsDBNull(row3("bai_entrega")), "", row3("bai_entrega")))
								lstrComEntrega = Trim(IIf(IsDBNull(row3("compl_entrega")), "", row3("compl_entrega")))
								lstrDisEntrega = Trim(IIf(IsDBNull(row3("dis_entrega")), "", row3("dis_entrega")))
								lstrCidEntrega = Trim(IIf(IsDBNull(row3("cid_entrega")), "", row3("cid_entrega")))
								lstrQuaEntrega = Trim(IIf(IsDBNull(row3("qua_entrega")), "", row3("qua_entrega")))
								lstrLotEntrega = Trim(IIf(IsDBNull(row3("lot_entrega")), "", row3("lot_entrega")))
								lstrEndUc = Trim(IIf(IsDBNull(row3("end")), "", row3("end")))
								lstrNumUc = Trim(IIf(IsDBNull(row3("numero")), "", row3("numero")))
								lstrBaiUc = Trim(IIf(IsDBNull(row3("bairro")), "", row3("bairro")))
								lstrComUc = Trim(IIf(IsDBNull(row3("complement")), "", row3("complement")))
								lstrDisUc = Trim(IIf(IsDBNull(row3("distrito")), "", row3("distrito")))
								lstrCidUc = Trim(IIf(IsDBNull(row3("cidade")), "", row3("cidade")))
								lstrQuaUc = Trim(IIf(IsDBNull(row3("quadra")), "", row3("quadra")))
								lstrLotUc = Trim(IIf(IsDBNull(row3("lote")), "", row3("lote")))
								If Me.chkEntrega.CheckState = 1 And lintEntrega = 1 Then
									lstrEndereco = lstrEndEntrega
									If Len(lstrNumEntrega) > 0 Then
										lstrEndereco = lstrEndereco & ", " & lstrNumEntrega
									End If
									If Len(lstrComEntrega) > 0 Then
										lstrEndereco = lstrEndereco & " - " & Trim(lstrComEntrega)
									End If
									If Len(lstrQuaEntrega) > 0 Then
										lstrEndereco = lstrEndereco & " Q:" & Trim(lstrQuaEntrega)
									End If
									If Len(lstrLotEntrega) > 0 Then
										lstrEndereco = lstrEndereco & " L:" & Trim(lstrLotEntrega)
									End If
									If Len(lstrBaiEntrega) > 0 Then
										lstrEndereco = lstrEndereco & " - " & lstrBaiEntrega
									End If
									If Len(lstrDisEntrega) > 0 And lstrDisEntrega <> "GERAL" Then
										lstrEndereco = lstrEndereco & " - " & lstrDisEntrega
									End If
									If Len(lstrCidEntrega) > 0 Then
										lstrEndereco = lstrEndereco & " - " & lstrCidEntrega
									End If
								Else
									lstrEndereco = lstrEndUc
									If Len(lstrNumUc) > 0 Then
										lstrEndereco = lstrEndereco & ", " & lstrNumUc
									End If
									If Len(lstrComUc) > 0 Then
										lstrEndereco = lstrEndereco & " - " & Trim(lstrComUc)
									End If
									If Len(lstrQuaUc) > 0 Then
										lstrEndereco = lstrEndereco & " Q:" & Trim(lstrQuaUc)
									End If
									If Len(lstrLotUc) > 0 Then
										lstrEndereco = lstrEndereco & " L:" & Trim(lstrLotUc)
									End If
									If Len(lstrBaiUc) > 0 Then
										lstrEndereco = lstrEndereco & " - " & lstrBaiUc
									End If
									If Len(lstrDisUc) > 0 And lstrDisUc <> "GERAL" Then
										lstrEndereco = lstrEndereco & " - " & lstrDisUc
									End If
									If Len(lstrCidUc) > 0 Then
										lstrEndereco = lstrEndereco & " - " & lstrCidUc
									End If
								End If
								If Me.chkIncluirDesligados.CheckState = 0 And lstrSituacao = "D" Then
									lstrMensagem = "U.C. já desligada!"
								End If
								If Me.chkIncluirCortados.CheckState = 0 And lstrSituacao = "C" Then
									lstrMensagem = "U.C. já cortada!"
								End If
								'If Me.chkIncluirPagtoGoverno.Value = 0 And lstrPagoGov = "S" Then
								'  lstrMensagem = "U.C. paga pelo governo!"
								'End If
								If lstrVipComercial = "S" Then
									lstrMensagem = "U.C. Vip Corte!"
								End If
								If Len(Trim(lstrMensagem)) = 0 Then
									With Me.mfgDados
										.Rows = .Rows + 1
										.FillStyle = MSFlexGridLib.FillStyleSettings.flexFillRepeat
										If lstrSituacao <> "L" Then
											.Row = .Rows - 1
											.Col = 0
											.ColSel = .Cols - 1
											.CellForeColor = System.Drawing.ColorTranslator.FromOle(&HFF)
										Else
											.Row = .Rows - 1
											.Col = 0
											.ColSel = .Cols - 1
											.CellForeColor = System.Drawing.ColorTranslator.FromOle(&H80000008)
										End If
										.FillStyle = MSFlexGridLib.FillStyleSettings.flexFillSingle
										.set_TextMatrix(.Rows - 1, 0, .Rows - 1)
										.set_TextMatrix(.Rows - 1, 1, lstrZona & "." & lstrLivro & "." & lstrConta)
										.set_TextMatrix(.Rows - 1, 2, lstrRota)
										.set_TextMatrix(.Rows - 1, 3, lstrNome)
										.set_TextMatrix(.Rows - 1, 4, IIf(ldteVecto = CDate("01/01/1900"), "00/00/0000", ldteVecto))
										.set_TextMatrix(.Rows - 1, 5, ldblNumNf)
										.set_TextMatrix(.Rows - 1, 6, lstrMesAno)
										'Colunas Ocultas
										.set_TextMatrix(.Rows - 1, 7, llngConsId)
										.set_TextMatrix(.Rows - 1, 8, llngUnidId)
										.set_TextMatrix(.Rows - 1, 9, lstrGrTar)
										.set_TextMatrix(.Rows - 1, 10, lstrSituacao)
										.set_TextMatrix(.Rows - 1, 11, lstrEndereco)
										.set_TextMatrix(.Rows - 1, 12, lstrMedidor)
										.set_TextMatrix(.Rows - 1, 13, IIf(ldblValorLiq <> 0, ldblValorLiq, ldblValorTot))
										.set_TextMatrix(.Rows - 1, 14, lstrSitPrazo)
										.set_TextMatrix(.Rows - 1, 16, IIf(ldtePrazo = CDate("01/01/1900"), "00/00/0000", ldtePrazo))
										.set_TextMatrix(.Rows - 1, 17, lstrClasse)
										.set_TextMatrix(.Rows - 1, 18, lstrApSaude)
										.set_TextMatrix(.Rows - 1, 19, llngSeq)
									End With
								End If
							Next
						Else
							lstrMensagem = "Esta U.C. já pertence a outro consumidor!"
						End If

					Else
						lstrMensagem = "Já existe reaviso em " & lstrMensagem & "!"
					End If
					If Len(Trim(lstrMensagem)) > 0 Then
						With Me.mfgNaoEntrou
							.Rows = .Rows + 1
							.set_TextMatrix(.Rows - 1, 0, .Rows - 1)
							.set_TextMatrix(.Rows - 1, 1, lstrZona & "." & lstrLivro & "." & lstrConta)
							.set_TextMatrix(.Rows - 1, 2, lstrRota)
							.set_TextMatrix(.Rows - 1, 3, lstrMensagem)
							.set_TextMatrix(.Rows - 1, 4, IIf(ldteVecto = CDate("01/01/1900"), "00/00/0000", ldteVecto))
							.set_TextMatrix(.Rows - 1, 5, ldblNumNf)
							.set_TextMatrix(.Rows - 1, 6, lstrMesAno)
							.set_TextMatrix(.Rows - 1, 18, lstrApSaude)
							.set_TextMatrix(.Rows - 1, 19, llngSeq)
						End With
					End If
					''Call .MoveNext()
					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
					System.Windows.Forms.Application.DoEvents()
				Next
			End If

			With Me.mfgDados
				.FillStyle = MSFlexGridLib.FillStyleSettings.flexFillRepeat
				If .Rows > 1 Then
					.Row = 1
					.Col = 1
					.ColSel = .Cols - 1
				End If
				.FillStyle = MSFlexGridLib.FillStyleSettings.flexFillSingle
				.Redraw = True
			End With
			Me.mfgNaoEntrou.Redraw = True

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

	End Sub

	Private Function ExisteReaviso(ByVal adblNumNf As Double, ByVal astrMesAno As String, Optional ByVal adteReaviso As Date = Nothing, Optional ByRef astrMensagem As String = "") As Boolean
		Dim lstrSituacao As String
		Dim ldteReaviso As Date
		Dim ldtePrazoRe As Date
		Dim ldteAux As Date
		Dim lstrSql As String
		Try
			ldteAux = Date.Now
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `concorte`.`sit`, "
			lstrSql = lstrSql & "       `concorte`.`datareav`, "
			lstrSql = lstrSql & "       `concorte`.`prazoreav`, "
			lstrSql = lstrSql & "       `concorte`.`numnf`, "
			lstrSql = lstrSql & "       `concorte`.`mesano` "
			lstrSql = lstrSql & " FROM concorte "
			lstrSql = lstrSql & "  WHERE numnf = " & adblNumNf & " "
			lstrSql = lstrSql & "    AND mesano = '" & astrMesAno & "' "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


			If dt.Rows.Count <> 0 Then
				For Each row As DataRow In dt.Rows
					If adteReaviso <> CDate("01/01/1900") Then
						lstrSituacao = IIf(IsDBNull(row("sit")), "R", row("sit"))
						ldteReaviso = CDate(VB6.Format(Trim(IIf(IsDBNull(row("datareav")), "1900-01-01", row("datareav"))), "dd/MM/yyyy"))
						ldtePrazoRe = CDate(VB6.Format(Trim(IIf(IsDBNull(row("prazoreav")), "1900-01-01", row("prazoreav"))), "dd/MM/yyyy"))
						If ldteReaviso <> CDate("01/01/1900") Then
							astrMensagem = VB6.Format(ldteReaviso, "dd/MM/yyyy") & IIf(lstrSituacao = "E", IIf(ldtePrazoRe < ldteAux, "-Praz.Vec.", "-Entregue"), "")
						End If
						If ldteReaviso = CDate(VB6.Format(adteReaviso, "dd/MM/yyyy")) And (lstrSituacao = "R" Or (lstrSituacao = "E" And ldtePrazoRe < CDate(Format(ldteAux, "dd/MM/yyyy")))) Then
							ExisteReaviso = False
						Else
							ExisteReaviso = True
						End If
					Else
						ExisteReaviso = True
					End If
				Next
			Else
				ExisteReaviso = False
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: ExisteReaviso" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Function
		End Try
	End Function

	Private Sub AjustaOrdemGrid()
		Dim lintOrdem As Short ' Controle da ordem de impressão
		Dim lintConta As Short ' Contador
		Dim lintPivo As Short ' Número do registro do Meio
		Dim lintNumReg As Short ' Número de registros da grid
		Try
			With Me.mfgDados
				If .Rows > 1 Then
					lintNumReg = .Rows - 1
					lintPivo = Fix(lintNumReg / 2)
					lintOrdem = 1
					lintConta = 1
					While lintConta <= lintNumReg
						If lintConta = (lintPivo + 1) Then
							lintOrdem = 2
						End If
						.set_TextMatrix(lintConta, 15, lintOrdem)
						lintConta = lintConta + 1
						lintOrdem = lintOrdem + 2
					End While
				End If
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: AjustaOrdemGrid" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub CarregaRotas()
		Dim lstrRota As String
		Dim lstrGrupo As String
		Dim lstrSql As String
		Try

			' ----- Monta as colunas na ListView de rotas
			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

			' ----- Busca as rotas
			lstrSql = ""
			lstrSql = lstrSql & "SELECT DISTINCT cast( MID(`u`.`rota`,1,4) as decimal) AS `rotagrupo`, MID(`u`.`ta`,3,1) AS `grupo` "
			'lstrSql = lstrSql & "  FROM `uc_faturamento` AS `u` USE INDEX(keyrota) "
			lstrSql = lstrSql & "  FROM `uc_faturamento` AS `u` USE INDEX(idx_rota) "
			lstrSql = lstrSql & " WHERE `u`.situacao = ""L"" "
			'lstrSql = lstrSql & " UNION "
			'lstrSql = lstrSql & "SELECT DISTINCT MID(`u`.`rota`,1,4) AS `rotagrupo`, MID(`u`.`ta`,3,1) AS `grupo`  "
			'lstrSql = lstrSql & "  FROM `unidb` AS `u` USE INDEX(keyrota)"
			'lstrSql = lstrSql & " WHERE `u`.situacao = ""L"" "
			lstrSql = lstrSql & " GROUP BY `rotagrupo`, `grupo` "
			lstrSql = lstrSql & " ORDER BY `rotagrupo` ASC, `grupo` ASC"
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


			If dt.Rows.Count <> 0 Then
				For Each row As DataRow In dt.Rows
					'lstrRota = VB6.Format(IIf(IsDBNull(row("rotagrupo")), "0", row("rotagrupo")), "0000")
					lstrRota = IIf(IsDBNull(row("rotagrupo")), "0", row("rotagrupo"))
					lstrGrupo = IIf(IsDBNull(row("grupo")), "B", row("grupo"))
					With Me.lsvRotas
						Call .Items.Add(lstrRota)
						Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrGrupo)
					End With
				Next
			End If
			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 CarregaBancos()
		Dim lstrNrBco As String
		Dim lstrNmBco As String
		Dim lstrTpMvto As String
		Dim llngBanId As Integer
		Dim lstrSql As String
		Try
			''' ----- Monta as colunas na ListView de rotas
			With Me.lsvBancos
				Call .Items.Clear()
				Call .Columns.Clear()
				If .Columns.Count <= 1 Then
					Call .Columns.Add("", "Descrição", CInt(VB6.TwipsToPixelsX(4500)))
					Call .Columns.Add("Nro", CInt(VB6.TwipsToPixelsX(700)), System.Windows.Forms.HorizontalAlignment.Center)
					Call .Columns.Add("", "Tipo", CInt(VB6.TwipsToPixelsX(0)))
					Call .Columns.Add("", "id", CInt(VB6.TwipsToPixelsX(0)))
				End If
				'Call .Items.Add("Todos os Bancos")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("000")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("T")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add(CStr(9999))
			End With

			lstrSql = "SELECT ban_id, nrbco, nmbco,tpmovto " & "  FROM bancos "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			If dt.Rows.Count <> 0 Then
				With Me.lsvBancos
					'Call .Items.Add("Somente Arrecadação")
					'Call .Items.Item(.Items.Count - 1).SubItems.Add("000")
					'Call .Items.Item(.Items.Count - 1).SubItems.Add("N")
					'Call .Items.Item(.Items.Count - 1).SubItems.Add(CStr(9998))
					'Call .Items.Add("Somente Débito Automático")
					'Call .Items.Item(.Items.Count - 1).SubItems.Add("000")
					'Call .Items.Item(.Items.Count - 1).SubItems.Add("D")
					'Call .Items.Item(.Items.Count - 1).SubItems.Add(CStr(9997))
				End With
				For Each row As DataRow In dt.Rows
					lstrNrBco = VB6.Format(IIf(IsDBNull(row("nrbco")), "0", row("nrbco")), "000")
					lstrNmBco = Trim(IIf(IsDBNull(row("nmbco")), "Indefinido", row("nmbco")))
					lstrTpMvto = UCase(Trim(IIf(IsDBNull(row("tpmovto")), "N", row("tpmovto"))))
					llngBanId = IIf(IsDBNull(row("ban_id")), 0, row("ban_id"))
					If lstrTpMvto = "D" Then
						lstrNmBco = lstrNmBco & " (Débito)"
					End If
					With Me.lsvBancos
						Call .Items.Add(lstrNmBco)
						Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrNrBco)
						Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrTpMvto)
						Call .Items.Item(.Items.Count - 1).SubItems.Add(CStr(llngBanId))
					End With
				Next
			End If
			System.Windows.Forms.Application.DoEvents()
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregaBancos" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub MontaGrid()
		Try
			With Me.mfgDados
				.Cols = 20
				.Rows = 1
				.Clear()
				.set_ColWidth(0, 700)
				.set_ColWidth(1, 1200)
				.set_ColWidth(2, 1000)
				.set_ColWidth(3, 3200)
				.set_ColWidth(4, 1000)
				.set_ColWidth(5, 900)
				.set_ColWidth(6, 700)
				.set_ColWidth(7, 0)
				.set_ColWidth(8, 0)
				.set_ColWidth(9, 0)
				.set_ColWidth(10, 0)
				.set_ColWidth(11, 0)
				.set_ColWidth(12, 0)
				.set_ColWidth(13, 0)
				.set_ColWidth(14, 0)
				.set_ColWidth(15, 0)
				.set_ColWidth(16, 0)
				.set_ColWidth(17, 0)
				.set_ColWidth(18, 0)
				.set_ColWidth(19, 0)
				.set_ColAlignment(0, MSFlexGridLib.AlignmentSettings.flexAlignRightCenter)
				.set_ColAlignment(1, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_ColAlignment(2, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_ColAlignment(3, MSFlexGridLib.AlignmentSettings.flexAlignLeftCenter)
				.set_ColAlignment(4, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_ColAlignment(5, MSFlexGridLib.AlignmentSettings.flexAlignRightCenter)
				.set_ColAlignment(6, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_TextMatrix(0, 0, " ")
				.set_TextMatrix(0, 1, "Identificação")
				.set_TextMatrix(0, 2, "Rota")
				.set_TextMatrix(0, 3, "Nome")
				.set_TextMatrix(0, 4, "Data Venc.")
				.set_TextMatrix(0, 5, "Número Nf")
				.set_TextMatrix(0, 6, "Mês Ano")
				'Colunas Ocultas
				.set_TextMatrix(0, 7, "Cód.Cons.")
				.set_TextMatrix(0, 8, "Cód.U.C.")
				.set_TextMatrix(0, 9, "Gr.Tarifa")
				.set_TextMatrix(0, 10, "Situação")
				.set_TextMatrix(0, 11, "Endereço")
				.set_TextMatrix(0, 12, "Medidor")
				.set_TextMatrix(0, 13, "Valor")
				.set_TextMatrix(0, 14, "Prazo")
				.set_TextMatrix(0, 15, "OrdemImp")
				.set_TextMatrix(0, 16, "DataPrazo")
				.set_TextMatrix(0, 17, "Classe")
				.set_TextMatrix(0, 18, "Ap. Saude")
				.set_TextMatrix(0, 19, "Sequencia")
			End With
			With Me.mfgNaoEntrou
				.Cols = 20
				.Rows = 1
				.Clear()
				.set_ColWidth(0, 700)
				.set_ColWidth(1, 1200)
				.set_ColWidth(2, 1000)
				.set_ColWidth(3, 3200)
				.set_ColWidth(4, 1000)
				.set_ColWidth(5, 900)
				.set_ColWidth(6, 700)
				.set_ColWidth(7, 0)
				.set_ColWidth(8, 0)
				.set_ColWidth(9, 0)
				.set_ColWidth(10, 0)
				.set_ColWidth(11, 0)
				.set_ColWidth(12, 0)
				.set_ColWidth(13, 0)
				.set_ColWidth(14, 0)
				.set_ColWidth(15, 0)
				.set_ColWidth(16, 0)
				.set_ColWidth(17, 0)
				.set_ColWidth(18, 0)
				.set_ColWidth(19, 0)
				.set_ColAlignment(0, MSFlexGridLib.AlignmentSettings.flexAlignRightCenter)
				.set_ColAlignment(1, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_ColAlignment(2, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_ColAlignment(3, MSFlexGridLib.AlignmentSettings.flexAlignLeftCenter)
				.set_ColAlignment(4, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_ColAlignment(5, MSFlexGridLib.AlignmentSettings.flexAlignRightCenter)
				.set_ColAlignment(6, MSFlexGridLib.AlignmentSettings.flexAlignCenterCenter)
				.set_TextMatrix(0, 0, " ")
				.set_TextMatrix(0, 1, "Identificação")
				.set_TextMatrix(0, 2, "Rota")
				.set_TextMatrix(0, 3, "Mensagem")
				.set_TextMatrix(0, 4, "Data Venc.")
				.set_TextMatrix(0, 5, "Número Nf")
				.set_TextMatrix(0, 6, "Mês Ano")
				'Colunas Ocultas
				.set_TextMatrix(0, 7, "Cód.Cons.")
				.set_TextMatrix(0, 8, "Cód.U.C.")
				.set_TextMatrix(0, 9, "Gr.Tarifa")
				.set_TextMatrix(0, 10, "Situação")
				.set_TextMatrix(0, 11, "Endereço")
				.set_TextMatrix(0, 12, "Medidor")
				.set_TextMatrix(0, 13, "Valor")
				.set_TextMatrix(0, 14, "Prazo")
				.set_TextMatrix(0, 15, "OrdemImp")
				.set_TextMatrix(0, 16, "DataPrazo")
				.set_TextMatrix(0, 17, "Classe")
				.set_TextMatrix(0, 18, "Ap. Saude")
				.set_TextMatrix(0, 19, "Sequencia")
			End With
			System.Windows.Forms.Application.DoEvents()
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontaGrid" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub LigDes(ByVal ablnModo As Boolean)
		Try
			'DATAS
			Me.dtpVecto.Enabled = ablnModo
			Me.dtpReaviso.Enabled = ablnModo
			'INCLUIR
			Me.chkIncluirDesligados.Enabled = ablnModo
			Me.chkIncluirCortados.Enabled = ablnModo
			Me.chkIncluirGrupoA.Enabled = ablnModo
			Me.chkIncluirPublico.Enabled = ablnModo
			Me.chkIncluirConsProp.Enabled = ablnModo
			Me.chkIncluirIlumPub.Enabled = ablnModo
			Me.chkIncluirJudice.Enabled = ablnModo
			Me.chkIncluirReserva.Enabled = ablnModo
			Me.chkIncluirPagtoGoverno.Enabled = ablnModo
			'MODO SELEÇÃO
			Me.opbRota.Enabled = ablnModo
			Me.opbIndividual.Enabled = ablnModo
			Me.lsvRotas.Enabled = Me.opbRota.Enabled
			Me.txtZona.Enabled = Me.opbIndividual.Enabled
			Me.txtLivro.Enabled = Me.opbIndividual.Enabled
			Me.txtConta.Enabled = Me.opbIndividual.Enabled
			Me.cmdBuscaUc.Enabled = Me.opbIndividual.Enabled
			'BANCOS
			Me.lsvBancos.Enabled = ablnModo
			System.Windows.Forms.Application.DoEvents()
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: LigaDes" & "", "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 dt_1 As DataTable
		Dim dt_2 As DataTable

		Dim dc As DataColumn
		Dim ds As DataSet

		Dim lstrsql As String
		Dim ldteBase As String

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

		Try
			Dim rpt As New ReportDocument()

			If vNomeRPT = "rptReavisoEflul" Then

				' CABEÇALHO
				dt_2 = New DataTable()
				dt_2.Columns.Add("NM_USUARIO", 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("SEQUENCIA", GetType(String))
				dt_2.Columns.Add("CODCLASS", GetType(String))
				dt_2.Columns.Add("NOME", GetType(String))
				dt_2.Columns.Add("NUMNF", GetType(String))
				dt_2.Columns.Add("MESANO", GetType(String))
				dt_2.Columns.Add("DATAREAV", GetType(String))
				dt_2.Columns.Add("PRAZOREAV", GetType(String))
				dt_2.Columns.Add("SIT", GetType(String))
				dt_2.Columns.Add("CONS_ID", GetType(String))
				dt_2.Columns.Add("UNID_ID", GetType(String))
				dt_2.Columns.Add("TA", GetType(String))
				dt_2.Columns.Add("CODBARRA", GetType(String))
				dt_2.Columns.Add("DVCODBARRA", GetType(String))
				dt_2.Columns.Add("SITUACAO", GetType(String))
				dt_2.Columns.Add("ENDERECO", GetType(String))
				dt_2.Columns.Add("MEDIDOR", GetType(String))
				dt_2.Columns.Add("DATAVENC", GetType(String))
				dt_2.Columns.Add("VALOR", GetType(String))
				dt_2.Columns.Add("AP_SAUDE", GetType(String))
				dt_2.Columns.Add("ORDIMP", GetType(String))
				dt_2.Columns.Add("DATAPRAZO", GetType(String))
				dt_2.Columns.Add("DIAS", GetType(String))
				dt_2.Columns.Add("IMAGEM", GetType(Byte()))

				ds = New DataSet

				' CABEÇALHO DO RELATÓRIO
				lstrsql = ""
				lstrsql = "SELECT * FROM AUX_REL_REAVISO ORDER BY CAST(`ROTA` AS UNSIGNED), CAST(`SEQUENCIA`  AS UNSIGNED)"
				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("ZONA"),
										  dr_1("LIVRO"),
										  dr_1("CONTA"),
										  dr_1("ROTA"),
										  dr_1("SEQUENCIA"),
										  dr_1("CODCLAS"),
										  dr_1("NOME"),
										  dr_1("NUMNF"),
										  dr_1("MESANO"),
										  dr_1("DATAREAV"),
										  dr_1("PRAZOREAV"),
										  dr_1("SIT"),
										  dr_1("CONS_ID"),
										  dr_1("UNID_ID"),
										  dr_1("TA"),
										  dr_1("CODBARRA"),
										  dr_1("DVCODBARRA"),
										  dr_1("SITUACAO"),
										  dr_1("ENDERECO"),
										  dr_1("MEDIDOR"),
										  dr_1("DATAVENC"),
										  dr_1("VALOR"),
										  dr_1("AP_SAUDE"),
										  dr_1("ORDIMP"),
										  dr_1("DATAPRAZO"),
										  dr_1("DIAS"),
										  Limagem)
					Next dr_1
				End If

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

				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 rptReavisoEflul

					rpt.SetDataSource(ds)

					frmViewRelatorios.rpt = rpt
					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)

					frmViewRelatorios.CRViewer.Zoom((100))
					frmViewRelatorios.Text = "Relatório de Reaviso"
					frmViewRelatorios.ShowDialog()

					dt = 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()

		Dim lstrsql As String

		Try

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

			lstrsql = ""
			lstrsql = lstrsql & "CREATE TABLE IF NOT EXISTS `AUX_REL_REAVISO` (" & vbCrLf
			lstrsql = lstrsql & "  `NM_USUARIO`   varchar(20) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `ZONA`         varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `LIVRO`        varchar(20) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `CONTA`        varchar(100) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `ROTA`         varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `SEQUENCIA`    varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `CODCLAS`      varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `NOME`         varchar(100) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `NUMNF`        varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `MESANO`       varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `DATAREAV`     varchar(50) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `PRAZOREAV`    varchar(30) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `SIT`          varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `CONS_ID`      varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `UNID_ID`      varchar(30) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `TA`           varchar(10) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `CODBARRA`     varchar(10) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `DVCODBARRA`   varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `SITUACAO`     varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `ENDERECO`     varchar(200) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `MEDIDOR`      varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `DATAVENC`     varchar(50) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `VALOR`        varchar(50) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `AP_SAUDE`     varchar(30) DEFAULT NULL,  " & vbCrLf
			lstrsql = lstrsql & "  `ORDIMP`       varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `DATAPRAZO`    varchar(30) DEFAULT NULL, " & vbCrLf
			lstrsql = lstrsql & "  `DIAS`         varchar(30) DEFAULT NULL) "
			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 chktodasrotas_CheckedChanged(sender As Object, e As EventArgs) Handles chktodasrotas.CheckedChanged

		Dim intConta As Short

		Try

			If chktodasrotas.Checked = True Then
				For intConta = 0 To lsvRotas.Items.Count - 1
					lsvRotas.Items.Item(intConta).Checked = True
				Next

			ElseIf chktodasrotas.Checked = False Then
				For intConta = 0 To lsvRotas.Items.Count - 1
					lsvRotas.Items.Item(intConta).Checked = False
				Next intConta
			End If

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

	End Sub

	Private Sub chktodosbancos_CheckStateChanged(sender As Object, e As EventArgs) Handles chktodosbancos.CheckStateChanged
		Dim intConta As Short

		Try

			If chktodosbancos.Checked = True Then

				chkarrecadacao.Checked = False
				chkdebitos.Checked = False

				For intConta = 0 To lsvBancos.Items.Count - 1
					lsvBancos.Items.Item(intConta).Checked = True
				Next
			ElseIf chktodosbancos.Checked = False Then
				For intConta = 0 To lsvBancos.Items.Count - 1
					lsvBancos.Items.Item(intConta).Checked = False
				Next intConta
			End If

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

	End Sub

	Private Sub frmReaviso_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed

		Dim lstrsql As String

		Try

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

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

	Private Sub chkarrecadacao_CheckStateChanged(sender As Object, e As EventArgs) Handles chkarrecadacao.CheckStateChanged
		Dim intConta As Short

		Try

			If chkarrecadacao.Checked = True Then

				chkdebitos.Checked = False
				chktodosbancos.Checked = False

				For intConta = 0 To lsvBancos.Items.Count - 1
					If lsvBancos.Items.Item(intConta).SubItems(2).Text = "N" Then
						lsvBancos.Items.Item(intConta).Checked = True
					Else
						lsvBancos.Items.Item(intConta).Checked = False
					End If
					'lsvBancos.Items.Item(intConta).Checked = True
				Next

			ElseIf chkarrecadacao.Checked = False Then
				For intConta = 0 To lsvBancos.Items.Count - 1
					lsvBancos.Items.Item(intConta).Checked = False
				Next intConta
			End If

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

	Private Sub chkdebitos_CheckStateChanged(sender As Object, e As EventArgs) Handles chkdebitos.CheckStateChanged
		Dim intConta As Short

		Try

			If chkdebitos.Checked = True Then

				chkarrecadacao.Checked = False
				chktodosbancos.Checked = False

				For intConta = 0 To lsvBancos.Items.Count - 1
					If lsvBancos.Items.Item(intConta).SubItems(2).Text = "D" Then
						lsvBancos.Items.Item(intConta).Checked = True
					Else
						lsvBancos.Items.Item(intConta).Checked = False
					End If
					'lsvBancos.Items.Item(intConta).Checked = True
				Next

			ElseIf chkdebitos.Checked = False Then
				For intConta = 0 To lsvBancos.Items.Count - 1
					lsvBancos.Items.Item(intConta).Checked = False
				Next intConta
			End If

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


End Class