Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Friend Class frmConvenio115SC
	Inherits System.Windows.Forms.Form
	Private istrNomeArq As String
	
	Private Sub dtpMesAno_Change(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles dtpMesAno.Change
		istrNomeArq = "SCUUU" & VB6.Format(Me.dtpMesAno.value, "yymm") & "N"
		Me.txtMestre.Text = VB.Left(Me.txtMestre.Text, InStrRev(Me.txtMestre.Text, "\")) & istrNomeArq & "M.001"
		Me.txtCadastro.Text = VB.Left(Me.txtCadastro.Text, InStrRev(Me.txtCadastro.Text, "\")) & istrNomeArq & "D.001"
		Me.txtItens.Text = VB.Left(Me.txtItens.Text, InStrRev(Me.txtItens.Text, "\")) & istrNomeArq & "I.001"
	End Sub
	
	Private Sub frmConvenio115SC_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
		Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
		If KeyAscii = System.Windows.Forms.Keys.Escape Then
			Call cmdFechar_Click(cmdFechar, New System.EventArgs())
		ElseIf KeyAscii = System.Windows.Forms.Keys.Return Then 
			Call SendKeysA(System.Windows.Forms.Keys.Tab, True)
		End If
		eventArgs.KeyChar = Chr(KeyAscii)
		If KeyAscii = 0 Then
			eventArgs.Handled = True
		End If
	End Sub
	
	Private Sub frmConvenio115SC_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Me.Height = VB6.TwipsToPixelsY(3270)
		Me.dtpMesAno.value = "01/" & LeConfig("MESANOFATURAMENTO")
		istrNomeArq = "SCUUU" & VB6.Format(Me.dtpMesAno.value, "yymm") & "N"
		Me.txtMestre.Text = My.Application.Info.DirectoryPath & "\" & istrNomeArq & "M.001"
		Me.txtCadastro.Text = My.Application.Info.DirectoryPath & "\" & istrNomeArq & "D.001"
		Me.txtItens.Text = My.Application.Info.DirectoryPath & "\" & istrNomeArq & "I.001"
	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 cmdMestre_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdMestre.Click
		'UPGRADE_WARNING: CommonDialog variable was not upgraded Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="671167DC-EA81-475D-B690-7A40C7BF4A23"'
		With Me.dialArq
			.DefaultExt = "001"
			'UPGRADE_WARNING: Filter has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			.Filter = istrNomeArq & "M." & .DefaultExt
			.FileName = istrNomeArq & "M." & .DefaultExt
			.Title = "Arquivo Mestre"
			Call .ShowDialog()
			Me.txtMestre.Text = .FileName
		End With
	End Sub
	
	Private Sub cmdCadastro_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCadastro.Click
		'UPGRADE_WARNING: CommonDialog variable was not upgraded Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="671167DC-EA81-475D-B690-7A40C7BF4A23"'
		With Me.dialArq
			.DefaultExt = "001"
			'UPGRADE_WARNING: Filter has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			.Filter = istrNomeArq & "D." & .DefaultExt
			.FileName = istrNomeArq & "D." & .DefaultExt
			.Title = "Arquivo de Cadastro"
			Call .ShowDialog()
			Me.txtCadastro.Text = .FileName
		End With
	End Sub
	
	Private Sub cmdItens_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdItens.Click
		'UPGRADE_WARNING: CommonDialog variable was not upgraded Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="671167DC-EA81-475D-B690-7A40C7BF4A23"'
		With Me.dialArq
			.DefaultExt = "001"
			'UPGRADE_WARNING: Filter has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			.Filter = istrNomeArq & "I." & .DefaultExt
			.FileName = istrNomeArq & "I." & .DefaultExt
			.Title = "Arquivo de Itens"
			Call .ShowDialog()
			Me.txtItens.Text = .FileName
		End With
	End Sub
	
	Private Sub cmdGerarMestre_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGerarMestre.Click
		Dim llngConsId As Integer
		Dim llngUnidId As Integer
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrCpf As String
		Dim lstrIE As String
		Dim lstrNome As String
		Dim lstrUf As String
		Dim lstrItensserv As String
		Dim lstrTa As String
		Dim lstrTensao As String
		Dim lstrFase As String
		Dim lstrClasse As String
		Dim lstrGrupo As String
		Dim lstrGrpTen As String
		Dim lstrDtEmissao As String
		Dim lstrDtCancela As String
		Dim lstrHash As String
		Dim lstrSituacao As String
		Dim ldblNumNF As Double
		Dim lstrMesAno As String
		Dim ldblVlrTot As Double
		Dim ldblMust As Double
		Dim ldblBaseIcms As Double
		Dim ldblIcms As Double
		Dim ldblOutros As Double
		Dim ldblIsentos As Double
		Dim ldblBaseIcmsDiferida As Double
		Dim ldblAliquota As Double
		Dim ldblBaseCofins As Double
		Dim ldblDevolucoes As Double
		Dim ldblRetencoes As Double
		Dim ldblConsumo As Double
		Dim llngRef As Integer
		Dim lstrCodValor As String
		Dim lstrItens() As String
		Dim llngCount As Integer
		Dim ldblValorItem As Double
		Dim lstrLinha As String
		Dim lintARQ As Short
		Dim lstrSql As String
		Dim lrstFat As ADODB.Recordset
		Dim lrstAux As ADODB.Recordset
		lrstFat = New ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrMesAno = VB6.Format(Me.dtpMesAno.value, "mm/yyyy")
		If Len(Trim(Me.txtMestre.Text)) > 0 Then
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.lblInfo.Text = " Buscando os dados... "
			Me.lblInfo.Refresh()
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `unid_id`, `cons_id`, `grupo`, "
			lstrSql = lstrSql & "       `numnf`, `mesano`, `mesano_ref`, `itensserv`, `valortot`, `valorliq`, "
			lstrSql = lstrSql & "       `codclas`, `fase`, `ta`, `tensao`, `flgst`, `datast`, `dataem`, `codhash`, `cpf_cnpj` "
			lstrSql = lstrSql & "  FROM `nf` "
			lstrSql = lstrSql & " WHERE `mesano` = '" & lstrMesAno & "' "
			If Me.txtClasse.Text <> "" Then
				lstrSql = lstrSql & " AND LEFT(codclas," & Len(Me.txtClasse.Text) & ") = '" & Me.txtClasse.Text & "' "
			End If
			If Me.txtGrupo.Text <> "" Then
				lstrSql = lstrSql & " AND grupo = '" & Me.txtGrupo.Text & "' "
			End If
			If (Trim(Me.txtFiltroNF.Text) <> "") Then
				lstrSql = lstrSql & " AND numnf = " & Me.txtFiltroNF.Text
			End If
			If (Trim(Me.txtNFinicial.Text)) <> "" And (Trim(Me.txtnfFinal.Text)) <> "" Then
				lstrSql = lstrSql & " AND numnf BETWEEN '" & txtNFinicial.Text & "' " & "AND '" & txtnfFinal.Text & "' "
			End If
			lstrSql = lstrSql & " ORDER BY numnf ASC "
			If (Trim(Me.txtFiltroLimite.Text) <> "") Then
				lstrSql = lstrSql & " LIMIT 0," & Me.txtFiltroLimite.Text
			End If
			Call Conectar(lstrSql, lrstFat)
			With lrstFat
				If .State = ADODB.ObjectStateEnum.adStateOpen Then
					If .RecordCount > 0 Then
						lintARQ = FreeFile
						FileOpen(lintARQ, Me.txtMestre.Text, OpenMode.Output)
						Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, .RecordCount)
						llngRef = 1
						While Not .EOF
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							llngConsId = IIf(IsDbNull(.Fields("cons_id").value), 0, .Fields("cons_id").value)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							llngUnidId = IIf(IsDbNull(.Fields("unid_id").value), 0, .Fields("unid_id").value)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrZona = VB.Right("000" & Trim(IIf(IsDbNull(.Fields("zona").value), "0", .Fields("zona").value)), 3)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrLivro = VB.Right("00" & Trim(IIf(IsDbNull(.Fields("livro").value), "0", .Fields("livro").value)), 2)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrConta = VB.Right("000000" & Trim(IIf(IsDbNull(.Fields("conta").value), "0", .Fields("conta").value)), 6)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCpf = Trim(IIf(IsDbNull(.Fields("cpf_cnpj").value), "", .Fields("cpf_cnpj").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrItensserv = Trim(IIf(IsDbNull(.Fields("itensserv").value), "", .Fields("itensserv").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrTa = Mid(Trim(IIf(IsDbNull(.Fields("ta").value), "01B100", .Fields("ta").value)), 3, 2)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrTensao = Trim(IIf(IsDbNull(.Fields("tensao").value), "380", .Fields("tensao").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrFase = Trim(IIf(IsDbNull(.Fields("fase").value), "M", .Fields("fase").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrClasse = Trim(IIf(IsDbNull(.Fields("codclas").value), "0000", .Fields("codclas").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrDtEmissao = VB6.Format(IIf(IsDbNull(.Fields("dataem").value), "00/00/0000", .Fields("dataem").value), "yyyymmdd")
							lstrDtCancela = "0000-00-00"
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrDtCancela = Replace(Replace(IIf(IsDbNull(.Fields("datast").value), "0000-00-00", .Fields("datast").value), "-", ""), "/", "")
							lstrDtCancela = VB.Right(lstrDtCancela, 2) & Mid(lstrDtCancela, 3, 2)
							'
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldblNumNF = IIf(IsDbNull(.Fields("numnf").value), 0, .Fields("numnf").value)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrMesAno = Trim(IIf(IsDbNull(.Fields("mesano").value), "", .Fields("mesano").value))
							lstrMesAno = VB.Right(lstrMesAno, 2) & VB.Left(lstrMesAno, 2)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrSituacao = Trim(IIf(IsDbNull(.Fields("flgst").value), "", .Fields("flgst").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldblVlrTot = IIf(IsDbNull(.Fields("valortot").value), 0, .Fields("valortot").value)
							'If Left(lstrClasse, 2) = 63 Then
							'  ldblVlrTot = IIf(IsNull(.Fields("valorliq").Value), 0, .Fields("valorliq").Value)
							'End If
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrHash = IIf(IsDbNull(.Fields("codhash").value), "", .Fields("codhash").value)
							ldblMust = BuscaValorItem(lstrItensserv, "0302020032")
							'
							ldblBaseIcms = BuscaValorItem(lstrItensserv, "0302030001") + BuscaValorItem(lstrItensserv, "0302030003")
							ldblIcms = BuscaValorItem(lstrItensserv, "0302030009") + BuscaValorItem(lstrItensserv, "0302030010")
							'
							ldblBaseIcmsDiferida = BuscaValorItem(lstrItensserv, "0302030020")
							ldblAliquota = BuscaValorItem(lstrItensserv, "0302030002")
							ldblBaseCofins = BuscaValorItem(lstrItensserv, "0302020034")
							'
							ldblDevolucoes = BuscaValorItem(lstrItensserv, "9070") 'Devoluções
							If ldblDevolucoes < 0 Then ldblDevolucoes = ldblDevolucoes * -1
							'
							'As retenções não devem entrar por que isso é somente demonstrativo de recolhimento
							'a obrigacao de declarar isso para o fisco é do próprio consumidor
							'ldblRetencoes = BuscaValorItem(lstrItensserv, "9090")
							'
							ldblOutros = BuscaValorItem(lstrItensserv, "9030") 'Convenios
							ldblOutros = ldblOutros + BuscaValorItem(lstrItensserv, "9040") 'Taxas
							ldblOutros = ldblOutros + BuscaValorItem(lstrItensserv, "9080") 'Diversos
							ldblOutros = ldblOutros + BuscaValorItem(lstrItensserv, "9050") 'Diversos
							ldblOutros = ldblOutros + BuscaValorItem(lstrItensserv, "0301000003") 'Iluminação
							ldblOutros = ldblOutros + BuscaValorItem(lstrItensserv, "0302990041") 'Arredondamento
							ldblOutros = ldblOutros - ldblRetencoes
							'
							'RURAL e SERV. PÚBLICO
							'If Left(lstrClasse, 1) <> "5" And Left(lstrClasse, 1) <> "7" Then
							ldblOutros = ldblOutros - ldblDevolucoes
							'End If
							'
							'If ldblOutros < 0 Then
							'  ldblVlrTot = ldblVlrTot + ldblOutros
							' ' ldblOutros = 0
							'End If
							ldblOutros = ldblOutros + ldblBaseIcmsDiferida
							'
							' isentos
							If ldblAliquota = 0 Then
								ldblIsentos = ldblBaseCofins
								If ldblIsentos = 0 Then
									If VB.Left(lstrTa, 1) = "A" Then
										ldblIsentos = ldblVlrTot - ldblOutros
									End If
								End If
								ldblBaseIcms = 0
							Else
								ldblIsentos = 0
							End If
							'
							'Situação
							If lstrSituacao = "C" And lstrDtCancela = lstrMesAno Then
								lstrSituacao = "S"
							Else
								lstrSituacao = "N"
							End If
							'
							'grupo
							lstrGrupo = PegaCodGrupoTensao(lstrTa, lstrClasse, lstrTensao)
							'
							'classe
							lstrClasse = PegaCodClasse(lstrClasse)
							'
							lstrSql = ""
							lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `cons_id`, `unid_id`,`uf` "
							lstrSql = lstrSql & "  FROM `unid" & LCase(VB.Left(lstrTa, 1)) & "` "
							lstrSql = lstrSql & " WHERE `unid_id` = " & llngUnidId
							lstrSql = lstrSql & "   AND `zona`    = '" & lstrZona & "' "
							lstrSql = lstrSql & "   AND `livro`   = '" & lstrLivro & "' "
							lstrSql = lstrSql & "   AND `conta`   = '" & lstrConta & "' "
							Call Conectar(lstrSql, lrstAux)
							With lrstAux
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrUf = Trim(IIf(IsDbNull(.Fields("uf").value), "", .Fields("uf").value))
									End If
									Call .Close()
								End If
							End With
							'
							'Pega os dados do consumidor (Pessoa Física/Jurídica)
							lstrSql = ""
							lstrSql = lstrSql & "SELECT `consreg`, `nome`, `cgc`, `insc` "
							lstrSql = lstrSql & "  FROM `consum` "
							lstrSql = lstrSql & " WHERE `consreg` = " & llngConsId
							Call Conectar(lstrSql, lrstAux)
							With lrstAux
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrIE = Trim(IIf(IsDbNull(.Fields("insc").value), "", .Fields("insc").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrNome = Trim(IIf(IsDbNull(.Fields("nome").value), "", .Fields("nome").value))
									End If
									Call .Close()
								End If
							End With
							'
							lstrLinha = ""
							lstrLinha = lstrLinha & TrataCampo(lstrCpf, 14, "0", 2) '1 - CNPJ ou CPF
							lstrLinha = lstrLinha & TrataCampo(lstrIE, 14, "0", 2) '2 - IE
							lstrLinha = lstrLinha & TrataCampo(lstrNome, 35, " ", 1) '3 - Razão Social
							lstrLinha = lstrLinha & TrataCampo(lstrUf, 2, " ", 1) '4 - UF
							lstrLinha = lstrLinha & TrataCampo(lstrClasse, 1, "0", 2) '5 - Classe de Consumo
							lstrLinha = lstrLinha & TrataCampo(IIf(lstrFase = "M", "1", IIf(lstrFase = "B", "2", "3")), 1, "0", 2) '6 - Fase
							lstrLinha = lstrLinha & TrataCampo(lstrGrupo, 2, "0", 2) '7 - Grupo de Tensão
							lstrLinha = lstrLinha & TrataCampo(lstrZona & lstrLivro & lstrConta, 12, "0", 2) '8 - Código de Identificação do consumidor
							lstrLinha = lstrLinha & TrataCampo(lstrDtEmissao, 8, "0", 1) '9 - Data de emissão
							lstrLinha = lstrLinha & TrataCampo("06", 2, "0", 2) '10 - Modelo
							lstrLinha = lstrLinha & TrataCampo("UUU", 3, " ", 1) '11 - Série
							lstrLinha = lstrLinha & TrataCampo(CStr(CShort(ldblNumNF)), 9, "0", 2) '12 - Número
							lstrLinha = lstrLinha & TrataCampo(lstrHash, 32, "0", 1) '13 - Código de Autenticação Digital documento fiscal
							lstrLinha = lstrLinha & PreparaCampo(Replace(VB6.Format(CStr(ldblVlrTot), "#,##0.00"), ".", ""), NUMERICO, 12, "0") '14 - Valor Total
							lstrLinha = lstrLinha & PreparaCampo(Replace(VB6.Format(CStr(ldblBaseIcms), "#,##0.00"), ".", ""), NUMERICO, 12, "0") '15 - BC ICMS
							lstrLinha = lstrLinha & PreparaCampo(Replace(VB6.Format(CStr(ldblIcms), "#,##0.00"), ".", ""), NUMERICO, 12, "0") '16 - ICMS destacado
							lstrLinha = lstrLinha & PreparaCampo(Replace(VB6.Format(CStr(ldblIsentos + ldblMust), "#,##0.00"), ".", ""), NUMERICO, 12, "0") '17 - Operações Isentas ou não tributadas
							If ldblOutros < 0 Then
								lstrLinha = lstrLinha & "-" & PreparaCampo(Replace(VB6.Format(CStr(ldblOutros * -1), "#,##0.00"), ".", ""), NUMERICO, 11, "0") '18 - Outros valores
							Else
								lstrLinha = lstrLinha & PreparaCampo(Replace(VB6.Format(CStr(ldblOutros), "#,##0.00"), ".", ""), NUMERICO, 12, "0") '18 - Outros valores
							End If
							lstrLinha = lstrLinha & TrataCampo(lstrSituacao, 1, "0", 1) '19 - Código de Autenticação Digital documento fiscal
							lstrLinha = lstrLinha & TrataCampo(lstrMesAno, 4, "0", 1) '20 - Ano e Mês de referência de apuração
							lstrLinha = lstrLinha & TrataCampo(CStr(llngRef), 9, "0", 2) '21 - Referência ao item da NF
							lstrLinha = lstrLinha & TrataCampo("", 10, " ", 1) '22 - Número do terminal telefônico ou Número da conta de consumo
							lstrLinha = lstrLinha & TrataCampo("", 3, " ", 1) '23 - Brancos - reservado para uso futuro
							'UPGRADE_WARNING: Couldn't resolve default property of object GeraHash(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							lstrLinha = lstrLinha & TrataCampo(GeraHash(lstrLinha), 32, " ", 1) '24 - Código de Autenticação Digital do registro
							PrintLine(lintARQ, lstrLinha)
							'
							' Usado somente para analise quando acontecer algum problema
							' Cria uma linha com o resumo para facilitar a leitura dos valores
							If (Trim(Me.txtFiltroNF.Text) <> "") Then
								lstrLinha = ""
								lstrLinha = lstrLinha & "[TOTAL:] " & VB6.Format(ldblVlrTot, "0.00")
								lstrLinha = lstrLinha & " [BC ICMS:] " & VB6.Format(ldblBaseIcms, "0.00")
								lstrLinha = lstrLinha & " [VLR ICMS:] " & VB6.Format(ldblIcms, "0.00")
								lstrLinha = lstrLinha & " [ISENTO:] " & VB6.Format(ldblIsentos, "0.00")
								lstrLinha = lstrLinha & " [OUTROS:] " & VB6.Format(ldblOutros, "0.00")
								PrintLine(lintARQ, lstrLinha)
							End If
							' Calcula a quantidade de itens na fatura para somar na sequencia (Item 21)
							lstrSql = ""
							lstrSql = lstrSql & "SELECT codigovlr, codigoqtde, descri, bxrenda from conv115 "
							If lstrGrupo = "08" Then
								lstrSql = lstrSql & " WHERE bxrenda = 'S' "
							End If
							lstrSql = lstrSql & " UNION "
							lstrSql = lstrSql & "SELECT num AS codigovlr, '' AS codigoqtde, descri AS descri, 'S' AS bxrenda FROM codigos WHERE LEFT(num, 1) = 9 AND LEFT(num, 4) NOT IN('9041', '9090') "
							Call Conectar(lstrSql, lrstAux)
							With lrstAux
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										While Not .EOF
											'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
											lstrCodValor = Trim(IIf(IsDbNull(.Fields("codigovlr").value), "", .Fields("codigovlr").value))
											If (Len(lstrCodValor) > 0) Then
												'Busca o valor do item da tabela CONV115 na tabela NF
												lstrItens = buscaValoresItem(lstrItensserv, lstrCodValor)
												For llngCount = 0 To UBound(lstrItens)
													ldblValorItem = CDbl(lstrItens(llngCount))
													'Busca os valores quando for consumo faturado, grupo 05 = grupo A
													If lstrCodValor = "0302020009" Then
														If lstrGrupo = "05" Then
															ldblValorItem = BuscaValorItem(lstrItensserv, "0302020008")
														Else
															ldblValorItem = BuscaValorItem(lstrItensserv, "030202009")
														End If
													End If
													If lstrCodValor = "0302020008" Then
														ldblValorItem = ldblValorItem
													End If
													If VB.Left(lstrTa, 1) <> "A" Then
														If lstrCodValor = "0502020001" Then
															ldblConsumo = BuscaValorItem(lstrItensserv, "030201009")
															If (ldblConsumo > 150 And VB.Left(lstrClasse, 1) = "6") Or (ldblConsumo > 500 And VB.Left(lstrClasse, 1) = "7") Then
																ldblValorItem = 1
															Else
																ldblValorItem = 1
															End If
														End If
														If lstrCodValor = "0502020002" Then
															ldblConsumo = BuscaValorItem(lstrItensserv, "030201009")
															If (ldblConsumo > 150 And VB.Left(lstrClasse, 1) = "6") Or (ldblConsumo > 500 And VB.Left(lstrClasse, 1) = "7") Then
																ldblValorItem = 1
															End If
														End If
													End If
													'Conta a referência para o próximo item
													If ldblValorItem > 0 Then
														llngRef = llngRef + 1
													End If
												Next llngCount
											End If
											Call .MoveNext()
											System.Windows.Forms.Application.DoEvents()
										End While
										If ldblMust > 0 Then
											llngRef = llngRef - 1
										End If
										
									End If
									Call .Close()
								End If
							End With
							Call .MoveNext()
							Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
						End While
						FileClose(lintARQ)
					End If
					Call .Close()
					Me.lblInfo.Text = Me.lblInfo.Text & " - Arquivo mestre gerado com sucesso!"
					Call Me.lblInfo.Refresh()
				End If
			End With
			Me.Cursor = System.Windows.Forms.Cursors.Arrow
		Else
			Call MsgBox("Preenchimento do arquivo Mestre é obrigatório.", MsgBoxStyle.Information, gstrTituloMensagem)
		End If
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		'UPGRADE_NOTE: Object lrstFat may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstFat = Nothing
	End Sub
	
	Private Sub cmdGerarCadastro_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGerarCadastro.Click
		Dim lstrLinha As String
		Dim lintARQ As Short
		Dim lstrMesAno As String
		Dim llngConsId As Integer
		Dim llngUnidId As Integer
		Dim lstrIdenti As String
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrGrupo As String
		Dim lstrCpf As String
		Dim lstrIE As String
		Dim lstrTelefo As String
		Dim lstrNome As String
		Dim lstrUf As String
		Dim lstrCep As String
		Dim lstrCidade As String
		Dim lstrBairro As String
		Dim lstrEndere As String
		Dim lstrNumero As String
		Dim lstrComple As String
		Dim lstrQuadra As String
		Dim lstrLote As String
		Dim lstrSql As String
		Dim lrstFat As ADODB.Recordset
		Dim lrstAux As ADODB.Recordset
		lrstFat = New ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrMesAno = VB6.Format(Me.dtpMesAno.value, "mm/yyyy")
		If Len(Trim(Me.txtCadastro.Text)) > 0 Then
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.lblInfo.Text = " Buscando os dados... "
			Call Me.lblInfo.Refresh()
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `numnf`, `mesano`, `mesano_ref`, `grupo`, `zona`, `livro`, `conta`, `cons_id`, `unid_id`, `cpf_cnpj` "
			lstrSql = lstrSql & "  FROM `nf` "
			lstrSql = lstrSql & " WHERE `mesano` = '" & lstrMesAno & "'"
			If Me.txtClasse.Text <> "" Then
				lstrSql = lstrSql & " AND LEFT(codclas," & Len(Me.txtClasse.Text) & ") = '" & Me.txtClasse.Text & "' "
			End If
			If Me.txtGrupo.Text <> "" Then
				lstrSql = lstrSql & " AND grupo = '" & Me.txtGrupo.Text & "' "
			End If
			If (Trim(Me.txtFiltroNF.Text) <> "") Then
				lstrSql = lstrSql & " AND numnf = " & Me.txtFiltroNF.Text
			End If
			If (Trim(Me.txtNFinicial.Text)) <> "" And (Trim(Me.txtnfFinal.Text)) <> "" Then
				lstrSql = lstrSql & " AND numnf BETWEEN '" & txtNFinicial.Text & "' " & "AND '" & txtnfFinal.Text & "' "
			End If
			lstrSql = lstrSql & " ORDER BY numnf ASC "
			If (Trim(Me.txtFiltroLimite.Text) <> "") Then
				lstrSql = lstrSql & " LIMIT 0," & Me.txtFiltroLimite.Text
			End If
			Call Conectar(lstrSql, lrstFat)
			With lrstFat
				If .State = ADODB.ObjectStateEnum.adStateOpen Then
					If .RecordCount > 0 Then
						lintARQ = FreeFile
						FileOpen(lintARQ, Me.txtCadastro.Text, OpenMode.Output)
						Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, .RecordCount)
						While Not .EOF
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							llngConsId = IIf(IsDbNull(.Fields("cons_id").value), 0, .Fields("cons_id").value)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							llngUnidId = IIf(IsDbNull(.Fields("unid_id").value), 0, .Fields("unid_id").value)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrZona = VB.Right("000" & Trim(IIf(IsDbNull(.Fields("zona").value), "0", .Fields("zona").value)), 3)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrLivro = VB.Right("00" & Trim(IIf(IsDbNull(.Fields("livro").value), "0", .Fields("livro").value)), 2)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrConta = VB.Right("000000" & Trim(IIf(IsDbNull(.Fields("conta").value), "0", .Fields("conta").value)), 6)
							lstrIdenti = (lstrZona & lstrLivro & lstrConta)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrGrupo = Trim(IIf(IsDbNull(.Fields("grupo").value), "B", .Fields("grupo").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCpf = Trim(IIf(IsDbNull(.Fields("cpf_cnpj").value), "", .Fields("cpf_cnpj").value))
							lstrSql = ""
							lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `cons_id`, `unid_id`, "
							lstrSql = lstrSql & "       `uf`, `cep`, `cidade`, `bairro`, `end`, `numero`, `complement`, `quadra`, `lote` "
							lstrSql = lstrSql & "  FROM `unid" & LCase(lstrGrupo) & "` "
							lstrSql = lstrSql & " WHERE `unid_id` = " & llngUnidId
							lstrSql = lstrSql & "   AND `zona`    = '" & lstrZona & "' "
							lstrSql = lstrSql & "   AND `livro`   = '" & lstrLivro & "' "
							lstrSql = lstrSql & "   AND `conta`   = '" & lstrConta & "' "
							Call Conectar(lstrSql, lrstAux)
							With lrstAux
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrUf = Trim(IIf(IsDbNull(.Fields("uf").value), "", .Fields("uf").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCep = Replace(Trim(IIf(IsDbNull(.Fields("cep").value), "0000000", .Fields("cep").value)), "-", "")
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCidade = Trim(IIf(IsDbNull(.Fields("cidade").value), "", .Fields("cidade").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrBairro = Trim(IIf(IsDbNull(.Fields("bairro").value), "", .Fields("bairro").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrEndere = Trim(IIf(IsDbNull(.Fields("end").value), "", .Fields("end").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrNumero = Trim(IIf(IsDbNull(.Fields("numero").value), "00000", .Fields("numero").value))
										If lstrNumero = "SN" Or lstrNumero = "S/N" Or lstrNumero = "" Then
											lstrNumero = "00001"
										End If
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrQuadra = Trim(IIf(IsDbNull(.Fields("quadra").value), "", .Fields("quadra").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrLote = Trim(IIf(IsDbNull(.Fields("lote").value), "", .Fields("lote").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrComple = Trim(IIf(IsDbNull(.Fields("complement").value), "", .Fields("complement").value))
										If Len(lstrQuadra) > 0 Then
											lstrComple = lstrComple & IIf(Len(lstrComple) > 0, " - QD: ", "") & lstrQuadra
										End If
										If Len(lstrLote) > 0 Then
											lstrComple = lstrComple & IIf(Len(lstrComple) > 0, " - LT: ", "") & lstrLote
										End If
									End If
									Call .Close()
								End If
							End With
							lstrSql = ""
							lstrSql = lstrSql & "SELECT `consreg`, `nome`, `cgc`, `insc`, `telefone` "
							lstrSql = lstrSql & "  FROM `consum` "
							lstrSql = lstrSql & " WHERE `consreg` = " & llngConsId
							Call Conectar(lstrSql, lrstAux)
							With lrstAux
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrIE = Trim(IIf(IsDbNull(.Fields("insc").value), "", .Fields("insc").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrTelefo = Replace(Replace(Trim(IIf(IsDbNull(.Fields("telefone").value), "", .Fields("telefone").value)), "-", ""), " ", "")
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrNome = Trim(IIf(IsDbNull(.Fields("nome").value), "", .Fields("nome").value))
									End If
									Call .Close()
								End If
							End With
							lstrLinha = ""
							lstrLinha = lstrLinha & TrataCampo(lstrCpf, 14, "0", 2) '1 - CNPJ ou CPF
							lstrLinha = lstrLinha & TrataCampo(lstrIE, 14, "0", 2) '2 - IE
							lstrLinha = lstrLinha & TrataCampo(lstrNome, 35, " ", 1) '3 - Razão Social
							lstrLinha = lstrLinha & TrataCampo(lstrEndere, 45, " ", 1) '4 - Logradouro
							lstrLinha = lstrLinha & TrataCampo(lstrNumero, 5, "0", 2) '5 - Número
							lstrLinha = lstrLinha & TrataCampo(lstrComple, 15, " ", 1) '6 - Complemento
							lstrLinha = lstrLinha & TrataCampo(lstrCep, 8, "0", 2) '7 - CEP
							lstrLinha = lstrLinha & TrataCampo(lstrBairro, 15, " ", 1) '8 - Bairro
							lstrLinha = lstrLinha & TrataCampo(lstrCidade, 30, " ", 1) '9 - Município
							lstrLinha = lstrLinha & TrataCampo(lstrUf, 2, " ", 1) '10 - UF
							lstrLinha = lstrLinha & TrataCampo(lstrTelefo, 10, "0", 2) '11 - Telefone de contato
							lstrLinha = lstrLinha & TrataCampo(lstrIdenti, 12, "0", 2) '12 - Código de Identificação do consumidor
							lstrLinha = lstrLinha & TrataCampo("", 10, " ", 1) '13 - Número da conta de consumo
							lstrLinha = lstrLinha & TrataCampo("", 2, " ", 1) '14 - UF de habilitação do terminal telefônico
							lstrLinha = lstrLinha & TrataCampo("", 5, " ", 1) '15 - Brancos - reservado para uso futuro
							'UPGRADE_WARNING: Couldn't resolve default property of object GeraHash(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							lstrLinha = lstrLinha & TrataCampo(GeraHash(lstrLinha), 32, " ", 1) '16 - Código de Autenticação Digital do registro
							PrintLine(lintARQ, lstrLinha)
							Call .MoveNext()
							Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
						End While
						FileClose(lintARQ)
					End If
					Call .Close()
				End If
			End With
			Me.lblInfo.Text = Me.lblInfo.Text & " - Arquivo de cadastro gerado com sucesso!"
			Call Me.lblInfo.Refresh()
			Me.Cursor = System.Windows.Forms.Cursors.Arrow
		Else
			Call MsgBox("Preenchimento do arquivo de Cadastro é obrigatório.", MsgBoxStyle.Information, gstrTituloMensagem)
		End If
		'UPGRADE_NOTE: Object lrstFat may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstFat = Nothing
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
	End Sub
	
	Private Sub cmdGerarItens_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGerarItens.Click
		'Unidade Consumidora
		Dim llngConsId As Integer
		Dim llngUnidId As Integer
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrCpf As String
		Dim lstrUf As String
		'
		'Fatura
		Dim lstrTa As String
		Dim lstrGrupo As String
		Dim lstrGrpTen As String
		Dim lstrGrpTar As String
		Dim lstrFase As String
		Dim lstrTensao As String
		Dim lstrClasse As String
		Dim lstrCfop As String
		Dim lstrItensserv As String
		Dim ldblNumNF As Double
		Dim lstrMesAno As String
		Dim ldblValorTot As Double
		Dim lstrSituacaoFatura As String
		Dim ldteEmissao As Date
		Dim ldteCancelamento As Date
		'
		'Tributacao
		Dim ldblAliqIcms1 As Double
		Dim ldblAliqIcms2 As Double
		Dim ldblBaseIcms As Double
		Dim ldblBaseIcms1 As Double
		Dim ldblBaseIcms2 As Double
		Dim ldblVlrIcms As Double
		Dim ldblVlrIcms1 As Double
		Dim ldblVlrIcms2 As Double
		Dim ldblBasePis As Double
		Dim ldblAliqPis As Double
		Dim ldblAliqCof As Double
		
		'
		'Consumo
		Dim ldblQtdCons1 As Double
		Dim ldblQtdCons2 As Double
		Dim ldblQtdConsumo As Double
		Dim ldblVlrConsumo As Double
		Dim ldblMust As Double
		Dim lintLimRes As Short
		Dim lintLimRur As Short
		Dim lintLimite As Short
		'
		'Outros
		Dim ldblConvenios As Double
		Dim ldblTaxas As Double
		Dim ldblDevolucoes As Double
		Dim ldblDiversos As Double
		Dim ldblCip As Double
		Dim ldblArredondamento As Double
		Dim ldblTotalOutros As Double
		Dim ldblOutros As Double
		'
		' Controle dos itens
		Dim lstrCodAut As String
		Dim llngRefItem As Integer
		Dim lstrValorItens() As String
		Dim lintAux As Short
		Dim lstrCodValor As String
		Dim lstrCodQtde As String
		Dim lstrCodDescri As String
		Dim lstrClasItem As String
		Dim lstrUnidItem As String
		'Valores dos itens
		Dim ldblQtdeItem As Double
		Dim ldblQtdeFat As Double
		Dim ldblValorItem As Double
		'Tributos dos itens para Recalculo
		Dim ldblBCitens As Double
		Dim ldblIcmsItens As Double
		Dim ldblIsento As Double
		Dim ldblDesconto As Double
		'Controle do Baixa Renda
		Dim lblnBaixaRenda As Boolean
		Dim ldblValorBxRenda As Double
		Dim ldblBaseTotalIcms As Double
		Dim ldblVlrPis As Double
		Dim ldblVlrCofins As Double
		'
		' Controe do arquivo
		Dim lintARQ As Short
		Dim lstrLin As String
		'
		' Nova implementacao
		' controle de items
		Dim llngPosIte As Integer
		Dim lstrCodIte As String
		Dim lstrCodVlr As String
		Dim lstrCodRef As String
		Dim lstrFlgIte As String
		' controle tarifas grupo B
		Dim ldteLAtu As Date
		Dim ldteLAnt As Date
		Dim ldblTarB(4) As Double
		
		
		
		'
		'Controle das query
		Dim lstrSql As String
		Dim lrstFat As ADODB.Recordset
		Dim lrstAux As ADODB.Recordset
		Dim lrstHash As ADODB.Recordset
		lrstFat = New ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lrstHash = New ADODB.Recordset
		'
		lstrMesAno = VB6.Format(Me.dtpMesAno.value, "mm/yyyy")
		'
		lintLimRes = CShort(LeConfig("LIMITE_RESIDENCIAL"))
		lintLimRur = CShort(LeConfig("LIMITE_RURAL"))
		
		With mfgDados
			.Clear()
			.Rows = 0
			.set_ColWidth(0, 1000)
			.set_ColWidth(1, 3000)
			.set_ColWidth(2, 700)
			.set_ColWidth(3, 1000)
			.set_ColWidth(4, 1800)
			.set_ColWidth(5, 1000)
			.set_ColWidth(6, 1000)
			.set_ColWidth(7, 1000)
			.set_ColWidth(8, 1000)
		End With
		
		If Len(Trim(txtItens.Text)) > 0 Then
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Me.lblInfo.Text = " Buscando os dados... "
			Call Me.lblInfo.Refresh()
			'Aqui vai buscar todas as nf do mes e ano selecionado
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `unid_id`, `cons_id`, `grupo`, "
			lstrSql = lstrSql & "       `numnf`, `mesano`, `mesano_ref`, `itensserv`, `valortot`, `valorliq`, "
			lstrSql = lstrSql & "       `codclas`, `fase`, `ta`, `tensao`, `flgst`, `datast`, `dataem`, `codhash`, `cpf_cnpj`, `cfop`, `dataleit`, `dataleitant` "
			lstrSql = lstrSql & "  FROM `nf` "
			lstrSql = lstrSql & " WHERE `mesano` = '" & lstrMesAno & "' "
			'lstrSql = lstrSql & " AND zona = '001' and livro = '07' and conta = '000425' "
			If Me.txtClasse.Text <> "" Then
				lstrSql = lstrSql & " AND LEFT(`codclas`," & Len(Me.txtClasse.Text) & ") = '" & Me.txtClasse.Text & "' "
			End If
			If Me.txtGrupo.Text <> "" Then
				lstrSql = lstrSql & " AND `grupo` = '" & Me.txtGrupo.Text & "' "
			End If
			If (Trim(Me.txtFiltroNF.Text) <> "") Then
				lstrSql = lstrSql & " AND `numnf` = " & Me.txtFiltroNF.Text
			End If
			If (Trim(Me.txtNFinicial.Text)) <> "" And (Trim(Me.txtnfFinal.Text)) <> "" Then
				lstrSql = lstrSql & " AND `numnf` BETWEEN '" & txtNFinicial.Text & "' " & "AND '" & txtnfFinal.Text & "' "
			End If
			lstrSql = lstrSql & " ORDER BY numnf ASC "
			If (Trim(Me.txtFiltroLimite.Text) <> "") Then
				lstrSql = lstrSql & " LIMIT 0," & Me.txtFiltroLimite.Text
			End If
			Call Conectar(lstrSql, lrstFat)
			With lrstFat
				If .State = ADODB.ObjectStateEnum.adStateOpen Then
					If .RecordCount > 0 Then
						lintARQ = FreeFile
						FileOpen(lintARQ, Me.txtItens.Text, OpenMode.Output)
						Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, .RecordCount)
						While Not .EOF
							llngRefItem = 0
							ldblBaseIcms = 0
							ldblBaseIcms1 = 0
							ldblBaseIcms2 = 0
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCpf = Trim(IIf(IsDbNull(.Fields("cpf_cnpj").value), "", .Fields("cpf_cnpj").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							llngConsId = CInt(IIf(IsDbNull(.Fields("cons_id").value), 0, .Fields("cons_id").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							llngUnidId = CInt(IIf(IsDbNull(.Fields("unid_id").value), 0, .Fields("unid_id").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrZona = VB6.Format(IIf(IsDbNull(.Fields("zona").value), "0", .Fields("zona").value), "000")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrLivro = VB6.Format(IIf(IsDbNull(.Fields("livro").value), "0", .Fields("livro").value), "00")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrConta = VB6.Format(IIf(IsDbNull(.Fields("conta").value), "0", .Fields("conta").value), "000000")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrClasse = Trim(IIf(IsDbNull(.Fields("codclas").value), "0000", .Fields("codclas").value))
							lintLimite = IIf(CDbl(VB.Left(lstrClasse, 1)) = 9, lintLimRes, IIf(CDbl(VB.Left(lstrClasse, 1)) = 5, lintLimRur, 0))
							lblnBaixaRenda = (lstrClasse = "9104" Or lstrClasse = "9105" Or lstrClasse = "9106")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrItensserv = Trim(IIf(IsDbNull(.Fields("itensserv").value), "", .Fields("itensserv").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrTa = Mid(IIf(IsDbNull(.Fields("ta").value), "01B100", .Fields("ta").value), 3, 2)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrGrupo = Trim(IIf(IsDbNull(.Fields("grupo").value), "B", .Fields("grupo").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrFase = Trim(IIf(IsDbNull(.Fields("fase").value), "M", .Fields("fase").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrTensao = Trim(IIf(IsDbNull(.Fields("tensao").value), "380", .Fields("tensao").value))
							lstrCfop = PegaCFOP(lstrTa, lstrClasse)
							lstrGrpTen = PegaCodGrupoTensao(lstrTa, lstrClasse, lstrTensao)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldblValorTot = CDbl(IIf(IsDbNull(.Fields("valortot").value), 0, .Fields("valortot").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldblNumNF = CDbl(IIf(IsDbNull(.Fields("numnf").value), 0, .Fields("numnf").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrSituacaoFatura = Trim(IIf(IsDbNull(.Fields("flgst").value), "", .Fields("flgst").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteLAtu = CDate(IIf(IsDbNull(.Fields("dataleit").value), "1900-01-01", .Fields("dataleit").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteLAnt = CDate(IIf(IsDbNull(.Fields("dataleitant").value), "1900-01-01", .Fields("dataleitant").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteEmissao = CDate(IIf(IsDbNull(.Fields("dataem").value), "1900-01-01", .Fields("dataem").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteCancelamento = CDate(IIf(IsDbNull(.Fields("datast").value), "1900-01-01", .Fields("datast").value))
							If lstrSituacaoFatura = "C" And VB6.Format(ldteCancelamento, "mm/yyyy") = lstrMesAno Then
								lstrSituacaoFatura = "S"
							Else
								lstrSituacaoFatura = "N"
							End If
							'Itens da fatura
							' Consumo
							ldblQtdConsumo = BuscaValorItem(lstrItensserv, "030201009")
							ldblVlrConsumo = BuscaValorItem(lstrItensserv, "030202009")
							'
							ldblMust = BuscaValorItem(lstrItensserv, "0302020032")
							
							' Tributacao
							ldblBaseIcms1 = BuscaValorItem(lstrItensserv, "0302030001")
							ldblBaseIcms2 = BuscaValorItem(lstrItensserv, "0302030003")
							ldblBaseIcms = ldblBaseIcms1 + ldblBaseIcms2
							ldblVlrIcms1 = BuscaValorItem(lstrItensserv, "0302030009")
							ldblVlrIcms2 = BuscaValorItem(lstrItensserv, "0302030010")
							ldblVlrIcms = ldblVlrIcms1 + ldblVlrIcms2
							ldblBasePis = BuscaValorItem(lstrItensserv, "0302020033") 'usado para diferenciar qdo for isento de icms
							ldblVlrPis = BuscaValorItem(lstrItensserv, "0302020029")
							ldblVlrCofins = BuscaValorItem(lstrItensserv, "0302020030")
							ldblAliqIcms1 = BuscaValorItem(lstrItensserv, "0302030002")
							ldblAliqIcms2 = BuscaValorItem(lstrItensserv, "0302030013")
							ldblAliqPis = BuscaValorItem(lstrItensserv, "0302990303")
							ldblAliqCof = BuscaValorItem(lstrItensserv, "0302990304")
							'Tarifas
							If lstrGrupo = "B" Then
								lstrGrpTar = BuscaGrupoTar(lstrClasse)
								If Len(lstrGrpTar) < 10 Then
									ldblTarB(0) = TarifaProporcional(ldteLAnt, ldteLAtu, lstrGrpTar & "1", 3) / 1000
									ldblTarB(1) = TarifaProporcional(ldteLAnt, ldteLAtu, lstrGrpTar & "2", 3) / 1000
									ldblTarB(2) = TarifaProporcional(ldteLAnt, ldteLAtu, lstrGrpTar & "3", 3) / 1000
									ldblTarB(3) = TarifaProporcional(ldteLAnt, ldteLAtu, lstrGrpTar & "4", 3) / 1000
									ldblTarB(4) = TarifaProporcional(ldteLAnt, ldteLAtu, lstrGrpTar & "5", 3) / 1000
								Else
									ldblTarB(0) = TarifaProporcional(ldteLAnt, ldteLAtu, lstrGrpTar, 3) / 1000
									ldblTarB(1) = ldblTarB(0)
									ldblTarB(2) = 0
									ldblTarB(3) = 0
									ldblTarB(4) = 0
								End If
							Else
								
							End If
							
							'##########################################################
							ldblConvenios = BuscaValorItem(lstrItensserv, "903000")
							ldblTaxas = BuscaValorItem(lstrItensserv, "904000") + BuscaValorItem(lstrItensserv, "905000")
							ldblDevolucoes = BuscaValorItem(lstrItensserv, "907000")
							If ldblDevolucoes < 0 Then ldblDevolucoes = ldblDevolucoes * -1
							ldblDiversos = BuscaValorItem(lstrItensserv, "908000")
							ldblCip = BuscaValorItem(lstrItensserv, "0301000003")
							ldblArredondamento = BuscaValorItem(lstrItensserv, "0302990041")
							ldblTotalOutros = (ldblConvenios + ldblTaxas + ldblDiversos + ldblCip + ldblArredondamento) - ldblDevolucoes
							
							'##########################################################
							'Pega UF da unidade consumidora
							lstrSql = ""
							lstrSql = lstrSql & "SELECT `zona`, `livro`, `conta`, `cons_id`, `unid_id`,`uf` "
							lstrSql = lstrSql & "  FROM `unid" & LCase(VB.Left(lstrTa, 1)) & "` "
							lstrSql = lstrSql & " WHERE `unid_id` = " & llngUnidId
							lstrSql = lstrSql & "   AND `zona`    = '" & lstrZona & "' "
							lstrSql = lstrSql & "   AND `livro`   = '" & lstrLivro & "' "
							lstrSql = lstrSql & "   AND `conta`   = '" & lstrConta & "' "
							Call Conectar(lstrSql, lrstAux)
							With lrstAux
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrUf = Trim(IIf(IsDbNull(.Fields("uf").value), "", .Fields("uf").value))
									End If
									Call .Close()
								End If
							End With
							For llngPosIte = 1 To Len(Trim(lstrItensserv))
								'lstrCodIte = Código do item na fatura
								'lstrCodVlr = Valor do código do item
								'lstrCodRef = Referencia do item.
								Call BuscaItemNf(llngPosIte, lstrItensserv, lstrCodIte, lstrCodVlr, lstrCodRef)
								lstrFlgIte = PegaFlgConv115Codigo(lstrCodIte, lstrClasItem)
								If lstrFlgIte = "S" Then
									If lstrGrupo = "B" Then
										If VB.Left(lstrCodIte, 9) = "030202009" Then
											If lintLimite > 0 Then
												If ldblQtdConsumo > lintLimite Then
													ldblQtdCons1 = lintLimite
													ldblQtdCons2 = ldblQtdConsumo - lintLimite
												Else
													ldblQtdCons1 = ldblQtdConsumo
													ldblQtdCons2 = 0
												End If
											Else
												ldblQtdCons1 = ldblQtdConsumo
												ldblQtdCons2 = 0
											End If
											
											If ldblQtdCons1 > 0 Then
												With Me.mfgDados
													.Rows = .Rows + 1
													.set_TextMatrix(.Rows - 1, 0, lstrCodIte)
													.set_TextMatrix(.Rows - 1, 1, codTodescri(lstrCodIte))
													.set_TextMatrix(.Rows - 1, 2, lstrClasItem)
													.set_TextMatrix(.Rows - 1, 3, Truncate(ldblQtdCons1 * ldblTarB(0), 2))
													.set_TextMatrix(.Rows - 1, 4, "( " & ldblQtdCons1 & " x " & VB6.Format(ldblTarB(0), "#,#####0.00000") & " )")
													.set_TextMatrix(.Rows - 1, 5, ldblQtdCons1)
													.set_TextMatrix(.Rows - 1, 6, VB6.Format(ldblTarB(0), "#,#####0.00000"))
													.set_TextMatrix(.Rows - 1, 7, VB6.Format(ldblTarB(0) / Truncate(1 - (((ldblAliqPis / 100) + (ldblAliqCof / 100)) + (ldblAliqIcms1 / 100)), 11), "#,#####0.00000"))
													.set_TextMatrix(.Rows - 1, 8, Truncate(CDbl(.get_TextMatrix(.Rows - 1, 3)) * (ldblAliqIcms1 / 100), 2))
												End With
											End If
											If ldblQtdCons2 > 0 Then
												lstrCodIte = VB.Left(lstrCodIte, 9) & "1"
												With Me.mfgDados
													.Rows = .Rows + 1
													.set_TextMatrix(.Rows - 1, 0, lstrCodIte)
													.set_TextMatrix(.Rows - 1, 1, codTodescri(lstrCodIte))
													.set_TextMatrix(.Rows - 1, 2, lstrClasItem)
													.set_TextMatrix(.Rows - 1, 3, Truncate(ldblQtdCons2 * ldblTarB(1), 2))
													.set_TextMatrix(.Rows - 1, 4, "( " & ldblQtdCons2 & " x " & VB6.Format(ldblTarB(1), "#,#####0.00000") & " )")
													.set_TextMatrix(.Rows - 1, 5, ldblQtdCons2)
													.set_TextMatrix(.Rows - 1, 6, VB6.Format(ldblTarB(1), "#,#####0.00000"))
													.set_TextMatrix(.Rows - 1, 7, VB6.Format(ldblTarB(1) / Truncate(1 - (((ldblAliqPis / 100) + (ldblAliqCof / 100)) + (ldblAliqIcms2 / 100)), 11), "#,#####0.00000"))
													.set_TextMatrix(.Rows - 1, 8, Truncate(CDbl(.get_TextMatrix(.Rows - 1, 3)) * (ldblAliqIcms2 / 100), 2))
												End With
											End If
										Else
											If VB.Left(lstrCodIte, 10) <> "0302020009" Then
												With Me.mfgDados
													.Rows = .Rows + 1
													.set_TextMatrix(.Rows - 1, 0, lstrCodIte)
													.set_TextMatrix(.Rows - 1, 1, codTodescri(lstrCodIte))
													.set_TextMatrix(.Rows - 1, 2, lstrClasItem)
													.set_TextMatrix(.Rows - 1, 3, VB6.Format(Val(lstrCodVlr), "#,##0.00"))
													.set_TextMatrix(.Rows - 1, 4, Trim(lstrCodRef))
												End With
											End If
										End If
									End If
								End If
							Next llngPosIte
							
							
							
							
							
							
							'            '##########################################################
							'            'Baixa Renda
							'
							'            ldblValorItem = 0
							'            ldblValorBxRenda = 0
							'
							'            If lblnBaixaRenda Then
							'              ldblValorBxRenda = BuscaValorItem(lstrItensserv, "030202009") 'Valor Faturado
							'              If ldblValorBxRenda = 0 Then
							'                ldblValorBxRenda = BuscaValorItem(lstrItensserv, "030202008") 'Valor Lido
							'              End If
							'              ldblValorItem = ldblValorBxRenda
							'            End If
							'            '##########################################################
							'            lstrSql = ""
							'            lstrSql = lstrSql & "SELECT codigovlr, codigoqtde, descri, bxrenda FROM conv115 "
							'            If lblnBaixaRenda Then
							'              lstrSql = lstrSql & " WHERE bxrenda = 'S' "
							'            End If
							'            lstrSql = lstrSql & " UNION "
							'            lstrSql = lstrSql & "SELECT num AS codigovlr, '' AS codigoqtde, descri AS descri, 'S' AS bxrenda FROM codigos WHERE LEFT(num, 1) = 9 AND LEFT(num, 4) NOT IN('9041', '9090') "
							'            Call Conectar(lstrSql, lrstAux)
							'            With lrstAux
							'              If .State = adodb.ObjectStateEnum.adStateOpen Then
							'                If .RecordCount > 0 Then
							'                  While Not .EOF
							'                    lstrCodValor = IIf(IsNull(.Fields("codigovlr").Value), "", .Fields("codigovlr").Value)
							'                    lstrCodQtde = IIf(IsNull(.Fields("codigoqtde").Value), "", .Fields("codigoqtde").Value)
							'                    lstrCodDescri = IIf(IsNull(.Fields("descri").Value), "", .Fields("descri").Value)
							'                    If lstrCodValor <> "" Then
							'                      'Cria o array dos valores do item selecionado
							'                      lstrValorItens = buscaValoresItem(lstrItensserv, lstrCodValor)
							'                      '
							'                      'Percorre dentro do array dos valores do item selecionado, qdo tem mais de um registro do mesmo codigo dentro dos itens da fatura
							'                      For lintAux = 0 To UBound(lstrValorItens)
							'                        ldblArredondamento = 0
							'                        ldblDesconto = 0
							'                        ldblValorItem = lstrValorItens(lintAux)
							'                        'Codigos usados para o consumidor Livre para controle dos descontos de CCEE
							'                        If Left(lstrCodValor, 9) = "030202005" And Right(lstrCodValor, 1) < 4 Then
							'                          ldblValorItem = ldblValorItem * -1
							'                        End If
							'                        '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Consumo 1 E 2 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
							'                        If lstrCodValor = "0502020001" Then
							'                          If (ldblQtdConsumo > 150 And Left(lstrClasse, 1) = "9") Or (ldblQtdConsumo > 500 And Left(lstrClasse, 1) = "5") Then
							'                            If Left(lstrClasse, 1) = "5" Then
							'                              ldblQtdeItem = 500
							'                            ElseIf Left(lstrClasse, 1) = "9" Then
							'                              ldblQtdeItem = 150
							'                            End If
							'                          Else
							'                            ldblQtdeItem = ldblQtdConsumo
							'                          End If
							'                          ldblValorItem = Arredondar(ldblVlrConsumo * (ldblQtdeItem / ldblQtdConsumo), 2) 'Certo é pegar a tarifa e recalcular
							'                        ElseIf lstrCodValor = "0502020002" Then
							'                          If (ldblQtdConsumo > 150 And Left(lstrClasse, 1) = "9") Or (ldblQtdConsumo > 500 And Left(lstrClasse, 1) = "5") Then
							'                            'rural
							'                            If Left(lstrClasse, 1) = "5" Then
							'                              ldblQtdeItem = ldblQtdConsumo - 500
							'                            Else
							'                              'residencial e demais
							'                              ldblQtdeItem = ldblQtdConsumo - 150
							'                            End If
							'                            ldblValorItem = Arredondar(ldblVlrConsumo * (ldblQtdeItem / ldblQtdConsumo), 2) 'Certo é pegar a tarifa e recalcular
							'                          End If
							'                        End If
							'                        '
							'                        ' Código de quantidade dos valores de itens da fatura
							'                        If Strings.Len(Strings.Trim(lstrCodQtde)) > 0 Then
							'                          ldblQtdeItem = BuscaValorItem(lstrItensserv, lstrCodQtde)
							'                        End If
							'                        If ldblQtdeItem < 1 Then
							'                          ldblQtdeItem = 1
							'                        End If
							'                        ldblQtdeFat = ldblQtdeItem
							'                        If lstrCodValor = "0502020001" And (lstrGrpTen = "05" Or ldblMust > 0) Then 'Grupo A
							'                          lstrCodValor = ""
							'                        End If
							'                        If (ldblValorItem <> 0 Or lstrCodValor = "0502020001") Then
							'                          llngRefItem = llngRefItem + 1
							'                          If ldblAliqIcms1 > 0 Then
							'                            If lblnBaixaRenda = True Then
							'
							'                              'ldblBaseTotalIcms = BuscaValorItem(lstrItensserv, "0302030015") 'base de icms total *** validar por que nao fecha com os valores individuais das bases
							'                              If lstrCodDescri = "ICMS" Then
							'                                'ldblBCitens = ldblBaseTotalIcms - (ldblVlrPis + ldblVlrCofins + ldblValorBxRenda)
							'                                ldblBCitens = ldblBaseIcms - (ldblVlrPis + ldblVlrCofins + ldblValorBxRenda)
							'                                ldblIcmsItens = Arredondar(ldblBCitens * (ldblAliqIcms1 / 100), 2)
							'                              Else
							'                                ldblBCitens = ldblValorItem
							'                                ldblIcmsItens = Arredondar(ldblValorItem * (ldblAliqIcms1 / 100), 2)
							'                              End If
							'                            Else
							'                              ldblBCitens = ldblValorItem - ldblDesconto
							'                              ldblIcmsItens = Arredondar(ldblBCitens * (ldblAliqIcms1 / 100), 2)
							'                            End If
							'                          Else
							'                            ldblIcmsItens = 0
							'                            ldblBCitens = 0
							'                            ldblAliqIcms1 = 0
							'                          End If
							'                          ldblOutros = 0
							'                          ldblIsento = 0
							'                          If ldblAliqIcms1 = 0 And Left(lstrCodValor, 2) <> "90" And lstrCodValor <> "0302990041" And lstrCodValor <> "0301000003" Then '
							'                            ldblIsento = ldblValorItem
							'                          Else
							'                            ldblIsento = 0
							'                          End If
							'                          If Left(lstrCodValor, 2) = "90" Or lstrCodValor = "0302990041" Or lstrCodValor = "0301000003" Then 'arredonda
							'                            ldblBCitens = 0
							'                            ldblIcmsItens = 0
							'                            ldblIsento = 0
							'                            If Left(lstrCodValor, 4) = "9070" Then
							'                              ldblOutros = ldblValorItem * (-1)
							'                              ldblValorItem = ldblOutros
							'                            Else
							'                              ldblOutros = ldblValorItem
							'                            End If
							'                            ldblAliqIcms1 = 0
							'                          End If
							'                          lstrUnidItem = ""
							'                          If Left(lstrCodDescri, 7) = "CONSUMO" And (Left(lstrCodValor, 6) = "030202" Or Left(lstrCodValor, 6) = "050202") Then
							'                            lstrClasItem = "0601"
							'                            lstrUnidItem = "KWH"
							'                          ElseIf Left(lstrCodDescri, 7) = "DEMANDA" And Left(lstrCodValor, 6) = "030202" Then
							'                            lstrClasItem = "0602"
							'                            lstrUnidItem = "KW"
							'                          ElseIf Left(lstrCodValor, 4) = "9040" Then
							'                            lstrClasItem = "0603"
							'                          Else
							'                            lstrClasItem = "0699"
							'                          End If
							'                          '##################################################################################################
							'                          ' Essa parte foi feita para poder fechar o valor total da base mestre com a soma da base dos itens
							'                          If lstrCodValor = "0302030009" Or lstrCodValor = "0302030010" Then
							'                             ldblBCitens = ldblBaseIcms
							'                             ldblIcmsItens = ldblVlrIcms
							'                          End If
							'                          If lstrCodValor = "0302990041" Then
							'                            ldblValorItem = Arredondar(ldblValorTot, 2)
							'                            ldblOutros = Arredondar(ldblTotalOutros, 2)
							'                          End If
							'                          If ldblAliqIcms1 = 0 Then
							'                            'If lstrCodValor = "0302020029" Then
							'                            '  ldblIsento = ldblBasePis
							'                            'End If
							'                          End If
							'                          'If ldblArredondamento = 0 Then
							'                          '  ldblOutros = Arredondar(ldblOutros, 2)
							'                          '  ldblValorItem = Arredondar(ldblValorItem, 2)
							'                          'End If
							'                          ldblTotalOutros = ldblTotalOutros - ldblOutros
							'                          ldblBasePis = Arredondar(ldblBasePis - ldblIsento, 2)
							'                          ldblValorTot = Arredondar(ldblValorTot - (ldblValorItem - ldblDesconto), 2)
							'                          ldblBaseIcms = ldblBaseIcms - ldblBCitens
							'                          ldblVlrIcms = ldblVlrIcms - ldblIcmsItens
							'                          '##################################################################################################
							'                          lstrLin = ""
							'                          lstrLin = lstrLin & PreparaCampo(lstrCpf, NUMERICO, 14, "0") '01 - CPF ou CNPJ
							'                          lstrLin = lstrLin & PreparaCampo(lstrUf, ALFANUMERICO, 2, " ") '02 - Uf
							'                          lstrLin = lstrLin & PreparaCampo(PegaCodClasse(lstrClasse), ALFANUMERICO, 1, " ") '03 Classe do consumo - tabela 11.1
							'                          lstrLin = lstrLin & PreparaCampo(IIf(lstrFase = "M", "1", IIf(lstrFase = "B", "2", "3")), ALFANUMERICO, 1, " ") '04 - Fase - tabela 11.2
							'                          lstrLin = lstrLin & PreparaCampo(lstrGrpTen, ALFANUMERICO, 2, " ") '05 - Grupo de tensão - tabela 11.3
							'                          lstrLin = lstrLin & PreparaCampo(Strings.Format(ldteEmissao, "yyyymmdd"), ALFANUMERICO, 8, " ") '06 - Data de emissao AAAAMMDDDD
							'                          lstrLin = lstrLin & PreparaCampo("06", ALFANUMERICO, 2, " ") '07 - Modelo tabela 11.4
							'                          lstrLin = lstrLin & PreparaCampo("UUU", ALFANUMERICO, 3, " ") '08- Série utillizar a letra U para série única.
							'                          lstrLin = lstrLin & PreparaCampo(Conversion.CStr(ldblNumNF), NUMERICO, 9, "0")  '09 - Número da fatura 000000000
							'                          lstrLin = lstrLin & PreparaCampo(lstrCfop, ALFANUMERICO, 4, " ") '10
							'                          lstrLin = lstrLin & PreparaCampo(Conversion.CStr(llngRefItem), NUMERICO, 3, "0") '11
							'                          lstrLin = lstrLin & PreparaCampo(lstrCodValor, ALFANUMERICO, 10, " ") '12
							'                          lstrLin = lstrLin & PreparaCampo(lstrCodDescri, ALFANUMERICO, 40, " ") '13
							'                          lstrLin = lstrLin & PreparaCampo(lstrClasItem, ALFANUMERICO, 4, " ") '14 - Classificacao do item tabela 11.5
							'                          lstrLin = lstrLin & PreparaCampo(lstrUnidItem, ALFANUMERICO, 6, " ") '15 - Unidade
							'                          lstrLin = lstrLin & PreparaCampo(Conversion.CStr(ldblQtdeItem), NUMERICO, 11, "0") '16 - Quantidade contratada
							'                          lstrLin = lstrLin & PreparaCampo(Conversion.CStr(ldblQtdeFat), NUMERICO, 11, "0") '17 - Quantidade prestada ou fornecida
							'                          lstrLin = lstrLin & IIf(ldblValorItem < 0, "-", "") & PreparaCampo(Strings.Replace(Strings.Format((ldblValorItem * IIf(ldblValorItem < 0, -1, 1)), "#,##0.00"), ".", ""), NUMERICO, IIf(ldblValorItem < 0, 10, 11), "0") '18 - Total (com 2 decimais)
							'                          lstrLin = lstrLin & IIf(ldblDesconto < 0, "-", "") & PreparaCampo(Strings.Replace(Strings.Format((ldblDesconto * IIf(ldblDesconto < 0, -1, 1)), "#,##0.00"), ".", ""), NUMERICO, IIf(ldblDesconto < 0, 10, 11), "0")     '19 - Desconto / Redutores
							'                          lstrLin = lstrLin & PreparaCampo("", NUMERICO, 11, "0") '20 - Acréscimos e Despesas Acessórias
							'                          lstrLin = lstrLin & IIf(ldblBCitens < 0, "-", "") & PreparaCampo(Strings.Replace(Strings.Format((ldblBCitens * IIf(ldblBCitens < 0, -1, 1)), "#,##0.00"), ".", ""), NUMERICO, IIf(ldblBCitens < 0, 10, 11), "0") '21 - BC Icms
							'                          lstrLin = lstrLin & IIf(ldblIcmsItens < 0, "-", "") & PreparaCampo(Strings.Replace(Strings.Format((ldblIcmsItens * IIf(ldblIcmsItens < 0, -1, 1)), "#,##0.00"), ".", ""), NUMERICO, IIf(ldblIcmsItens < 0, 10, 11), "0") '22 - ICMS
							'                          lstrLin = lstrLin & IIf(ldblIsento < 0, "-", "") & PreparaCampo(Strings.Replace(Strings.Format((ldblIsento * IIf(ldblIsento < 0, -1, 1)), "#,##0.00"), ".", ""), NUMERICO, IIf(ldblIsento < 0, 10, 11), "0") '23 - Operações Isentas ou não tributadas
							'                          lstrLin = lstrLin & IIf(ldblOutros < 0, "-", "") & PreparaCampo(Strings.Replace(Strings.Format((ldblOutros * IIf(ldblOutros < 0, -1, 1)), "#,##0.00"), ".", ""), NUMERICO, IIf(ldblOutros < 0, 10, 11), "0") '24 - Outros valores
							'                          lstrLin = lstrLin & PreparaCampo(Strings.Replace(Strings.Format(ldblAliqIcms1, "#,##0.00"), ".", ""), NUMERICO, 4, "0") '25 - Aliquota ICMS
							'                          lstrLin = lstrLin & PreparaCampo(lstrSituacaoFatura, ALFANUMERICO, 1, " ") '26 - Situação
							'                          lstrLin = lstrLin & PreparaCampo((Strings.Right(lstrMesAno, 2) & Strings.Left(lstrMesAno, 2)), ALFANUMERICO, 4, " ") '27 - Ano e mês de referência de apuração AAMM
							'                          lstrLin = lstrLin & PreparaCampo("", ALFANUMERICO, 5, " ") '28 - Brancos
							'                          'Monta o HASH COD
							'                          lstrSql = "SELECT CONVERT(md5('" & lstrLin & "') USING latin1) hash;"
							'                          Call Conectar(lstrSql, lrstHash)
							'                          With lrstHash
							'                            If .State = adodb.ObjectStateEnum.adStateOpen Then
							'                              If .RecordCount > 0 Then
							'                                lstrCodAut = IIf(IsNull(.Fields("hash").Value), "", .Fields("hash").Value)
							'                              Else
							'                                lstrCodAut = ""
							'                              End If
							'                              Call .Close
							'                            End If
							'                          End With
							'                          lstrLin = lstrLin & PreparaCampoGrafica(lstrCodAut, ALFANUMERICO, 32, " ") '29 -  Hash
							'                          Print #lintARQ, lstrLin
							'                        End If
							'                      Next lintAux
							'                    End If
							'                    Call .MoveNext
							'                  Wend 'lrstAux
							'                End If 'recordcount
							'                Call lrstAux.Close
							'              End If
							'            End With
							Call .MoveNext()
							Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
						End While 'lrstFat
						FileClose(lintARQ)
						Me.lblInfo.Text = Me.lblInfo.Text & " Arquivo gerado!"
						Call Me.lblInfo.Refresh()
					Else
						Call MsgBox("Não existe dados neste mês!", MsgBoxStyle.Information, gstrTituloMensagem)
					End If
					Call .Close()
				End If
			End With
			Me.Cursor = System.Windows.Forms.Cursors.Arrow
		Else
			Call MsgBox("Favor informe o arquivo do Cadastro!", MsgBoxStyle.Information, gstrTituloMensagem)
			Me.txtItens.Focus()
		End If
		'UPGRADE_NOTE: Object lrstFat may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstFat = Nothing
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		'UPGRADE_NOTE: Object lrstHash may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstHash = Nothing
	End Sub
	
	Private Function TrataCampo(ByVal astrCampo As String, ByVal alngTamanho As Integer, ByVal astrCaracter As String, Optional ByVal aintAlinhamento As Short = 1) As String
		Dim lstrCampo As String
		
		lstrCampo = Trim(astrCampo)
		If aintAlinhamento = 1 Then 'Esquerda
			lstrCampo = VB.Left(lstrCampo & New String(astrCaracter, alngTamanho), alngTamanho)
		ElseIf aintAlinhamento = 2 Then  'Direita
			lstrCampo = VB.Right(New String(astrCaracter, alngTamanho) & lstrCampo, alngTamanho)
		End If
		
		TrataCampo = lstrCampo
	End Function
	
	Private Function PreparaCampoGrafica(ByRef Campo As String, ByRef tipo_campo As Short, ByRef comp As Short, ByRef Caracter As String) As String
		Campo = Trim(Campo)
		
		'tipo NUMERICO
		If tipo_campo = 0 Then
			Campo = Replace(Campo, ",", "")
			Campo = Replace(Campo, ".", "")
			
			If Len(Campo) > comp Then
				PreparaCampoGrafica = VB.Left(Campo, comp)
			Else
				PreparaCampoGrafica = New String(Caracter, comp - Len(Campo)) & Campo
			End If
		End If
		
		'tipo ALFANUMÉRICO
		If tipo_campo = 1 Then
			If Len(Campo) > comp Then
				PreparaCampoGrafica = VB.Left(Campo, comp)
			Else
				PreparaCampoGrafica = Campo & New String(Caracter, comp - Len(Campo))
			End If
		End If
	End Function
	
	Private Function BuscaValorItem(ByRef astrTexto As String, ByRef astrCod As String) As Double
		Dim lintP1 As Short
		Dim lintP2 As Short
		Dim lintP3 As Short
		Dim lintP4 As Short
		Dim lintProx As Short
		Dim lstrAux As String
		Dim lstrCod As String
		Dim ldblVlrTotal As Double
		Dim lstrItem As String
		Dim lstrNCod As String
		Dim lintTamTexto As Short
		
		lintTamTexto = Len(astrTexto)
		lstrNCod = ";" & astrCod
		
		If VB.Left(astrTexto, Len(astrCod)) = astrCod Then
			lintP1 = 1
		Else
			lintP1 = InStr(1, astrTexto, lstrNCod) + 1
		End If
		
		ldblVlrTotal = 0
		
		If lintP1 > 0 Then
			While lintP1 <= lintTamTexto
				lintP4 = InStr(lintP1, astrTexto, ";")
				lintProx = InStr(lintP4, astrTexto, lstrNCod)
				If lintProx = 0 Then
					lintProx = lintTamTexto + 1
				Else
					lintProx = lintProx + 1
				End If
				lstrItem = Mid(astrTexto, lintP1, lintP4 - lintP1)
				lintP2 = InStr(1, lstrItem, "?")
				lintP3 = InStr(1, lstrItem, "$")
				If VB.Left(VB.Left(lstrItem, lintP2 - 1), Len(astrCod)) = astrCod Then
					If lintP3 > 0 Then
						ldblVlrTotal = ldblVlrTotal + CDbl(Replace(Mid(lstrItem, lintP2 + 1, lintP3 - lintP2 - 1), ".", ","))
					Else
						ldblVlrTotal = ldblVlrTotal + CDbl(Replace(Mid(lstrItem, lintP2 + 1, lintP4 - lintP2 - 1), ".", ","))
					End If
				End If
				lintP1 = lintProx
			End While
		End If
		
		BuscaValorItem = ldblVlrTotal
	End Function
	
	Private Function buscaValoresItem(ByRef astrTexto As String, ByRef astrCod As String) As String()
		Dim lintP1 As Short
		Dim lintP2 As Short
		Dim lintP3 As Short
		Dim lintP4 As Short
		Dim lintProx As Short
		Dim lstrAux As String
		Dim lstrCod As String
		Dim lstrItem As String
		Dim lstrTmp As String
		Dim lstrNCod As String
		Dim lintTamTexto As Short
		
		lstrTmp = ""
		lintTamTexto = Len(astrTexto)
		lstrNCod = ";" & astrCod
		
		If VB.Left(astrTexto, Len(astrCod)) = astrCod Then
			lintP1 = 1
		Else
			lintP1 = InStr(1, astrTexto, lstrNCod) + 1
		End If
		
		If lintP1 > 0 Then
			While lintP1 <= lintTamTexto
				lintP4 = InStr(lintP1, astrTexto, ";")
				lintProx = InStr(lintP4, astrTexto, lstrCod)
				If lintProx = 0 Then
					lintProx = lintTamTexto + 1
				Else
					lintProx = lintProx + 1
				End If
				lstrItem = Mid(astrTexto, lintP1, lintP4 - lintP1)
				lintP2 = InStr(1, lstrItem, "?")
				lintP3 = InStr(1, lstrItem, "$")
				If VB.Left(VB.Left(lstrItem, lintP2 - 1), lintTamTexto) = astrCod Then
					If lintP3 > 0 Then
						lstrTmp = lstrTmp & "$" & Replace(Mid(lstrItem, lintP2 + 1, lintP3 - lintP2 - 1), ".", ",")
					Else
						lstrTmp = lstrTmp & "$" & Replace(Mid(lstrItem, lintP2 + 1, lintP4 - lintP2 - 1), ".", ",")
					End If
				End If
				lintP1 = lintProx
			End While
		End If
		
		If Len(lstrTmp) > 1 Then
			lstrTmp = VB.Right(lstrTmp, Len(lstrTmp) - 1)
		Else
			lstrTmp = ""
		End If
		If astrCod = "0502020001" Or astrCod = "0502020002" Then
			buscaValoresItem = Split(CStr(0), "$")
		Else
			buscaValoresItem = Split(lstrTmp, "$")
		End If
	End Function
	
	Private Function GeraHash(ByVal astrValor As String) As Object
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		Call Conectar("SELECT CONVERT(MD5(""" & astrValor & """) USING latin1) as `hash`", lrstAux)
		If lrstAux.RecordCount > 0 Then
			'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
			GeraHash = UCase(Trim(IIf(IsDbNull(lrstAux.Fields("hash").value), "", lrstAux.Fields("hash").value)))
		Else
			'UPGRADE_WARNING: Couldn't resolve default property of object GeraHash. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			GeraHash = ""
		End If
		If lrstAux.State = 1 Then lrstAux.Close()
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
	End Function
	
	Private Sub frmConvenio115SC_MouseUp(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
		Dim Button As Short = eventArgs.Button \ &H100000
		Dim Shift As Short = System.Windows.Forms.Control.ModifierKeys \ &H10000
		Dim X As Single = VB6.PixelsToTwipsX(eventArgs.X)
		Dim Y As Single = VB6.PixelsToTwipsY(eventArgs.Y)
		If Shift = 1 And Button = 2 Then
			If VB6.PixelsToTwipsY(Me.Height) = 3270 Then
				Me.Height = VB6.TwipsToPixelsY(5070)
			Else
				Me.Height = VB6.TwipsToPixelsY(3270)
			End If
		End If
	End Sub
	
	Private Sub cmdTeste_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdTeste.Click
		Dim lstrCpfCnpj As String
		Dim lstrMesAno As String
		Dim ldblNumNF As Double
		Dim lstrItensserv As String
		Dim ldblVlrTot As Double
		Dim lstrClasse As String
		Dim ldblBaseIcms As Double
		Dim ldblVlrIcms As Double
		Dim lstrHash As String
		Dim lstrHashNovo As String
		Dim lstrSql As String
		Dim lrstConsulta As New ADODB.Recordset
		Dim dblcont As Double
		
		'ldblNumNF = txtFiltroNF.Text
		lstrMesAno = VB6.Format(Me.dtpMesAno.value, "mm/yyyy")
		
		Me.Cursor = System.Windows.Forms.Cursors.AppStarting
		Me.lblInfo.Text = " Buscando os dados... "
		Me.lblInfo.Refresh()
		
		lstrSql = "SELECT numnf,itensserv, valortot,valorliq,codclas, codhash,cpf_cnpj FROM nf WHERE mesano = '" & lstrMesAno & "' "
		If Me.txtClasse.Text <> "" Then
			lstrSql = lstrSql & " AND LEFT(codclas," & Len(Me.txtClasse.Text) & ") = '" & Me.txtClasse.Text & "' "
		End If
		If Me.txtGrupo.Text <> "" Then
			lstrSql = lstrSql & " AND grupo = '" & Me.txtGrupo.Text & "' "
		End If
		
		If (Trim(Me.txtFiltroNF.Text) <> "") Then
			lstrSql = lstrSql & " AND numnf = " & Me.txtFiltroNF.Text
		End If
		
		If (Trim(Me.txtNFinicial.Text)) <> "" And (Trim(Me.txtnfFinal.Text)) <> "" Then
			lstrSql = lstrSql & " AND numnf BETWEEN '" & txtNFinicial.Text & "' " & "AND '" & txtnfFinal.Text & "' "
		End If
		
		lstrSql = lstrSql & " ORDER BY numnf ASC "
		If (Trim(Me.txtFiltroLimite.Text) <> "") Then
			lstrSql = lstrSql & " LIMIT 0," & Me.txtFiltroLimite.Text
		End If
		
		Call Conectar(lstrSql, lrstConsulta)
		
		With lrstConsulta
			dblcont = 0
			If lrstConsulta.RecordCount > 0 Then
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, .RecordCount)
				While Not .EOF
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrHash = IIf(IsDbNull(.Fields("codhash").value), "", .Fields("codhash").value)
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldblNumNF = IIf(IsDbNull(.Fields("numnf").value), 0, .Fields("numnf").value)
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrClasse = IIf(IsDbNull(.Fields("codclas").value), "0000", .Fields("codclas").value)
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldblVlrTot = IIf(IsDbNull(.Fields("valortot").value), 0, .Fields("valortot").value)
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrItensserv = IIf(IsDbNull(.Fields("itensserv").value), 0, .Fields("itensserv").value)
					ldblBaseIcms = BuscaValorItem(lstrItensserv, "0302030001") + BuscaValorItem(lstrItensserv, "0302030003")
					ldblVlrIcms = BuscaValorItem(lstrItensserv, "0302030009") + BuscaValorItem(lstrItensserv, "0302030010")
					If ldblVlrIcms = 0 Then
						ldblBaseIcms = 0
					End If
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrCpfCnpj = IIf(IsDbNull(.Fields("cpf_cnpj").value), 0, .Fields("cpf_cnpj").value)
					lstrHashNovo = ""
					lstrHashNovo = lstrHashNovo & TrataCampo(lstrCpfCnpj, 14, "0", 2)
					lstrHashNovo = lstrHashNovo & TrataCampo(VB6.Format(ldblNumNF, "0"), 9, "0", 2)
					lstrHashNovo = lstrHashNovo & TrataCampo(Replace(VB6.Format(ldblVlrTot, "0.00"), ",", ""), 12, "0", 2)
					lstrHashNovo = lstrHashNovo & TrataCampo(Replace(VB6.Format(ldblBaseIcms, "0.00"), ",", ""), 12, "0", 2)
					lstrHashNovo = lstrHashNovo & TrataCampo(Replace(VB6.Format(ldblVlrIcms, "0.00"), ",", ""), 12, "0", 2)
					'UPGRADE_WARNING: Couldn't resolve default property of object GeraHash(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					lstrHashNovo = GeraHash(lstrHashNovo)
					If lstrHashNovo <> lstrHash Then
						lstrSql = "UPDATE nf SET codhash = '" & lstrHashNovo & "' WHERE numnf = '" & ldblNumNF & "' AND mesano = '" & lstrMesAno & "' "
						Call Executar(lstrSql)
						dblcont = dblcont + 1
					End If
					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1, .RecordCount)
					.MoveNext()
					System.Windows.Forms.Application.DoEvents()
				End While
			Else
				Call MsgBox("Fatura(s) inexistente")
				If .State = 1 Then Call .Close()
			End If
		End With
		Me.lblInfo.Text = " Arquivo gerado!"
		Me.lblInfo.Refresh()
		Me.Cursor = System.Windows.Forms.Cursors.Arrow
		Call MsgBox(" Foram alterados " & dblcont & " Notas Fiscais com Número de hash incorreto", MsgBoxStyle.Information, gstrTituloMensagem)
	End Sub
	
	Private Function PegaCodGrupoTensao(ByVal astrGrTar As String, ByVal astrClasse As String, ByVal astrTensao As String) As String
		Dim lstrRet As String
		If astrGrTar = "A1" Then
			lstrRet = "01"
		ElseIf astrGrTar = "A2" Then 
			lstrRet = "02"
		ElseIf astrGrTar = "A3" Then 
			If IsNumeric(astrTensao) Then
				If CDbl(astrTensao) >= 30000 And CDbl(astrTensao) <= 44000 Then
					lstrRet = "04"
				Else
					lstrRet = "03"
				End If
			Else
				lstrRet = "03"
			End If
		ElseIf VB.Left(astrGrTar, 1) = "A" Then 
			lstrRet = "05"
		ElseIf astrGrTar = "B1" Then 
			If (VB.Left(astrClasse, 1) = "9" And (astrClasse <> "9104" Or astrClasse <> "9105" Or astrClasse <> "9106")) Then
				lstrRet = "07"
			Else
				lstrRet = "08"
			End If
		ElseIf astrGrTar = "B2" Then 
			If VB.Left(astrClasse, 2) = "52" Then 'Coop.
				lstrRet = "10"
			ElseIf VB.Left(astrClasse, 2) = "55" Then  'Irrigação
				lstrRet = "11"
			Else
				lstrRet = "09"
			End If
		ElseIf astrGrTar = "B3" Then 
			lstrRet = "12"
		ElseIf astrGrTar = "B4" Then 
			If VB.Right(astrClasse, 2) = "01" Then 'Rede
				lstrRet = "13"
			Else
				lstrRet = "14"
			End If
		Else
			lstrRet = "07"
		End If
		PegaCodGrupoTensao = lstrRet
	End Function
	
	Private Function PegaCodClasse(ByVal astrClasse As String) As String
		Dim lstrRet As String
		If VB.Left(astrClasse, 1) = "4" Then 'Comercial
			lstrRet = "1"
		ElseIf VB.Left(astrClasse, 1) = "8" Then  'Consumo Próprio
			lstrRet = "2"
		ElseIf VB.Left(astrClasse, 2) = "64" Then  'Iluminação
			lstrRet = "3"
		ElseIf VB.Left(astrClasse, 1) < "4" Then  'Industrial
			lstrRet = "4"
		ElseIf VB.Left(astrClasse, 2) = "61" Or VB.Left(astrClasse, 2) = "62" Or VB.Left(astrClasse, 2) = "63" Then  'Poder Público
			lstrRet = "5"
		ElseIf VB.Left(astrClasse, 1) = "9" Then  'Residencial
			lstrRet = "6"
		ElseIf VB.Left(astrClasse, 1) = "5" Then  'Rural
			lstrRet = "7"
		ElseIf VB.Left(astrClasse, 1) = "7" Then  'Serviço Público
			lstrRet = "8"
		End If
		PegaCodClasse = lstrRet
	End Function
	
	Private Function PegaCFOP(ByVal astrGrTar As String, ByVal astrClasse As String) As String
		Dim lstrRet As String
		If VB.Left(astrGrTar, 1) = "B" Then
			If CDbl(VB.Left(astrClasse, 1)) < 4 Then ' INDUSTRIAL
				lstrRet = "5252"
			ElseIf CDbl(VB.Left(astrClasse, 1)) = 4 Then  ' COMERCIAL
				lstrRet = "5253"
				If CDbl(VB.Left(astrClasse, 2)) = 42 Then ' SERVIÇO TRANSPORTE
					lstrRet = "5254"
				ElseIf CDbl(VB.Left(astrClasse, 2)) = 43 Then  ' SERVIÇO COMUNICAÇÃO
					lstrRet = "5255"
				End If
			ElseIf CDbl(VB.Left(astrClasse, 1)) = 5 Then  ' RURAL
				lstrRet = "5256"
			ElseIf CDbl(VB.Left(astrClasse, 2)) = 61 Then  ' PODER PÚBLICO MUNICIPAL
				lstrRet = "5258"
			ElseIf CDbl(VB.Left(astrClasse, 2)) = 62 Then  ' PODER PÚBLICO ESTADUAL
				lstrRet = "5258"
			ElseIf CDbl(VB.Left(astrClasse, 2)) = 63 Then  ' PODER PÚBLICO FEDERAL
				lstrRet = "5258"
			ElseIf CDbl(VB.Left(astrClasse, 2)) = 64 Then  ' ILUMINAÇÃO PÚBLICA
				lstrRet = "5258"
			ElseIf CDbl(VB.Left(astrClasse, 1)) = 7 Then  ' SERVIÇO PÚBLICO
				lstrRet = "5258"
			ElseIf CDbl(VB.Left(astrClasse, 1)) = 8 Then  ' CONSUMO PRÓPRIO
				lstrRet = "5253"
			ElseIf CDbl(VB.Left(astrClasse, 1)) = 9 Then  ' RESIDENCIAL NORMAL
				lstrRet = "5258"
			End If
		Else ' DEMANDA CONTRATADA
			lstrRet = "5257"
		End If
		PegaCFOP = lstrRet
	End Function
	
	Private Sub BuscaItemNf(ByRef alngPosicaoInicial As Integer, ByVal astrItensFatura As String, ByRef astrCodigo As String, ByRef astrCodValor As String, ByRef astrCodRefer As String)
		'Esta rotina atribui valores  do codigo, valor e referencia nos argumentos passados como referencia.
		' CÓDIGO ? VALOR $ REFERENCIA ;
		'exemplo 1: 0302010080?118.00;    ou exemplo 2: 0302020080?41.65$( 118 x 0,35300 );
		Dim llngPosInterr As Integer
		Dim llngPosPtoVir As Integer
		Dim llngPosCifrao As Integer
		'
		llngPosInterr = InStr(alngPosicaoInicial, Trim(astrItensFatura), "?") 'Posição do código
		'
		llngPosCifrao = InStr(llngPosInterr, astrItensFatura, "$") 'Posição da referencia
		'
		llngPosPtoVir = InStr(llngPosInterr, astrItensFatura, ";") 'Posição Final do Item
		'
		astrCodigo = Mid(astrItensFatura, alngPosicaoInicial, llngPosInterr - alngPosicaoInicial)
		'
		If llngPosCifrao <= llngPosPtoVir And llngPosCifrao > 0 Then
			astrCodValor = Mid(astrItensFatura, llngPosInterr + 1, (llngPosCifrao - llngPosInterr) - 1)
			astrCodRefer = Mid(astrItensFatura, llngPosCifrao + 1, (llngPosPtoVir - 1) - llngPosCifrao)
		Else
			astrCodValor = Mid(astrItensFatura, llngPosInterr + 1, (llngPosPtoVir - llngPosInterr) - 1)
			astrCodRefer = ""
		End If
		astrCodValor = Replace(astrCodValor, ",", ".")
		
		alngPosicaoInicial = llngPosPtoVir
	End Sub
	
	Private Function PegaFlgConv115Codigo(ByVal astrCodigo As String, ByRef astrClasIte As String) As String
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM `codigos` "
		lstrSql = lstrSql & " WHERE `num` = '" & astrCodigo & "' "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					'UPGRADE_WARNING: Couldn't resolve default property of object Interaction.IIf(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("flgconv115").value), "N", .Fields("flgconv115").value))
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					'UPGRADE_WARNING: Couldn't resolve default property of object Interaction.IIf(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					astrClasIte = Trim(IIf(IsDbNull(.Fields("clasconv115").value), "0699", .Fields("clasconv115").value))
				Else
					lstrRet = "N"
					astrClasIte = "0699"
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		PegaFlgConv115Codigo = lstrRet
	End Function
	
	Private Function BuscaGrupoTar(ByVal astrClasse As String) As String
		Dim lstrRet As String
		Select Case CDbl(VB.Left(astrClasse, 1)) + 0
			Case Is < 4
				lstrRet = "01B3101101"
			Case Is = 4
				lstrRet = "01B3301101"
			Case Is = 5
				lstrRet = "01B2011101"
			Case Is = 6
				If VB.Left(astrClasse, 2) = "64" Then
					If CDbl(VB.Right(astrClasse, 1)) = 2 Then
						lstrRet = "01B4021101"
					Else
						lstrRet = "01B4011101"
					End If
				Else
					lstrRet = "01B3501101"
				End If
			Case Is = 7
				lstrRet = "01B3201101"
			Case Is = 8
				lstrRet = "01B3401101"
			Case Is = 9
				If CDbl(VB.Right(astrClasse, 1)) = 4 Or CDbl(VB.Right(astrClasse, 1)) = 5 Or CDbl(VB.Right(astrClasse, 1)) = 6 Then
					lstrRet = "01B102110"
				Else
					lstrRet = "01B1011101"
				End If
			Case Else
				lstrRet = "01B1011101"
		End Select
		BuscaGrupoTar = lstrRet
	End Function
End Class