Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Friend Class frmCalcUsina
	Inherits System.Windows.Forms.Form
	Private bNoDrag As Boolean
	Private istrCodMUST As String
	Private Structure iItensServ
		Dim strCod As String
		Dim dblVlr As String
		Dim strRef As String
	End Structure
	
	Private Sub cmdCancelar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancelar.Click
		Me.cmdGerar.Enabled = False
		Me.cmdCancelar.Enabled = False
		Me.txtZona.Text = ""
		Me.txtLivro.Text = ""
		Me.txtConta.Text = ""
		
		Me.txtTa.Text = ""
		Me.txtNome.Text = ""
		Me.txtQtd.Text = "0"
		Me.txtVlrTarifa.Text = "0,00000"
		Me.txtTotMust.Text = "0,00"
		Me.txtReferencia.Text = ""
		Me.txtVlrItem.Text = "0,00"
		Me.cmbCodigos.SelectedIndex = 0
		Me.mfgItens.Rows = 1
		Me.mfgItens.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightNever
		Me.txtVlrTotal.Text = "0,00"
		
		Call SetaStatusFrame((Me.fmeCabec), True)
		Call SetaStatusFrame((Me.fmeDatas), False)
		Call SetaStatusFrame((Me.fmeItens), False)
		Call SetaStatusFrame((Me.fmeMust), False)
		Call Me.txtZona.Focus()
	End Sub
	
	Private Sub GridMUST(ByVal blnAcao As Boolean)
		'blnAcao, TRUE = Adicionar, FALSE = Remover
		Dim lblnMUST As Boolean
		Dim llngCount As Integer
		Dim llngNumRows As Integer
		
		lblnMUST = False
		With Me.mfgItens
			llngNumRows = .Rows
			For llngCount = 1 To (.Rows - 1)
				If llngCount >= (.Rows - 1) Then
					Exit For
				End If
				If .get_TextMatrix(llngCount, 0) = istrCodMUST Then
					If blnAcao Then
						.set_TextMatrix(llngCount, 1, "EUSD-G")
						.set_TextMatrix(llngCount, 2, Me.txtTotMust.Text)
						.set_TextMatrix(llngCount, 3, "( " & Me.txtQtd.Text & " x " & Me.txtVlrTarifa.Text & " )")
						lblnMUST = True
					Else
						If .Rows > 2 Then
							Call .RemoveItem(llngCount)
							llngCount = llngCount - 1
						Else
							.Rows = 1
							.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightNever
						End If
					End If
				End If
			Next 
			If Not lblnMUST And blnAcao Then
				If .Rows > 1 Then
					.Rows = .Rows + 1
					For llngCount = (.Rows - 1) To 1 Step -1
						.set_TextMatrix(llngCount, 0, .get_TextMatrix(llngCount - 1, 0))
						.set_TextMatrix(llngCount, 1, .get_TextMatrix(llngCount - 1, 1))
						.set_TextMatrix(llngCount, 2, .get_TextMatrix(llngCount - 1, 2))
						.set_TextMatrix(llngCount, 3, .get_TextMatrix(llngCount - 1, 3))
					Next 
					
				End If
				.set_TextMatrix(1, 0, istrCodMUST)
				.set_TextMatrix(1, 1, "EUSD-G")
				.set_TextMatrix(1, 2, Me.txtTotMust.Text)
				.set_TextMatrix(1, 3, "( " & Me.txtQtd.Text & " x " & Me.txtVlrTarifa.Text & " )")
			End If
		End With
		
	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 cmdGerar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGerar.Click
		Dim llngCount As Integer
		Dim lblnMUST As Boolean
		
		If CDbl(Me.txtQtd.Text) > 0 Then
			Call GridMUST(True)
			Call GerarNF()
			Call GridMUST(False)
		Else
			Call MsgBox("Obrigatório informar a quantidade do MUST!", MsgBoxStyle.Information, gstrTituloMensagem)
		End If
	End Sub
	
	Private Sub cmdReimprimir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdReimprimir.Click
		Dim lstrSql As String
		Dim lrstConsulta As New ADODB.Recordset
		Dim ldblNumNf As Double
		Dim lblnNFTrans As Boolean
		
		If Len(Trim(Me.txtZonaImp.Text)) = 0 Then
			Call MsgBox("O campo Zona é de preenchimento obrigatório para a reimpressão.", MsgBoxStyle.Information, gstrTituloMensagem)
			Exit Sub
		End If
		
		If Len(Trim(Me.txtLivroImp.Text)) = 0 Then
			Call MsgBox("O campo Livro é de preenchimento obrigatório para a reimpressão.", MsgBoxStyle.Information, gstrTituloMensagem)
			Exit Sub
		End If
		
		If Len(Trim(Me.txtContaImp.Text)) = 0 Then
			Call MsgBox("O campo Conta é de preenchimento obrigatório para a reimpressão.", MsgBoxStyle.Information, gstrTituloMensagem)
			Exit Sub
		End If
		
		lstrSql = "SELECT numnf, 0 AS nfTrans FROM nf " & " WHERE mesano = '" & VB6.Format(Me.dtpMesAnoImp.value, "mm/yyyy") & "'  " & "   AND zona = '" & Me.txtZonaImp.Text & "' " & "   AND livro = '" & Me.txtLivroImp.Text & "' " & "   AND conta = '" & Me.txtContaImp.Text & "' " & "UNION " & "SELECT numnf, 1 AS nfTrans FROM nftransicao " & " WHERE mesano = '" & VB6.Format(Me.dtpMesAnoImp.value, "mm/yyyy") & "'  " & "   AND zona = '" & Me.txtZonaImp.Text & "' " & "   AND livro = '" & Me.txtLivroImp.Text & "' " & "   AND conta = '" & Me.txtContaImp.Text & "' "
		Call Conectar(lstrSql, lrstConsulta)
		
		With lrstConsulta
			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"'
				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"'
				lblnNFTrans = IIf(IsDbNull(.Fields("nfTrans").value), 0, .Fields("nfTrans").value)
				Call ImpFaturaUsina(VB6.Format(Me.dtpMesAnoImp.value, "mm/yyyy"), ldblNumNf, lblnNFTrans)
			Else
				Call MsgBox("Não há faturas para esse consumidor no mês selecionado.", MsgBoxStyle.Information, gstrTituloMensagem)
			End If
			If .State = 1 Then .Close()
		End With
		
	End Sub
	
	Private Sub dtpLeitAnt_Change(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles dtpLeitAnt.Change
		Me.txtVlrTarifa.Text = CStr(TarifaProporcional(Me.dtpLeitAnt.value, Me.dtpLeitAtual.value, "01BU011401", 3))
	End Sub
	
	Private Sub dtpLeitAtual_Change(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles dtpLeitAtual.Change
		Me.txtVlrTarifa.Text = CStr(TarifaProporcional(Me.dtpLeitAnt.value, Me.dtpLeitAtual.value, "01BU011401", 3))
	End Sub
	
	Private Sub mfgItens_MouseDownEvent(ByVal eventSender As System.Object, ByVal eventArgs As AxMSFlexGridLib.DMSFlexGridEvents_MouseDownEvent) Handles mfgItens.MouseDownEvent
		If eventArgs.Button = VB6.MouseButtonConstants.LeftButton Then bNoDrag = True
	End Sub
	
	Private Sub mfgItens_MouseMoveEvent(ByVal eventSender As System.Object, ByVal eventArgs As AxMSFlexGridLib.DMSFlexGridEvents_MouseMoveEvent) Handles mfgItens.MouseMoveEvent
		If bNoDrag Then
			mfgItens.Redraw = False
			mfgItens.Row = mfgItens.MouseRow
			mfgItens.ColSel = mfgItens.Cols - 1
			mfgItens.Redraw = True
		End If
	End Sub
	
	Private Sub mfgItens_MouseUpEvent(ByVal eventSender As System.Object, ByVal eventArgs As AxMSFlexGridLib.DMSFlexGridEvents_MouseUpEvent) Handles mfgItens.MouseUpEvent
		bNoDrag = False
	End Sub
	
	Private Sub frmCalcUsina_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Dim lstrMesAno As String
		
		Me.Icon = FrmAtPrincipal.Icon
		Call CenterForm(Me)
		
		istrCodMUST = "0302020032"
		
		lstrMesAno = Trim(LeConfig("MESANOFATURAMENTO"))
		If lstrMesAno = "" Or lstrMesAno = "-1" Then
			Call MsgBox("Não existe nenhuma fatura em arrecadação!", MsgBoxStyle.Information, gstrTituloMensagem)
			Call Me.Close()
		Else
			Me.dtpMesAno._Value = lstrMesAno
		End If
		
		Me.dtpFat.value = VB6.Format("01/" & lstrMesAno, "dd/mm/yyyy")
		Me.dtpLeitAnt.value = VB6.Format("01/" & VB6.Format(Me.dtpFat.value - 1, "mm/yyyy"), "dd/mm/yyyy")
		Me.dtpLeitAtual.value = VB6.Format("01/" & VB6.Format(Me.dtpFat.value, "mm/yyyy"), "dd/mm/yyyy")
		Me.dtpProxLeit.value = VB6.Format(UltimoDiaMes(Month(Me.dtpFat.value), Year(Me.dtpFat.value)) & "/" & VB6.Format(Me.dtpFat.value, "mm/yyyy"), "dd/mm/yyyy")
		Me.dtpProxLeit.value = Me.dtpProxLeit.value + 1
		'UPGRADE_WARNING: Couldn't resolve default property of object Me.dtpFat.value. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		Me.dtpApres.value = Me.dtpFat.value
		Me.dtpVenc.value = VB6.Format("09/" & VB6.Format(Me.dtpFat.value, "mm/yyyy"), "dd/mm/yyyy")
		Me.dtpMesAnoImp.value = Me.dtpMesAno
		
		Call SetaStatusFrame((Me.fmeDatas), False)
		Call SetaStatusFrame((Me.fmeItens), False)
		Call SetaStatusFrame((Me.fmeMust), False)
		
		Call CarregaCmbCodigos()
		Call MontaGrid()
	End Sub
	
	Private Sub frmCalcUsina_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 = 27 Then
			Call Me.Close()
		ElseIf KeyAscii = 13 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 cmdAdicionar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdAdicionar.Click
		With Me.mfgItens
			If IsNumeric(Replace(Me.txtVlrItem.Text, ",", ".")) Then
				.Rows = .Rows + 1
				.set_TextMatrix(.Rows - 1, 0, Mid(Me.cmbCodigos.Text, 1, 10))
				.set_TextMatrix(.Rows - 1, 1, Mid(Me.cmbCodigos.Text, 14))
				.set_TextMatrix(.Rows - 1, 2, Me.txtVlrItem.Text)
				.set_TextMatrix(.Rows - 1, 3, Me.txtReferencia.Text)
				Me.mfgItens.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightAlways
				
				'Limpa os campos
				If Me.cmbCodigos.Items.Count > 0 Then
					Me.cmbCodigos.SelectedIndex = 0
				Else
					Me.cmbCodigos.SelectedIndex = -1
				End If
				Me.txtVlrItem.Text = "0,00"
				Me.txtReferencia.Text = ""
			Else
				Exit Sub
			End If
		End With
		Call SomaGrid()
	End Sub
	
	Private Sub MontaGrid()
		With Me.mfgItens
			Call .Clear()
			.Cols = 4
			.Rows = 1
			.set_ColWidth(0, 1100)
			.set_ColWidth(1, 3800)
			.set_ColWidth(2, 800)
			.set_ColWidth(3, 3930)
			.set_TextMatrix(0, 0, "Código")
			.set_TextMatrix(0, 1, "Descrição")
			.set_TextMatrix(0, 2, "Valor")
			.set_TextMatrix(0, 3, "Referência")
			.set_ColAlignment(3, MSFlexGridLib.AlignmentSettings.flexAlignLeftCenter)
		End With
		Me.txtVlrTotal.Text = FormatNumber(0, 2, TriState.True)
	End Sub
	
	Private Sub cmdRemover_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdRemover.Click
		With Me.mfgItens
			If .RowSel > 0 Then
				If .Rows > 2 Then
					Call .RemoveItem(.RowSel)
				Else
					.Rows = 1
					.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightNever
				End If
			End If
		End With
		Call SomaGrid()
	End Sub
	
	Private Sub txtZona_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Enter
		With Me.txtZona
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtZona_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Leave
		With Me.txtZona
			.Text = VB6.Format(.Text, "000")
		End With
	End Sub
	
	Private Sub txtLivro_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Enter
		With Me.txtLivro
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtLivro_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Leave
		With Me.txtLivro
			.Text = VB6.Format(.Text, "00")
		End With
	End Sub
	
	Private Sub txtConta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Enter
		With Me.txtConta
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtConta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Leave
		With Me.txtConta
			.Text = VB6.Format(.Text, "000000")
		End With
	End Sub
	
	Private Sub txtZonaImp_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZonaImp.Enter
		With Me.txtZonaImp
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtZonaImp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZonaImp.Leave
		With Me.txtZonaImp
			.Text = VB6.Format(.Text, "000")
		End With
	End Sub
	
	Private Sub txtLivroImp_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivroImp.Enter
		With Me.txtLivroImp
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtLivroImp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivroImp.Leave
		With Me.txtLivroImp
			.Text = VB6.Format(.Text, "00")
		End With
	End Sub
	
	Private Sub txtContaImp_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtContaImp.Enter
		With Me.txtContaImp
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtContaImp_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtContaImp.Leave
		With Me.txtContaImp
			.Text = VB6.Format(.Text, "000000")
		End With
	End Sub
	
	'UPGRADE_WARNING: Event txtQtd.TextChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
	Private Sub txtQtd_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtQtd.TextChanged
		If Len(Me.txtQtd.Text) > 0 And IsNumeric(Me.txtQtd.Text) Then
			Me.txtTotMust.Text = VB6.Format(CDbl(Me.txtQtd.Text) * CDbl(Me.txtVlrTarifa.Text), "##,##0.00")
		Else
			Me.txtTotMust.Text = "0,00"
		End If
		Call SomaGrid()
	End Sub
	
	Private Sub txtQtd_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtQtd.Enter
		With Me.txtQtd
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtQtd_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtQtd.KeyPress
		Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
		If KeyAscii <> 8 And (KeyAscii < 48 Or KeyAscii > 57) Then
			KeyAscii = 0
		End If
		eventArgs.KeyChar = Chr(KeyAscii)
		If KeyAscii = 0 Then
			eventArgs.Handled = True
		End If
	End Sub
	
	Private Sub txtVlrItem_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtVlrItem.Enter
		With Me.txtVlrItem
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtVlrItem_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtVlrItem.KeyPress
		Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
		If KeyAscii <> 8 And (KeyAscii <> 44 Or (KeyAscii = 44 And InStr(1, Me.txtVlrItem.Text, ","))) And (KeyAscii < 48 Or KeyAscii > 57) Then
			KeyAscii = 0
		End If
		eventArgs.KeyChar = Chr(KeyAscii)
		If KeyAscii = 0 Then
			eventArgs.Handled = True
		End If
	End Sub
	
	Private Sub txtVlrItem_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtVlrItem.Leave
		With Me.txtVlrItem
			.Text = VB6.Format(.Text, "##,##0.00")
		End With
	End Sub
	
	Private Sub cmdBusca_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBusca.Click
		Me.txtTa.Text = ""
		Me.txtNome.Text = ""
		Me.txtQtd.Text = "0"
		Me.txtVlrTarifa.Text = "0,00000"
		Me.txtTotMust.Text = "0,00"
		Me.txtReferencia.Text = ""
		Me.txtVlrItem.Text = "0,00"
		Me.cmbCodigos.SelectedIndex = 0
		Me.mfgItens.Rows = 1
		Me.mfgItens.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightNever
		Me.txtVlrTotal.Text = "0,00"
		
		If Not carregaDados Then
			Call Me.txtZona.Focus()
			Call SetaStatusFrame((Me.fmeDatas), False)
			Call SetaStatusFrame((Me.fmeItens), False)
			Call SetaStatusFrame((Me.fmeMust), False)
		End If
	End Sub
	
	Private Function carregaDados() As Boolean
		Dim lstrSql As String
		Dim lrstConsulta As ADODB.Recordset
		Dim lblnErro As Boolean
		
		lrstConsulta = New ADODB.Recordset
		lblnErro = True
		
		If Len(Trim(Me.txtZona.Text)) > 0 And Len(Trim(Me.txtLivro.Text)) > 0 And Len(Trim(Me.txtConta.Text)) > 0 Then
			lstrSql = "SELECT nome, ta " & "FROM unidb " & "WHERE zona = '" & Me.txtZona.Text & "' AND livro = '" & Me.txtLivro.Text & "' AND conta = '" & Me.txtConta.Text & "'"
			Call Conectar(lstrSql, lrstConsulta)
			
			With lrstConsulta
				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"'
					Me.txtNome.Text = IIf(IsDbNull(.Fields("nome").value), "", .Fields("nome").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"'
					Me.txtTa.Text = Mid(Trim(IIf(IsDbNull(.Fields("ta").value), "01B1", .Fields("ta").value)), 3, 2)
					If .State = 1 Then Call .Close()
					Me.cmdGerar.Enabled = True
					Me.cmdCancelar.Enabled = True
					Call SetaStatusFrame((Me.fmeCabec), False)
					Call SetaStatusFrame((Me.fmeDatas), True)
					Call SetaStatusFrame((Me.fmeItens), True)
					Call SetaStatusFrame((Me.fmeMust), True)
					Call Me.txtQtd.Focus()
					
					Call CarregaNFAnterior(Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text)
					
				Else
					Call MsgBox("Unidade Consumidora não foi encontrada!", MsgBoxStyle.Information, gstrTituloMensagem)
					lblnErro = False
					If .State = 1 Then Call .Close()
				End If
			End With
			'UPGRADE_NOTE: Object lrstConsulta 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"'
			lrstConsulta = Nothing
		Else
			Call MsgBox("Por favor, informe a identificação do consumidor!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
			lblnErro = False
		End If
		
		carregaDados = lblnErro
	End Function
	
	Private Sub CarregaNFAnterior(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String)
		Dim lstrSql As String
		Dim lrstConsulta As ADODB.Recordset
		Dim lstrItensserv As String
		Dim lItensServ() As iItensServ
		Dim llngCountItem As Short
		Dim llngCountCmb As Short
		lrstConsulta = New ADODB.Recordset
		
		Me.txtVlrTarifa.Text = CStr(TarifaProporcional(Me.dtpLeitAnt.value, Me.dtpLeitAtual.value, "01BU011401", 3))
		
		lstrSql = "SELECT itensserv " & "  FROM nf " & " WHERE zona = '" & astrZona & "' " & "   AND livro = '" & astrLivro & "' " & "   AND conta = '" & astrConta & "' " & " ORDER BY RIGHT(mesano, 4) DESC, LEFT(mesano, 2) DESC " & " LIMIT 0,1"
		Call Conectar(lstrSql, lrstConsulta)
		
		With lrstConsulta
			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"'
				lstrItensserv = IIf(IsDbNull(.Fields("itensserv").value), "", .Fields("itensserv").value)
				lItensServ = BuscaItens(lstrItensserv)
				
				For llngCountItem = 0 To UBound(lItensServ)
					If lItensServ(llngCountItem).strCod = "0302010032" Then
						
						Me.txtQtd.Text = CStr(CShort(CDbl(lItensServ(llngCountItem).dblVlr))) '/ CDbl(Me.txtVlrTarifa.Text))
						
					ElseIf VB.Left(lItensServ(llngCountItem).strCod, 4) = "9030" Or VB.Left(lItensServ(llngCountItem).strCod, 4) = "9080" Or VB.Left(lItensServ(llngCountItem).strCod, 4) = "9070" Or VB.Left(lItensServ(llngCountItem).strCod, 4) = "9040" Or VB.Left(lItensServ(llngCountItem).strCod, 4) = "9050" Then 
						
						With Me.cmbCodigos
							For llngCountCmb = 0 To (.Items.Count - 1)
								If VB.Left(VB6.GetItemString(Me.cmbCodigos, llngCountCmb), 10) = lItensServ(llngCountItem).strCod Then
									With Me.mfgItens
										
										.Rows = .Rows + 1
										.set_TextMatrix(.Rows - 1, 0, lItensServ(llngCountItem).strCod)
										.set_TextMatrix(.Rows - 1, 1, Mid(VB6.GetItemString(Me.cmbCodigos, llngCountCmb), 14))
										.set_TextMatrix(.Rows - 1, 2, lItensServ(llngCountItem).dblVlr)
										.set_TextMatrix(.Rows - 1, 3, lItensServ(llngCountItem).strRef)
										.HighLight = MSFlexGridLib.HighLightSettings.flexHighlightAlways
										
									End With
								End If
							Next 
						End With
					End If
				Next 
			End If
			Call SomaGrid()
			If .State = 1 Then Call .Close()
			'UPGRADE_NOTE: Object lrstConsulta 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"'
			lrstConsulta = Nothing
		End With
	End Sub
	
	Private Function BuscaItens(ByVal astrItensServ As String) As iItensServ()
		Dim lItensServ() As iItensServ
		Dim lintCount As Short
		Dim lintP1 As Short
		Dim lintP2 As Short
		Dim lintP3 As Short
		Dim lintP4 As Short
		
		If Len(astrItensServ) > 0 Then
			lintP1 = 1
			lintP4 = InStr(lintP1, astrItensServ, ";")
			lintCount = 0
			
			While lintP1 < Len(astrItensServ) And lintP4 <> 0
				lintP2 = InStr(lintP1, astrItensServ, "?")
				lintP3 = InStr(lintP1, astrItensServ, "$")
				lintP4 = InStr(lintP1, astrItensServ, ";")
				
				ReDim Preserve lItensServ(lintCount)
				
				lItensServ(lintCount).strCod = Mid(astrItensServ, lintP1, lintP2 - lintP1)
				
				If lintP3 <> 0 And lintP3 < lintP4 Then
					lItensServ(lintCount).dblVlr = Replace(Mid(astrItensServ, lintP2 + 1, lintP3 - lintP2 - 1), ".", ",")
					lItensServ(lintCount).strRef = Mid(astrItensServ, lintP3 + 1, lintP4 - lintP3 - 1)
				Else
					lItensServ(lintCount).dblVlr = Replace(Mid(astrItensServ, lintP2 + 1, lintP4 - lintP2 - 1), ".", ",")
					lItensServ(lintCount).strRef = ""
				End If
				
				lintCount = lintCount + 1
				lintP1 = lintP4 + 1
			End While
		End If
		
		BuscaItens = VB6.CopyArray(lItensServ)
		
	End Function
	
	Private Sub CarregaCmbCodigos()
		Dim lstrSql As String
		Dim lstrCodigo As String
		Dim lstrDescricao As String
		Dim lstrCondicao As String
		Dim lrstConsulta As ADODB.Recordset
		
		lrstConsulta = New ADODB.Recordset
		Me.cmbCodigos.Items.Clear()
		
		lstrSql = "SELECT DISTINCT num, descri " & "FROM codigos " & "WHERE ((LEFT(TRIM(num),4)= '9030' AND num <> '9030000000') " & "OR ((LEFT(TRIM(num),4)= '9080' AND num <> '9080000000') OR (LEFT(TRIM(num),4)= '9070' AND num <> '9070000000')) " & "OR ((LEFT(TRIM(num),4)= '9040' AND num <> '9040000000') OR (LEFT(TRIM(num),4)= '9050' AND num <> '9050000000'))) " & "ORDER BY num ASC "
		Call Conectar(lstrSql, lrstConsulta)
		
		If lrstConsulta.RecordCount > 0 Then
			While Not lrstConsulta.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"'
				lstrCodigo = IIf(IsDbNull(lrstConsulta.Fields("Num").Value), "0000000000", lrstConsulta.Fields("Num").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"'
				lstrDescricao = IIf(IsDbNull(lrstConsulta.Fields("descri").Value), "", lrstConsulta.Fields("descri").Value)
				Call Me.cmbCodigos.Items.Add(lstrCodigo & " - " & lstrDescricao)
				Call lrstConsulta.MoveNext()
			End While
		Else
			Call Me.cmbCodigos.Items.Add("0000000000 - Nenhum")
		End If
		If lrstConsulta.State = 1 Then Call lrstConsulta.Close()
		
		Me.cmbCodigos.SelectedIndex = 0
		'UPGRADE_NOTE: Object lrstConsulta 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"'
		lrstConsulta = Nothing
	End Sub
	
	Private Sub SomaGrid()
		Dim llngLinha As Integer
		
		Me.txtVlrTotal.Text = "0,00"
		With Me.mfgItens
			If .Rows > 1 Then
				For llngLinha = 1 To .Rows - 1
					If VB.Left(.get_TextMatrix(llngLinha, 0), 4) = "9070" And .get_TextMatrix(llngLinha, 0) <> "9070000088" Then
						Me.txtVlrTotal.Text = VB6.Format(CDbl(Me.txtVlrTotal.Text) - CDbl(.get_TextMatrix(llngLinha, 2)), "##,##0.00")
					Else
						Me.txtVlrTotal.Text = VB6.Format(CDbl(Me.txtVlrTotal.Text) + CDbl(.get_TextMatrix(llngLinha, 2)), "##,##0.00")
					End If
				Next llngLinha
			End If
		End With
		Me.txtVlrTotal.Text = VB6.Format(CDbl(Me.txtVlrTotal.Text) + CDbl(Me.txtTotMust.Text), "##,##0.00")
	End Sub
	
	Private Sub GerarNF()
		Dim lstrSql As String
		Dim lrstConsulta As ADODB.Recordset
		Dim lrstNF As ADODB.Recordset
		Dim lblnVerNumNf As Boolean
		Dim ldblNumNf As Double
		Dim ldblNumNSU As Double
		Dim lstrClasse As String
		'Dim lstrDtVenc      As String
		Dim llngConsId As Integer
		Dim llngUnidId As Integer
		Dim lstrTipoUC As String
		Dim lstrTa As String
		Dim lstrFase As String
		Dim lstrTensao As String
		Dim lstrMedidor As String
		Dim ldblConst As Double
		Dim lstrRota As String
		Dim lstrBanco As String
		Dim lstrNmBanco As String
		Dim lstrMesAno As String
		Dim lstrAgrupa As String
		Dim lstrCpfCnpj As String
		Dim lstrItensserv As String
		Dim lstrItensImp As String
		Dim lstrCodBarra As String
		Dim lstrDvCodBarra As String
		Dim lstrHash As String
		
		lrstConsulta = New ADODB.Recordset
		lrstNF = New ADODB.Recordset
		
		
		lstrMesAno = VB6.Format(Me.dtpMesAno.value, "mm/yyyy")
		
		lstrSql = "SELECT clas, diavenc, rota, cons_id, unid_id, banco, tipouc, ta, fase, tensao, num, const, agrupa, cpf_cnpj, " & "(SELECT nmbco FROM bancos WHERE bancos.ban_id = unidb.banco) nmbanco " & "FROM unidb " & "WHERE zona = '" & Me.txtZona.Text & "' AND livro = '" & Me.txtLivro.Text & "' AND conta = '" & Me.txtConta.Text & "'"
		Call Conectar(lstrSql, lrstConsulta)
		
		With lrstConsulta
			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"'
				lstrClasse = IIf(IsDbNull(.Fields("clas").value), "0000", .Fields("clas").value)
				'lstrDtVenc = Format(DateSerial(Year(Me.dtpMesAno.Value), Month(Me.dtpMesAno.Value), IIf(IsNull(.Fields("diavenc").Value), Day(Now), .Fields("diavenc").Value)), "yyyy-MM-dd")
				'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"'
				lstrRota = IIf(IsDbNull(.Fields("rota").value), "", .Fields("rota").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 = 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"'
				lstrBanco = IIf(IsDbNull(.Fields("banco").value), "000", .Fields("banco").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"'
				lstrNmBanco = IIf(IsDbNull(.Fields("nmbanco").value), "", .Fields("nmbanco").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"'
				lstrTipoUC = IIf(IsDbNull(.Fields("tipouc").value), "", .Fields("tipouc").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 = IIf(IsDbNull(.Fields("ta").value), "", .Fields("ta").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 = IIf(IsDbNull(.Fields("fase").value), "", .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 = IIf(IsDbNull(.Fields("tensao").value), "", .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"'
				lstrMedidor = IIf(IsDbNull(.Fields("num").value), "", .Fields("num").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"'
				ldblConst = IIf(IsDbNull(.Fields("const").value), 1, .Fields("const").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"'
				lstrAgrupa = IIf(IsDbNull(.Fields("agrupa").value), "", .Fields("agrupa").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"'
				lstrCpfCnpj = IIf(IsDbNull(.Fields("cpf_cnpj").value), "", .Fields("cpf_cnpj").value)
				
				Call MontaItensNF(lstrItensserv, lstrItensImp)
				
				'Verifica se existe a fatura em transição
				lstrSql = "SELECT numnf, nsu, itensserv FROM nftransicao " & "WHERE zona = '" & Me.txtZona.Text & "' " & "  AND livro = '" & Me.txtLivro.Text & "' " & "  AND conta = '" & Me.txtConta.Text & "' " & "  AND mesano = '" & lstrMesAno & "'" & "  AND cons_id = " & llngConsId & " " & "  AND unid_id = " & llngUnidId
				Call Conectar(lstrSql, lrstNF)
				
				If lrstNF.RecordCount < 1 Then
					Call lrstNF.Close()
					
					'Busca o último número da NF na tabela config
					ldblNumNf = Val(LeConfig("ULTIMONRFISCAL")) + 1
					'Busca o último número de NSU na tabela config (SÓ P/ SANTA CATARINA)
					If LeConfig("EMPRESA_UF") = "SC" Then ldblNumNSU = CDbl(LeConfig("ULTIMONRNSU")) + 1
					
					'Verifica se este número já esta gravado para outra zona, livro, conta
					lblnVerNumNf = False
					While Not lblnVerNumNf
						lstrSql = "SELECT numnf FROM nftransicao " & "WHERE numnf = " & ldblNumNf & " " & "  AND mesano = '" & lstrMesAno & "'"
						Call Conectar(lstrSql, lrstNF)
						
						If lrstNF.RecordCount < 1 Then
							lblnVerNumNf = True
						Else
							ldblNumNf = ldblNumNf + 1
						End If
						
						Call lrstNF.Close()
						System.Windows.Forms.Application.DoEvents()
					End While
					
					'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"'
					lstrHash = GeraHash(lstrCpfCnpj, ldblNumNf, CDbl(Me.txtVlrTotal.Text), 0, 0)
					Call MontaCodBarras(ldblNumNf, lstrMesAno, CDbl(Me.txtVlrTotal.Text), Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, lstrCodBarra, lstrDvCodBarra)
					
					lstrSql = "INSERT INTO nftransicao SET " & "numnf         = " & ldblNumNf & ", " & "codclas       = '" & lstrClasse & "', " & "mesano        = '" & lstrMesAno & "', " & "mesano_ref   =  " & CInt(VB.Right(lstrMesAno, 4) & VB.Left(lstrMesAno, 2)) & ", " & "datavenc      = '" & VB6.Format(Me.dtpVenc.value, "yyyy-MM-dd") & "', " & "dataleit      = '" & VB6.Format(Me.dtpLeitAtual.value, "yyyy-MM-dd") & "', " & "dataapr       = '" & VB6.Format(Me.dtpApres.value, "yyyy-MM-dd") & "', " & "dataem        = '" & VB6.Format(Now, "yyyy-MM-dd") & "', " & "dataleitant   = '" & VB6.Format(Me.dtpLeitAnt.value, "yyyy-MM-dd") & "', " & "datapag       = '0000-00-00', " & "codhash       = '" & lstrHash & "', " & "datast        = '0000-00-00', " & "flgst         = '', " & "valortot      = '" & Replace(Replace(Me.txtVlrTotal.Text, ".", ""), ",", ".") & "', "
					lstrSql = lstrSql & "zona          = '" & Me.txtZona.Text & "', " & "livro         = '" & Me.txtLivro.Text & "', " & "conta         = '" & Me.txtConta.Text & "', " & "rota          = '" & lstrRota & "', " & "rota_quatro   = '" & VB.Left(lstrRota, 4) & "', " & "caderno       = " & VB.Right(VB.Left(lstrRota, 4), 2) & ", " & "caderno_sequencia = " & VB.Right(lstrRota, 4) & ", " & "cons_id       = '" & llngConsId & "', " & "unid_id       = '" & llngUnidId & "', " & "dataproxleit  = '" & VB6.Format(Me.dtpProxLeit.value, "yyyy-MM-dd") & "', " & "banarrec      = '" & lstrBanco & "', " & "banident      = '" & lstrNmBanco & "', " & "flgmedfat     = 'N', " & "tipouc        = '" & lstrTipoUC & "', " & "cfop          = '5.949', " & "itensserv     = '" & lstrItensserv & "', "
					'UPGRADE_WARNING: DateDiff behavior may be different. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B38EC3F-686D-4B2E-B5A5-9E8E7A762E32"'
					lstrSql = lstrSql & "ta            = '" & lstrTa & "', " & "grupo         = '" & Mid(lstrTa, 3, 1) & "', " & "fase          = '" & lstrFase & "', " & "tensao        = '" & lstrTensao & "', " & "num_med       = '" & lstrMedidor & "', " & "const_med     = '" & Replace(CStr(ldblConst), ",", ".") & "', " & "motivocanc    = NULL, " & "banco_fatur   = '" & VB6.Format(lstrBanco, "000") & "', " & "social        = NULL, " & "multa         = NULL, " & "dataprazo     = '0000-00-00', " & "dias          = '" & DateDiff(Microsoft.VisualBasic.DateInterval.Day, Me.dtpLeitAnt.value, Me.dtpLeitAtual.value) & "', " & "valorliq      = '" & Replace(Replace(Me.txtVlrTotal.Text, ".", ""), ",", ".") & "', " & "nsu           = " & IIf(ldblNumNSU < 1, "NULL", "'" & ldblNumNSU & "'") & "," & "codbarra      = '" & lstrCodBarra & "', " & "dvcodbarra    = '" & lstrDvCodBarra & "', " & "agrupa        = '" & lstrAgrupa & "', " & "itensImp      = '" & lstrItensImp & "', " & "sgdenvio      = 'P', usina = 1"
					Call Executar(lstrSql)
					
					'Grava o último número da NF na tabela config
					Call GravaConfig("ULTIMONRFISCAL", Trim(Str(ldblNumNf)))
					'Grava o último número do NSU na tabela config (SOMENTE P/ SANTA CATARINA)
					If LeConfig("EMPRESA_UF") = "SC" Then Call GravaConfig("ULTIMONRNSU", Trim(Str(ldblNumNSU)))
					
				Else
					
					'Update da nftransicao
					'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(lrstNF.Fields("numnf").value), 0, lrstNF.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"'
					ldblNumNSU = IIf(IsDbNull(lrstNF.Fields("nsu").value), 0, lrstNF.Fields("nsu").value)
					If Trim(lstrItensserv) = "" 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"'
						lstrItensserv = IIf(IsDbNull(lrstNF.Fields("itensserv").value), "", lrstNF.Fields("itensserv").value)
					End If
					If LeConfig("EMPRESA_UF") = "SC" And ldblNumNSU < 1 Then ldblNumNSU = CDbl(LeConfig("ULTIMONRNSU")) + 1
					
					'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"'
					lstrHash = GeraHash(lstrCpfCnpj, ldblNumNf, CDbl(Me.txtVlrTotal.Text), 0, 0)
					Call MontaCodBarras(ldblNumNf, lstrMesAno, CDbl(Me.txtVlrTotal.Text), Me.txtZona.Text, Me.txtLivro.Text, Me.txtConta.Text, lstrCodBarra, lstrDvCodBarra)
					
					lstrSql = "UPDATE nftransicao SET " & "codclas       = '" & lstrClasse & "', " & "datavenc      = '" & VB6.Format(Me.dtpVenc.value, "yyyy-MM-dd") & "', " & "dataleit      = '" & VB6.Format(Me.dtpLeitAtual.value, "yyyy-MM-dd") & "', " & "dataapr       = '" & VB6.Format(Me.dtpApres.value, "yyyy-MM-dd") & "', " & "dataem        = '" & VB6.Format(Now, "yyyy-MM-dd") & "', " & "dataleitant   = '" & VB6.Format(Me.dtpLeitAnt.value, "yyyy-MM-dd") & "', " & "datapag       = '0000-00-00', " & "codhash       = '" & lstrHash & "', " & "datast        = '0000-00-00', " & "flgst         = '', " & "valortot      = '" & Replace(Replace(Me.txtVlrTotal.Text, ".", ""), ",", ".") & "', "
					lstrSql = lstrSql & "zona          = '" & Me.txtZona.Text & "', " & "livro         = '" & Me.txtLivro.Text & "', " & "conta         = '" & Me.txtConta.Text & "', " & "rota          = '" & lstrRota & "', " & "rota_quatro   = '" & VB.Left(lstrRota, 4) & "', " & "caderno       = " & VB.Right(VB.Left(lstrRota, 4), 2) & ", " & "caderno_sequencia = " & VB.Right(lstrRota, 4) & ", " & "cons_id       = '" & llngConsId & "', " & "unid_id       = '" & llngUnidId & "', " & "dataproxleit  = '" & VB6.Format(Me.dtpProxLeit.value, "yyyy-MM-dd") & "', " & "banarrec      = '" & lstrBanco & "', " & "banident      = '" & lstrNmBanco & "', " & "flgmedfat     = 'N', " & "tipouc        = '" & lstrTipoUC & "', " & "cfop          = '5.949', " & "itensserv     = '" & lstrItensserv & "', "
					'UPGRADE_WARNING: DateDiff behavior may be different. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B38EC3F-686D-4B2E-B5A5-9E8E7A762E32"'
					lstrSql = lstrSql & "ta            = '" & lstrTa & "', " & "grupo         = '" & Mid(lstrTa, 3, 1) & "', " & "fase          = '" & lstrFase & "', " & "tensao        = '" & lstrTensao & "', " & "num_med       = '" & lstrMedidor & "', " & "const_med     = '" & Replace(CStr(ldblConst), ",", ".") & "', " & "motivocanc    = NULL, " & "banco_fatur   = '" & VB6.Format(lstrBanco, "000") & "', " & "social        = NULL, " & "multa         = NULL, " & "dataprazo     = '0000-00-00', " & "dias          = '" & DateDiff(Microsoft.VisualBasic.DateInterval.Day, Me.dtpLeitAnt.value, Me.dtpLeitAtual.value) & "', " & "valorliq      = '" & Replace(Replace(Me.txtVlrTotal.Text, ".", ""), ",", ".") & "', " & "nsu           = " & IIf(ldblNumNSU < 1, "NULL", "'" & ldblNumNSU & "'") & "," & "codbarra      = '" & lstrCodBarra & "', " & "dvcodbarra    = '" & lstrDvCodBarra & "', " & "agrupa        = '" & lstrAgrupa & "', " & "itensImp      = '" & lstrItensImp & "', " & "sgdenvio      = 'P', usina = 1 "
					lstrSql = lstrSql & "WHERE numnf = " & ldblNumNf & " " & "  AND mesano = '" & lstrMesAno & "'"
					
					Call Executar(lstrSql)
					
					If lrstNF.State = 1 Then Call lrstNF.Close()
				End If
				
				Call MsgBox("A seguinte Nota Fiscal foi gerada: " & ldblNumNf, MsgBoxStyle.Information, gstrTituloMensagem)
				
			End If
		End With
	End Sub
	
	Private Function GeraHash(ByVal astrCpfCnpj As String, ByVal adblNumNf As Double, ByVal adblVlrTot As Double, ByVal adblBaseIcms As Double, ByVal adblVlrIcms As Double) As Object
		Dim lstrHash As String
		Dim lstrSql As String
		Dim lrstConsulta As ADODB.Recordset
		lrstConsulta = New ADODB.Recordset
		
		lstrHash = PreparaCampo(astrCpfCnpj, NUMERICO, 14, CStr(0)) & PreparaCampo(Str(adblNumNf), NUMERICO, 9, "0") & PreparaCampo(Str(CDbl(Replace(Replace(VB6.Format(Arredondar(adblVlrTot, 2), "Standard"), ",", ""), ".", ""))), NUMERICO, 12, "0") & PreparaCampo(Str(CDbl(Replace(Replace(VB6.Format(Arredondar(adblBaseIcms, 2), "Standard"), ",", ""), ".", ""))), NUMERICO, 12, "0") & PreparaCampo(Str(CDbl(Replace(Replace(VB6.Format(Arredondar(adblVlrIcms, 2), "Standard"), ",", ""), ".", ""))), NUMERICO, 12, "0")
		
		lstrSql = "SELECT CONVERT(MD5('" & lstrHash & "') USING latin1) as `hash`"
		Call Conectar(lstrSql, lrstConsulta)
		If lrstConsulta.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"'
			lstrHash = UCase(Trim(IIf(IsDbNull(lrstConsulta.Fields("hash").value), "", lrstConsulta.Fields("hash").value)))
		Else
			lstrHash = ""
		End If
		If lrstConsulta.State = 1 Then lrstConsulta.Close()
		'UPGRADE_NOTE: Object lrstConsulta 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"'
		lrstConsulta = Nothing
		
		'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 = lstrHash
	End Function
	
	Private Sub MontaItensNF(ByRef astrItensServ As String, ByRef astrItensImp As String)
		Dim llngCount As Integer
		Dim lstrItensImp As String
		Dim lstrItensserv As String
		
		With Me.mfgItens
			lstrItensImp = ""
			lstrItensserv = ""
			For llngCount = 1 To (.Rows - 1)
				If Len(lstrItensImp) > 0 Then lstrItensImp = lstrItensImp & vbCrLf
				lstrItensImp = lstrItensImp & VB.Left(.get_TextMatrix(llngCount, 1) & .get_TextMatrix(llngCount, 3) & New String(" ", 50), 50) & VB.Right(New String(" ", 15) & VB6.Format(.get_TextMatrix(llngCount, 2), "Standard"), 15)
				lstrItensserv = lstrItensserv & VB.Right(New String("0", 10) & .get_TextMatrix(llngCount, 0), 10) & "?" & Replace(Replace(.get_TextMatrix(llngCount, 2), ".", ""), ",", ".") & IIf(Len(Trim(.get_TextMatrix(llngCount, 3))) > 0, "$" & .get_TextMatrix(llngCount, 3), "") & ";"
				If VB.Right(New String("0", 10) & .get_TextMatrix(llngCount, 0), 10) = "0302020032" Then
					lstrItensserv = lstrItensserv & "0302010032?" & Replace(Replace(Me.txtQtd.Text, ".", ""), ",", ".") & ";" 'quantidade faturada
				End If
			Next 
		End With
		
		astrItensServ = lstrItensserv
		astrItensImp = lstrItensImp
	End Sub
	
	Public Sub ImpFaturaUsina(ByVal astrMesAno As String, ByVal adblNumNf As Integer, Optional ByVal ablnNFTransicao As Boolean = False)
		Dim lstrSql As String
		Dim lrstConsulta As New ADODB.Recordset
		Dim llngCount As Integer
		
		lstrSql = "DELETE FROM temp_fatura"
		Call Executar(lstrSql)
		
		lstrSql = "INSERT INTO temp_fatura( segvia, nomemaquina, " & vbCrLf & "numnf            , cfop                    , zona            , livro             , " & vbCrLf & "conta            , rota                    , agenc           , cc                , " & vbCrLf & "codclas          , datavenc                , banco_fatur     , banident          , " & vbCrLf & "mesano           , NomeCons                , RefCons         , Rua               , " & vbCrLf & "complement       , cep                     , Bairro          , cidade            , " & vbCrLf & "uf               , cpf_cnpj                , rg_ie           , dataemissao       , " & vbCrLf & "dataapr          , dataproxleit            , dataleit        , dataleitant       , " & vbCrLf & "num_med          , const_med               , fase            , ta                , " & vbCrLf & "tensao           , codhash                 , leit            , descclasse        , " & vbCrLf & "leituraant       , end_entrega             , bai_entrega     , cid_entrega       , " & vbCrLf & "cep_entrega      , uf_entrega              , num_entrega     , entrega           , " & vbCrLf & "valortot         , valorliq                , consfaturado    , conslido          , " & vbCrLf & "valorconsumo     , baseicms                , aliqicms        , vlricms           , " & vbCrLf & "baseicms1        , aliqicms1               , vlricms1        , basepis           , " & vbCrLf & "aliqpis          , vlrpis                  , basecofins      , aliqcofins        , " & vbCrLf & "vlrcofins        , dec_meta                , dec_rea         , fec_meta          , " & vbCrLf & "fec_rea          , dic_meta                , dic_rea         , fic_meta          , " & vbCrLf & "fic_rea          , dmic                    , refindicador    , vlrconsutrib      , " & vbCrLf & "baseicmstotal    , vlricmstotal            , ret_irpj        , ret_pis           , " & vbCrLf & "ret_csll         , ret_cofins              , comp_energia    , comp_transmissao  , " & vbCrLf & "comp_distribuicao, comp_encargos_setoriais , mensagem        , itensImp          , " & vbCrLf & "ocorrencia       , codbarra                , dvcodbarra )"
		
		lstrSql = lstrSql & " (SELECT 0, """ & Trim(gstrNmEstacao) & """, " & vbCrLf & "f.numnf         , f.cfop          , f.zona                                 , f.livro         , " & vbCrLf & "f.conta         , u.rota          , u.agenc                                , u.cc            , " & vbCrLf & "f.codclas       , f.datavenc      , f.banco_fatur                          , f.banident      , " & vbCrLf & "f.mesano        , u.nome NomeCons , u.nome rc                              , c.end           , " & vbCrLf & "u.complement    , c.cep           , c.bairro                               , c.cidade        , " & vbCrLf & "c.uf            , u.cpf_cnpj      , if(length(trim(u.insc))>0,u.insc,u.rg) , f.dataem        , " & vbCrLf & "f.dataapr       , f.dataproxleit  , f.dataleit                             , f.dataleitant   , " & vbCrLf & "f.num_med       , f.const_med     , f.fase                                 , u.ta            , " & vbCrLf & "u.tensao        , f.codhash       , u.leit                                 , l.descricao     , " & vbCrLf & "u.ultleit       , u.end_entrega   , u.bai_entrega                          , u.cid_entrega   , " & vbCrLf & "u.cep_entrega   , u.uf_entrega    , u.num_entrega                          , u.entrega       , " & vbCrLf & "f.valortot      , f.valorliq      , " & vbCrLf
		'consfat
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""030201009"") consfat, "
		'conslido
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""030201008"") conslido, "
		'valorconsumo
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""030202009"") valorconsumo, "
		'baseicms
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030001"") baseicms, "
		'aliqicms
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030002"") aliqicms, "
		'icms
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030009"") icms, "
		'baseicms1
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030003"") baseicms1, "
		'aliqicms1
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030013"") aliqicms1, "
		'icms1
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030010"") vlricms1, "
		'basepis
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302020033"") basepis, "
		'aliqpis
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302990303"") aliqpis, "
		'valor pis
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302020029"") pis, "
		'basecofins
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302020034"") basecofins, "
		'aliqcofins
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302990304"") aliqcofins, "
		'valor cofins
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302020030"") cofins, "
		'dec_meta
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080101"") dec_meta, "
		'dec_rea
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080001"") dec_rea, "
		'fec_meta
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080102"") fec_meta, "
		'fec_rea
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080002"") fec_rea, "
		'dic_meta
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080103"") dic_meta, "
		'dic_rea
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080003"") dic_rea, "
		'fic_meta
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080104"") fic_meta, "
		'fic_rea
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080004"") fic_rea, "
		'dmic
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302080105"") dmic, "
		'refindicador
		lstrSql = lstrSql & "buscarefitem(f.itensserv,""0302080099"") refindicador, "
		'valor total com tributos
		lstrSql = lstrSql & "(buscavlritem(f.itensserv,""030202009"") + " & "buscavlritem(f.itensserv,""0302030009"") + " & "buscavlritem(f.itensserv,""0302020029"") + " & "buscavlritem(f.itensserv,""0302020030"")) totnftrib, "
		'baseicmstotal
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030015"") baseicmstotal, "
		'vlricmstotal
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302030014"") vlricmstotal, "
		'ret_irpj
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""9090000004"") ret_irpj, "
		'ret_pis
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""9090000001"") ret_pis, "
		'ret_csll
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""9090000003"") ret_csll, "
		'ret_cofins
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""9090000002"") ret_cofins, "
		'comp_energia
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302090001"") comp_energia, "
		'comp_transmissao
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302090002"") comp_transmissao, "
		'comp_distribuicao
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302090003"") comp_distribuicao, "
		'comp_encargos_setoriais
		lstrSql = lstrSql & "buscavlritem(f.itensserv,""0302090004"") comp_encargos_setoriais, "
		If LeConfig("EMPRESA_UF") = "SC" Then
			'mensagem - NSU
			lstrSql = lstrSql & " if(f.nsu>0,concat('NSU: ', right(concat('0000000000', f.nsu, '" & vbCrLf & "'),10)),'') nsu, "
		Else
			lstrSql = lstrSql & " '' nsu, "
		End If
		lstrSql = lstrSql & "f.itensImp itensImp, buscavlritem(f.itensserv,""90410000"") ocorrencia, f.codbarra, f.dvcodbarra "
		
		lstrSql = lstrSql & " FROM " & IIf(ablnNFTransicao, "nftransicao", "nf") & " f, consum c, unidb u, classe l"
		lstrSql = lstrSql & " WHERE  u.cons_id = c.consreg"
		lstrSql = lstrSql & "   AND f.zona = u.zona "
		lstrSql = lstrSql & "   AND f.livro = u.livro "
		lstrSql = lstrSql & "   AND f.conta = u.conta"
		lstrSql = lstrSql & "   AND l.codigo = f.codclas"
		lstrSql = lstrSql & "   AND u.cons_id = c.consreg"
		lstrSql = lstrSql & "   AND u.cons_id = c.consreg"
		lstrSql = lstrSql & "   AND f.numnf = '" & adblNumNf & "'"
		lstrSql = lstrSql & "   AND f.mesano = '" & astrMesAno & "'"
		lstrSql = lstrSql & " )"
		
		Call Executar(lstrSql)
		
		'DIAS DE CONSUMO
		lstrSql = "UPDATE temp_fatura SET " & "temp_fatura.diasconsumo = datediff(temp_fatura.dataleit,temp_fatura.dataleitant);  "
		Call Executar(lstrSql)
		
		'VALOR DIÁRIO
		lstrSql = "UPDATE temp_fatura SET " & "temp_fatura.vlrdiario = temp_fatura.valorconsumo / temp_fatura.diasconsumo;  "
		Call Executar(lstrSql)
		
		'CONSUMO DIÁRIO
		lstrSql = "UPDATE temp_fatura SET " & "temp_fatura.mediaconsumodiario = consfaturado / diasconsumo;   "
		Call Executar(lstrSql)
		
		'MAIOR CONSUMO
		lstrSql = "UPDATE temp_fatura, `consumos` SET " & "temp_fatura.maiorconsumo = GREATEST(consumos.consumo0, " & "consumos.consumo1, " & "consumos.consumo2, " & "consumos.consumo3, " & "consumos.consumo4, " & "consumos.consumo5, " & "consumos.consumo6, " & "consumos.consumo7, " & "consumos.consumo8, " & "consumos.consumo9, " & "consumos.consumo10, " & "consumos.consumo11, " & "temp_fatura.consfaturado) " & "WHERE consumos.zona = temp_fatura.zona" & "  AND consumos.livro = temp_fatura.livro" & "  AND consumos.conta = temp_fatura.conta;"
		Call Executar(lstrSql)
		
		lstrSql = "UPDATE temp_fatura SET " & "temp_fatura.mesmaiorconsumo = getmesconsumo(temp_fatura.zona, " & "temp_fatura.livro, " & "temp_fatura.conta, " & "temp_fatura.maiorconsumo) "
		Call Executar(lstrSql)
		
		'MENOR CONSUMO
		lstrSql = "UPDATE temp_fatura, consumos SET " & "temp_fatura.menorconsumo = LEAST(consumos.consumo0, " & "consumos.consumo1, " & "consumos.consumo2, " & "consumos.consumo3, " & "consumos.consumo4, " & "consumos.consumo5, " & "consumos.consumo6, " & "consumos.consumo7, " & "consumos.consumo8, " & "consumos.consumo9, " & "consumos.consumo10, " & "consumos.consumo11, " & "temp_fatura.consfaturado) " & "WHERE consumos.zona = temp_fatura.zona" & "  AND consumos.livro = temp_fatura.livro" & "  AND consumos.conta = temp_fatura.conta;"
		Call Executar(lstrSql)
		
		lstrSql = "UPDATE temp_fatura SET " & "temp_fatura.mesmenorconsumo = getMesConsumo(temp_fatura.zona, " & "temp_fatura.livro, " & "temp_fatura.conta, " & "temp_fatura.menorconsumo) "
		Call Executar(lstrSql)
		
		'MEDIA DE CONSUMOS
		lstrSql = "UPDATE temp_fatura, consumos SET " & "temp_fatura.mediaconsumo3meses = (consumos.consumo11 + " & "consumos.consumo10 + " & "consumos.consumo9)/3 " & "WHERE consumos.zona = temp_fatura.zona " & "  AND consumos.livro = temp_fatura.livro " & "  AND consumos.conta = temp_fatura.conta; "
		Call Executar(lstrSql)
		
		'FATURAS PENDENTES
		For llngCount = 0 To 11
			lstrSql = "UPDATE temp_fatura, `consumos` SET " & "temp_fatura.valorpend = temp_fatura.valorpend + consumos.valor" & llngCount & ", " & "temp_fatura.totalpend = temp_fatura.totalpend + 1 " & "WHERE (consumos.datapag" & llngCount & " IS NULL or consumos.datapag" & llngCount & " = '0000-00-00') " & "  AND consumos.mesano" & llngCount & " IS NOT NULL " & "  AND temp_fatura.zona = consumos.zona " & "  AND temp_fatura.livro = consumos.livro " & "  AND temp_fatura.conta = consumos.conta; "
			Call Executar(lstrSql)
		Next llngCount
		
		'MENSAGENS
		lstrSql = "UPDATE temp_fatura SET temp_fatura.mensagem = concat(temp_fatura.mensagem,'" & LeConfig("FATURA_MENSAGEM") & "');"
		Call Executar(lstrSql)
		
		'LEITURAS
		lstrSql = "UPDATE temp_fatura, leitmensal SET "
		lstrSql = lstrSql & "temp_fatura.leituraant             = leitmensal.leit_ant + 0 , "
		lstrSql = lstrSql & "temp_fatura.leit                   = leitmensal.leit_atual + 0 , "
		lstrSql = lstrSql & "temp_fatura.leitura_kvarh_anterior = leitmensal.kvarh, "
		lstrSql = lstrSql & "temp_fatura.leitura_kvarh_atual    = leitmensal.kvarhatual, "
		lstrSql = lstrSql & "temp_fatura.consumo_kvarh          = leitmensal.consumokvarh, "
		lstrSql = lstrSql & "temp_fatura.fp                     = leitmensal.fp "
		lstrSql = lstrSql & "WHERE CONCAT(MID(leitmensal.dt_faturamento, 6, 2), ""/"", YEAR(leitmensal.dt_faturamento)) = temp_fatura.mesano "
		lstrSql = lstrSql & "AND temp_fatura.zona = leitmensal.zona "
		lstrSql = lstrSql & "AND temp_fatura.livro = leitmensal.livro "
		lstrSql = lstrSql & "AND temp_fatura.conta = leitmensal.conta "
		Call Executar(lstrSql)
		
		'CONJUNTO (INDICADORES DE CONTINUIDADE)
		lstrSql = "UPDATE temp_fatura t, unidb u, conjunto c SET "
		lstrSql = lstrSql & "t.conjunto = c.nome "
		lstrSql = lstrSql & "WHERE t.zona     = u.zona "
		lstrSql = lstrSql & "AND   t.livro    = u.livro "
		lstrSql = lstrSql & "AND   t.conta    = u.conta "
		lstrSql = lstrSql & "AND   u.circuito = c.id_conjunto "
		Call Executar(lstrSql)
		
		'IMPRESSAO
		With FrmAtPrincipal.cr
			.ReportFileName = My.Application.Info.DirectoryPath & "\" & LeConfig("DIR_RPT") & "FaturaEflulUsina.rpt"
			.DiscardSavedData = True
			.WindowState = Crystal.WindowStateConstants.crptMaximized
			.WindowControlBox = True
			.WindowControls = True
			.WindowShowPrintSetupBtn = True
			.WindowShowCloseBtn = True
			.WindowShowSearchBtn = True
			.WindowTitle = "Impressão de Faturas"
			.Destination = Crystal.DestinationConstants.crptToWindow
			.SelectionFormula = "TRIM({temp_fatura.nomemaquina}) = """ & Trim(gstrNmEstacao) & """"
			.Action = 0
		End With
		
		With FrmAtPrincipal.cr
			.ReportFileName = My.Application.Info.DirectoryPath & "\" & LeConfig("DIR_RPT") & LeConfig("FATURA_MODELO_GRUPOB_VERSO")
			.DiscardSavedData = True
			.WindowState = Crystal.WindowStateConstants.crptMaximized
			.WindowControlBox = True
			.WindowControls = True
			.WindowShowPrintSetupBtn = True
			.WindowShowCloseBtn = True
			.WindowShowSearchBtn = True
			.SelectionFormula = "TRIM({temp_fatura.nomemaquina}) = """ & Trim(gstrNmEstacao) & """"
			.WindowTitle = "Impressão de Faturas Verso"
			.Destination = Crystal.DestinationConstants.crptToWindow
			.Action = 0
		End With
		
	End Sub
End Class