Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Friend Class frmEntregaReaviso
	Inherits System.Windows.Forms.Form

	Private objAtualizaBancoDados As New entidadeAtualizaBancoDados
	Private repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados
	Private objExecAtualizaBancoDados As New entidadeAtualizaBancoDados
	Private repositorioExecAtualizaBancoDados As New repositorioAtualizaBancoDados
	Private dt As DataTable

	Public sExecutaAutomatico As Boolean = False
	Private sTerminouExecucao As Boolean = False
	Private sGravouExecucao As Boolean = False

	'[Rotina para buscar os reavisos com a situacao R]
	Private Sub CarregarReaviso()
		Dim lstrSql As String
		Dim lstrZLC As String
		Dim lstrRot As String
		Dim lstrNom As String
		Dim ldteRea As Date
		Dim ldblNnf As Double
		Dim lstrMes As String
		Dim lstrClasse As String
		Dim lstrSqlTipo As String
		Dim lstrAux As String
		Dim lintLinha As Short
		Try
			With Me.lvsReaviso
				Call .Items.Clear()
				Call .Columns.Clear()
				If .Columns.Count <= 1 Then
					Call .Columns.Add("", "Identificação", CInt(VB6.TwipsToPixelsX(1450)))
					Call .Columns.Add("Rota", CInt(VB6.TwipsToPixelsX(1000)), System.Windows.Forms.HorizontalAlignment.Center)
					Call .Columns.Add("Nome", CInt(VB6.TwipsToPixelsX(3200)), System.Windows.Forms.HorizontalAlignment.Left)
					Call .Columns.Add("Dt.Reav.", CInt(VB6.TwipsToPixelsX(1050)), System.Windows.Forms.HorizontalAlignment.Center)
					Call .Columns.Add("Fatura", CInt(VB6.TwipsToPixelsX(1000)), System.Windows.Forms.HorizontalAlignment.Right)
					Call .Columns.Add("Mês/Ano", CInt(VB6.TwipsToPixelsX(950)), System.Windows.Forms.HorizontalAlignment.Center)
					Call .Columns.Add("Classe", CInt(VB6.TwipsToPixelsX(950)), System.Windows.Forms.HorizontalAlignment.Center)
				End If
				'Call .Items.Add("Marcar Todos")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("")
				'Call .Items.Item(.Items.Count - 1).SubItems.Add("")
			End With

			'-----------POR ROTA ----------------
			lstrAux = "  "
			lstrSqlTipo = ""

			If Me.opbRota.Checked Then
				With Me.lsvRotas
					If .Items.Count > 0 Then
						'If .ListItems.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
				If Len(Trim(lstrAux)) > 0 Then
					'lstrSqlTipo = " AND MID(`concorte`.`rota`,1,4) IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
					lstrSqlTipo = " AND `concorte`.`rota`+0 IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
				End If
			Else ' ------------------ ZONA,LIVRO,CONTA--------------
				lstrSqlTipo = " AND `concorte`.`zona` = '" & txtZona.Text & "'  AND `concorte`.`livro` = '" & txtLivro.Text & "'  and `concorte`.`conta` = '" & txtConta.Text & "'  "
			End If

			If lstrSqlTipo <> "" Then

				lstrSql = ""
				lstrSql = lstrSql & "   SELECT `concorte`.`zona`, "
				lstrSql = lstrSql & "          `concorte`.`livro`, "
				lstrSql = lstrSql & "          `concorte`.`conta`, "
				lstrSql = lstrSql & "          `concorte`.`rota`, "
				lstrSql = lstrSql & "          `concorte`.`nome`, "
				lstrSql = lstrSql & "          `concorte`.`datareav`, "
				lstrSql = lstrSql & "          `concorte`.`numnf`, "
				lstrSql = lstrSql & "          `concorte`.`mesano`, "
				lstrSql = lstrSql & "          `nf`.`codclas`, "
				lstrSql = lstrSql & "          `nf`.`mesano`, "
				lstrSql = lstrSql & "          `nf`.`numnf` "
				lstrSql = lstrSql & "     FROM `concorte` , `nf` "
				lstrSql = lstrSql & "    WHERE `concorte`.`sit` = 'R' AND (concorte.grafica = 1 OR concorte.impressao =1 ) "
				lstrSql = lstrSql & "    AND `concorte`.`mesano` = `nf`.`mesano`"
				lstrSql = lstrSql & "    AND `concorte`.`numnf` = `nf`.`numnf`"
				lstrSql = lstrSql & " " & lstrSqlTipo & "  "
				lstrSql = lstrSql & " ORDER BY `concorte`.`rota` ASC"
				objAtualizaBancoDados.QUERY_NAME = lstrSql
				dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

				If dt.Rows.Count > 0 Then
					For Each row As DataRow In dt.Rows
						lstrZLC = ""
						lstrZLC = lstrZLC & VB6.Format(IIf(IsDBNull(row.Item("zona")), "0", row.Item("zona")), "000") & "."
						lstrZLC = lstrZLC & VB6.Format(IIf(IsDBNull(row.Item("livro")), "0", row.Item("livro")), "00") & "."
						lstrZLC = lstrZLC & VB6.Format(IIf(IsDBNull(row.Item("conta")), "0", row.Item("conta")), "000000")
						lstrRot = VB6.Format(IIf(IsDBNull(row.Item("rota")), "0", row.Item("rota")), "00000000")
						lstrRot = VB.Left(lstrRot, 4) & "." & VB.Right(lstrRot, 4)
						lstrNom = Trim(IIf(IsDBNull(row.Item("nome")), "", row.Item("nome")))
						ldteRea = CDate(IIf(IsDBNull(row.Item("datareav")), "1900-01-01", row.Item("datareav")))
						ldblNnf = CDbl(IIf(IsDBNull(row.Item("numnf")), "0", row.Item("numnf")))
						lstrMes = IIf(IsDBNull(row.Item("mesano")), "", row.Item("mesano"))
						lstrClasse = IIf(IsDBNull(row.Item("codclas")), "", row.Item("codclas"))
						With Me.lvsReaviso
							Call .Items.Add(lstrZLC)
							Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrRot)
							Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrNom)
							Call .Items.Item(.Items.Count - 1).SubItems.Add(CStr(ldteRea))
							Call .Items.Item(.Items.Count - 1).SubItems.Add(CStr(ldblNnf))
							Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrMes)
							Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrClasse)
						End With
					Next
					cmdRegistrar.Enabled = True
				End If
			Else
				If sExecutaAutomatico = False Then
					Call MsgBox("Favor selecionar alguma rota ou identificar o consumidor desejado!", MsgBoxStyle.Information, gstrTituloMensagem)
				End If
				cmdRegistrar.Enabled = False
			End If ' se lstrSql <> "" 
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregarReaviso" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try

	End Sub
	
	Private Sub RegistrarConsumidor()
		Dim lstrSql As String
		Dim lintLin As Short
		Dim lstrZon As String
		Dim lstrLiv As String
		Dim lstrCon As String
		Dim lstrZLC As String
		Dim ldblNnf As Double
		Dim lstrMes As String
		Dim lstrClasse As String
		Dim ldteReaviso As Date
		Dim ldteEntrega As Date
		Dim ldteAux As Date
		Dim astrMensagem As String
		Try
			ldteEntrega = Me.dtpEntrega.Value
			lintLin = 0
			With Me.lvsReaviso
				If sExecutaAutomatico = False Then
					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, .Items.Count - 1)
				End If
				While lintLin <= .Items.Count - 1
					If .Items.Item(lintLin).Checked Then

						ldteEntrega = Me.dtpEntrega.Value
						lstrZLC = Replace(CStr(.Items.Item(lintLin).Text), ".", "")
						lstrZon = Mid(lstrZLC, 1, 3)
						lstrLiv = Mid(lstrZLC, 4, 2)
						lstrCon = Mid(lstrZLC, 6)
						ldblNnf = CDbl(.Items.Item(lintLin).SubItems(4).Text)
						lstrMes = CStr(.Items.Item(lintLin).SubItems(5).Text)
						lstrClasse = CStr(.Items.Item(lintLin).SubItems(6).Text)
						ldteReaviso = CDate(.Items.Item(lintLin).SubItems(3).Text)
						If Me.chkEmissaoReaviso.CheckState = 1 Then
							ldteEntrega = ldteReaviso

						ElseIf Me.chkApresentaFatura.CheckState = 1 Then

							ldteAux = PegaApresentacaoFatura(ldblNnf, lstrMes, lstrZon, lstrLiv, lstrCon, ldteReaviso)
							If ldteAux <> CDate("01/01/1900") Then
								ldteEntrega = ldteAux
							End If

						End If
						''If ldteReaviso > ldteEntrega Then
						''ldteEntrega = ldteReaviso
						'Call MsgBox("A data de entrega não pode ser menor que a data do reaviso!", vbInformation, gstrTituloMensagem)
						'cmdRegistrar.Enabled = True
						'Exit Sub
						''Else
						lstrSql = ""
						lstrSql = lstrSql & "UPDATE `concorte` SET `concorte`.`sit` = 'E', "
						lstrSql = lstrSql & " `concorte`.`dataentrega` = """ & VB6.Format(ldteEntrega, "YYYY-MM-DD") & """, "
						If lstrClasse = 9105 Then
							lstrSql = lstrSql & " `concorte`.`prazoreav` = """ & VB6.Format(System.DateTime.FromOADate(ldteEntrega.ToOADate + 30), "YYYY-MM-DD") & """ "
						Else
							lstrSql = lstrSql & " `concorte`.`prazoreav` = """ & VB6.Format(System.DateTime.FromOADate(ldteEntrega.ToOADate + 15), "YYYY-MM-DD") & """ "
						End If
						lstrSql = lstrSql & " WHERE `concorte`.`sit`    = 'R' AND (concorte.grafica = 1 OR concorte.impressao =1 ) "
						lstrSql = lstrSql & "   AND `concorte`.`zona`   = '" & lstrZon & "' "
						lstrSql = lstrSql & "   AND `concorte`.`livro`  = '" & lstrLiv & "' "
						lstrSql = lstrSql & "   AND `concorte`.`conta`  = '" & lstrCon & "' "
						lstrSql = lstrSql & "   AND `concorte`.`mesano` = '" & lstrMes & "' "
						lstrSql = lstrSql & "   AND `concorte`.`numnf`  = " & ldblNnf
						objExecAtualizaBancoDados.QUERY_NAME = lstrSql
						repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

						'----- Atualiza histórico da unidade consumidora ---------------------------------------------------------
						astrMensagem = "ENTREGUE REAVISO DA FATURA: " & ldblNnf & " " & lstrMes & " EM: " & VB6.Format(Me.dtpEntrega.Value, "dd/mm/yyyy")
						lstrSql = ""
						lstrSql = "UPDATE uc_faturamento " & "   SET historico = CONCAT(IFNULL(historico, ''), IF(historico IS NULL OR LENGTH(TRIM(historico)) = 0, '', CONVERT(""\r\n"" USING latin1)), CONVERT(""" & astrMensagem & """ USING latin1)) " & " WHERE zona  = " & lstrZon & " AND livro  = " & lstrLiv & " AND conta  = " & lstrCon & "  "
						objExecAtualizaBancoDados.QUERY_NAME = lstrSql
						repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

						''End If
					End If
					lintLin = lintLin + 1
					If sExecutaAutomatico = False Then
						Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
					End If
				End While
				If sExecutaAutomatico = False Then
					Call MsgBox("Processo realizado com sucesso!", MsgBoxStyle.Information, gstrTituloMensagem)
					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 2, .Items.Count - 1)
				End If
				.Items.Item(1).Selected = True
				.Items.Item(1).EnsureVisible()
				.Enabled = True
				Call .Focus()
			End With
		Catch ex As Exception
			If sExecutaAutomatico = False Then
				MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: RegistrarConsumidor" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			End If
			Exit Sub
		End Try
	End Sub

	Private Sub cmdBuscar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBuscar.Click
		Try
			cmdRegistrar.Enabled = False
			Me.lblInfo.Text = " Aguarde...."
			Call Me.lblInfo.Refresh()
			Me.cmdBuscar.Enabled = False
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Call CarregarReaviso()
			Me.cmdBuscar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdBuscar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub cmdCancelar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancelar.Click
		Call Me.Close()
	End Sub

	Private Sub cmdLocalizar_Click()
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lintLinha As Short
		Dim lblnAchou As Boolean
		Try
			If opbRota.Checked Then
				Call CarregaRotas()
			Else

				lstrZona = VB6.Format(IIf(Trim(Me.txtZona.Text) = "", "0", Me.txtZona.Text), "000")
				lstrLivro = VB6.Format(IIf(Trim(Me.txtLivro.Text) = "", "0", Me.txtLivro.Text), "00")
				lstrConta = VB6.Format(IIf(Trim(Me.txtConta.Text) = "", "0", Me.txtConta.Text), "000000")
				If lstrZona <> "000" And lstrLivro <> "00" And lstrConta <> "000" Then
					lintLinha = 1
					With Me.lvsReaviso
						'Deseleciona tudo
						While lintLinha <= .Items.Count - 1
							.Items.Item(lintLinha).Selected = False
							lintLinha = lintLinha + 1
						End While
						lintLinha = 1
						'Busca
						While lintLinha <= .Items.Count - 1 And lblnAchou = False
							If Replace(.Items.Item(lintLinha).Text, ".", "") = lstrZona & lstrLivro & lstrConta Then
								.Items.Item(lintLinha).Selected = True
								.Items.Item(lintLinha).EnsureVisible()
								lblnAchou = True
							End If
							lintLinha = lintLinha + 1
						End While
						If lblnAchou = False Then
							Call MsgBox("Consumidor não encontrado!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
							' .ListItems.Item(1).Selected = True
							'  .ListItems.Item(1).EnsureVisible
						End If
						Call .Focus()
					End With
				End If
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdLocalizar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub cmdRegistrar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdRegistrar.Click
		Dim databd As Date
		Try
			databd = Date.Now
			If MsgBox("Confirma o registro de entrega dos reavisos marcados?", MsgBoxStyle.YesNoCancel + MsgBoxStyle.Question, gstrTituloMensagem) = MsgBoxResult.Yes Then
				Call LigDes(False)
				Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
				Call RegistrarConsumidor()
				Me.Cursor = System.Windows.Forms.Cursors.Default
				Call LigDes(True)
				Call frmEntregaReaviso_Load(Me, New System.EventArgs())
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdRegistrar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub frmEntregaReaviso_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
		Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
		Try
			If KeyAscii = System.Windows.Forms.Keys.Return Then
				TabEnter(KeyAscii, eventArgs)
			ElseIf KeyAscii = System.Windows.Forms.Keys.Escape Then
				If MsgBox("Tem certeza que deseja sair da entrega de reaviso?", MsgBoxStyle.YesNo + MsgBoxStyle.Question, gstrTituloMensagem) = MsgBoxResult.Yes Then
					Call cmdCancelar_Click(cmdCancelar, New System.EventArgs())
				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: frmEntregaReaviso_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	
	Private Sub frmEntregaReaviso_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Dim lintLinhas As Short
		Try
			'Call CenterForm(Me)
			Me.txtZona.Text = ""
			Me.txtLivro.Text = ""
			Me.txtConta.Text = ""
			Call CarregaRotas()
			Me.dtpEntrega.Value = VB6.Format(Date.Now, "dd/mm/yyyy hh:mm:ss")
			cmdRegistrar.Enabled = False
			If sExecutaAutomatico = True Then
				Dim f As New frmAguarde
				f.lbMensagem.Text = "Processando Entrega de Reavisos"
				f.Show(Me)
				Call ExecutaAutomatico()
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmEntregaReaviso_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 Buscar()

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

				If Me.lvsReaviso.Items.Count > 0 Then
					Call Registrar()
				End If
				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 Buscar()
		Try
			cmdRegistrar.Enabled = False
			Me.lblInfo.Text = " Aguarde...."
			Call Me.lblInfo.Refresh()
			Me.cmdBuscar.Enabled = False
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Call CarregarReaviso()
			Me.cmdBuscar.Enabled = True
			Me.Cursor = System.Windows.Forms.Cursors.Default
			sTerminouExecucao = True
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: Buscar" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub Registrar()
		Dim databd As Date
		Try
			databd = Date.Now

			Call LigDes(False)
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Call RegistrarConsumidor()
			Me.Cursor = System.Windows.Forms.Cursors.Default
			Call LigDes(True)
			sTerminouExecucao = True

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

	Private Sub AtualizaTabelaExecucaoAutomatica()
		Dim lstrSql As String
		Dim datainicio As New DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1)
		Dim dataUltimoDia As DateTime
		dataUltimoDia = datainicio.AddDays(-1)
		Try
			lstrSql = "SELECT * "
			lstrSql += "FROM execucao_automatica "
			lstrSql += "WHERE funcao = 'ENTREGAREAVISO' "
			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(dataUltimoDia, "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 += "'ENTREGAREAVISO', "
				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 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

	'Private Sub lvsReaviso_ItemCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ItemCheckEventArgs) Handles lvsReaviso.ItemCheck
	'	Dim aListItem As System.Windows.Forms.ListViewItem = lvsReaviso.Items(eventArgs.Index)
	'	Dim lintLinhas As Short
	'	Try
	'		With Me.lvsReaviso
	'			If aListItem.Text = "Marcar Todos" 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: lvsReaviso_ItemCheck" & "", "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) Handles opbIndividual.CheckedChanged
		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.lsvRotas.Enabled = Me.opbRota.Checked = True
				Me.chkTodasrotas.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.chkTodasrotas.Enabled = Me.opbRota.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 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

	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_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

	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_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 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 LigDes(ByVal ablnModo As Boolean)
		Try
			Me.lvsReaviso.Enabled = ablnModo
			Me.txtZona.Enabled = ablnModo
			Me.txtLivro.Enabled = ablnModo
			Me.txtConta.Enabled = ablnModo
			Me.cmdRegistrar.Enabled = ablnModo
			Me.cmdCancelar.Enabled = ablnModo
			System.Windows.Forms.Application.DoEvents()
		Catch ex As Exception
			If sExecutaAutomatico = False Then
				MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: LigDes" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			End If
			Exit Sub
		End Try
	End Sub
	Private Sub CarregaRotas()
		Dim lstrRota 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)))
				End If
				'Call .Items.Add("Todas as rotas")
				' Call .ListItems.Item(.ListItems.Count).ListSubItems.Add(, , "T")
			End With
			' ----- Busca as rotas
			lstrSql = ""
			lstrSql = lstrSql & "SELECT DISTINCT CAST(MID(`rota`,1,4) AS DECIMAL)  AS `rotagrupo`  "
			lstrSql = lstrSql & "  FROM `concorte` "
			lstrSql = lstrSql & " WHERE sit = ""R"" AND (concorte.grafica = 1 OR concorte.impressao =1 )"
			lstrSql = lstrSql & " GROUP BY rotagrupo"
			lstrSql = lstrSql & " ORDER BY  `rotagrupo` ASC"
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			' ----- Fim do Busca as rotas

			' ----- Se Retornou alguma coisa, monta as rotas!
			If dt.Rows.Count > 0 Then
				For Each row As DataRow In dt.Rows
					'lstrRota = VB6.Format(Mid(IIf(IsDBNull(row.Item("rotagrupo")), "0", row.Item("rotagrupo")), 1, 4), "0000")
					lstrRota = IIf(IsDBNull(row.Item("rotagrupo")), "0", row.Item("rotagrupo"))
					With Me.lsvRotas
						Call .Items.Add(lstrRota)
					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 Function PegaApresentacaoFatura(ByVal adblNumNf As Double, ByVal astrMesAno As String, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal adteReaviso As Date) As Date
		Dim lstrMes As String
		Dim ldteFat As Date
		Dim ldteRet As Date
		Dim lstrSql As String
		Try

			'ldteFat = Conversion.CDate("01/" & Left(astrMesano, 2) & "/" & Right(astrMesano, 4))
			'ldteFat = Conversion.CDate(UltimoDiaMes(Month(ldteFat), Year(ldteFat)) & "/" & Format(ldteFat, "mm/yyyy"))
			'ldteFat = ldteFat + 1
			lstrMes = VB6.Format(adteReaviso, "mm/yyyy")
			lstrSql = ""
			lstrSql = lstrSql & "SELECT "
			lstrSql = lstrSql & "       numnf,"
			lstrSql = lstrSql & "       mesano,"
			lstrSql = lstrSql & "       zona,"
			lstrSql = lstrSql & "       livro,"
			lstrSql = lstrSql & "       conta,"
			lstrSql = lstrSql & "       dataapr"
			lstrSql = lstrSql & "  FROM nf"
			lstrSql = lstrSql & " WHERE nf.mesano = '" & lstrMes & "' "
			lstrSql = lstrSql & "   AND nf.zona = '" & astrZona & "' "
			lstrSql = lstrSql & "   AND nf.livro = '" & astrLivro & "' "
			lstrSql = lstrSql & "   AND nf.conta = '" & astrConta & "' "
			lstrSql = lstrSql & " ORDER BY numnf DESC LIMIT 0, 1"
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			ldteRet = CDate("01/01/1900")

			If dt.Rows.Count > 0 Then
				For Each row As DataRow In dt.Rows
					ldteRet = CDate(IIf(IsDBNull(row.Item("dataapr")), "1900-01-01", row("dataapr")))
				Next
			End If

			PegaApresentacaoFatura = ldteRet

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

	Private Sub chktodosreg_CheckedChanged(sender As Object, e As EventArgs) Handles chktodosreg.CheckedChanged
		Dim intConta As Short

		Try

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

			ElseIf chktodosreg.Checked = False Then
				For intConta = 0 To lvsReaviso.Items.Count - 1
					lvsReaviso.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 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
End Class