Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Friend Class frmImportarLeitGrupoA
	Inherits System.Windows.Forms.Form
	
	Private Sub cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click
		Me.Close()
	End Sub
	
	Private Sub cmdImportar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImportar.Click
		Call ImportaLeituras()
	End Sub
	
	Private Sub cmdSalvarArq_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSalvarArq.Click
		Me.dialArqOpen.ShowDialog()
		Me.txtDir.Text = Me.dialArqOpen.FileName
	End Sub
	
	Private Sub ImportaLeituras()
		Dim strSql As String
		Dim rsConsulta As New ADODB.Recordset
		Dim strZona As String
		Dim strLivro As String
		Dim strConta As String
		Dim strNome As String
		Dim strCons_id As String
		Dim strUnid_id As String
		Dim strTa As String
		
		Dim intARQ As Short
		Dim strLinha As String
		Dim lngNRows As Integer
		Dim lngRow As Integer
		
		' ----- Valores do arquivo
		Dim strMedidor As String
		Dim dblConsumoP As Double
		Dim dblConsumoFP As Double
		Dim dblDemandaP As Double
		Dim dblDemandaFP As Double
		Dim dblUferP As Double
		Dim dblUferFP As Double
		Dim dblDmcrP As Double
		Dim dblDmcrFP As Double
		Dim strDt_leitura As String
		
		lngNRows = getNumRows((Me.txtDir.Text))
		lngRow = 1
		
		If (lngNRows > 1) Then
			
			Me.cmdImportar.Enabled = False
			
			' ----- Abre arquivo externo
			intARQ = FreeFile
			FileOpen(intARQ, Me.txtDir.Text, OpenMode.Input)
			
			Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, lngNRows)
			lblInfo.Text = "Importando leituras..."
			
			While Not EOF(intARQ)
				On Error GoTo ErroArquivo
				strLinha = LineInput(intARQ)
				strLinha = Trim(strLinha)
				
				' ----- Se for o Inicio do Arquivo
				If VB.Left(strLinha, 6) = "Landis" Then
					lngRow = 1
				End If
				
				' ----- Busca valores
				If lngRow = 2 Then
					strDt_leitura = VB6.Format(Mid(strLinha, 8, 10), "yyyy-MM-dd")
				ElseIf lngRow = 3 Then 
					strMedidor = Mid(strLinha, 41, 8)
					
					' ----- Busca as informações do consumidor
					strSql = "SELECT zona, livro, conta, cons_id, unid_id, ta, nome " & "FROM unida " & "WHERE (num      = """ & CDbl(strMedidor) & """ " & "   OR eletr     = """ & CDbl(strMedidor) & """ " & "   OR medkw     = """ & CDbl(strMedidor) & """ " & "   OR medkvark  = """ & CDbl(strMedidor) & """) "
					Call Conectar(strSql, rsConsulta)
					If rsConsulta.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"'
						strZona = IIf(IsDbNull(rsConsulta.Fields("Zona").Value), 0, rsConsulta.Fields("Zona").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"'
						strLivro = IIf(IsDbNull(rsConsulta.Fields("Livro").Value), 0, rsConsulta.Fields("Livro").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"'
						strConta = IIf(IsDbNull(rsConsulta.Fields("Conta").Value), 0, rsConsulta.Fields("Conta").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"'
						strCons_id = IIf(IsDbNull(rsConsulta.Fields("cons_id").Value), 0, rsConsulta.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"'
						strUnid_id = IIf(IsDbNull(rsConsulta.Fields("unid_id").Value), 0, rsConsulta.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"'
						strTa = IIf(IsDbNull(rsConsulta.Fields("ta").Value), 0, rsConsulta.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"'
						strNome = IIf(IsDbNull(rsConsulta.Fields("nome").Value), 0, rsConsulta.Fields("nome").Value)
					Else
						MsgBox("Não foi possível localizar a Unidade Consumidora com Nº Medidor: " & strMedidor, MsgBoxStyle.Exclamation + MsgBoxStyle.OKOnly, gstrTituloMensagem)
						GoTo ErroArquivo
					End If
					
					' ----- Fecha a RecordSet
					If rsConsulta.State = 1 Then Call rsConsulta.Close()
					
				ElseIf lngRow = 7 Then 
					If UCase(Mid(strTa, 3, 2)) = "A4" Then
						dblConsumoP = Arredondar((CDbl(Mid(strLinha, 32, 10)) * 3) / 10000, 2)
					End If
				ElseIf lngRow = 8 Then 
					If UCase(Mid(strTa, 3, 2)) = "AV" Then
						dblConsumoP = Arredondar((CDbl(Mid(strLinha, 32, 10)) * 3) / 10000, 2)
					End If
				ElseIf lngRow = 10 Then 
					If UCase(Mid(strTa, 3, 2)) = "AV" Then
						dblConsumoFP = Arredondar((CDbl(Mid(strLinha, 32, 10)) * 3) / 10000, 2)
					End If
				ElseIf lngRow = 16 Then 
					dblDemandaP = Arredondar((CDbl(Mid(strLinha, 36, 6)) * 3 * 4) / 10000, 2)
				ElseIf lngRow = 18 Then 
					dblDemandaFP = Arredondar((CDbl(Mid(strLinha, 36, 6)) * 3 * 4) / 10000, 2)
					If dblDemandaFP > dblDemandaP Then
						dblDemandaP = 0
					Else
						dblDemandaFP = 0
					End If
					
					If UCase(Mid(strTa, 3, 2)) = "AV" And dblDemandaP > dblDemandaFP Then
						dblDemandaFP = dblDemandaP
					End If
					
					If UCase(Mid(strTa, 3, 2)) = "A4" Then
						dblDemandaP = dblDemandaP + dblDemandaFP
						dblDemandaFP = 0
					End If
				ElseIf lngRow = 29 Then 
					dblUferP = Arredondar((CDbl(Mid(strLinha, 60, 10)) * 3) / 10000, 2)
				ElseIf lngRow = 30 Then 
					dblUferFP = Arredondar((CDbl(Mid(strLinha, 60, 10)) * 3) / 10000, 2)
					If UCase(Mid(strTa, 3, 2)) = "A4" Then
						dblUferP = dblUferP + dblUferFP
						dblUferFP = 0
					End If
				ElseIf lngRow = 32 Then 
					dblDmcrP = Arredondar((CDbl(Mid(strLinha, 64, 6)) * 3) / 10000, 2)
				ElseIf lngRow = 33 Then 
					dblDmcrFP = Arredondar((CDbl(Mid(strLinha, 64, 6)) * 3) / 10000, 2)
					
					' ----- No momento que chegar aqui, é porque tá no fim do arquivo de leitura de 1 consumidor, então grava no banco.
					strSql = "SELECT * " & "FROM leitura " & "WHERE id_consumidor = " & strCons_id & "" & "  AND id_unid       = " & strUnid_id & "" & "  AND mesano        = """ & VB.Left(VB.Right(Me.txtDir.Text, 10), 2) & "/" & Mid(VB.Right(Me.txtDir.Text, 11), 4, 4) & """ "
					Call Conectar(strSql, rsConsulta)
					If rsConsulta.RecordCount > 0 Then
						If MsgBox("Já existe leitura para " & strZona & "." & strLivro & "." & strConta & " " & strNome & " neste mês. Deseja atualizar as mesmas?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, gstrTituloMensagem) = MsgBoxResult.Yes Then
							strSql = "UPDATE leitura SET " & " dt_leit_atual      = """ & strDt_leitura & """, " & " consumo_p          = """ & Replace(CStr(dblConsumoP), ",", ".") & """, " & " consumo_fp         = """ & Replace(CStr(dblConsumoFP), ",", ".") & """, " & " demanda_p          = """ & Replace(CStr(dblDemandaP), ",", ".") & """, " & " demanda_fp         = """ & Replace(CStr(dblDemandaFP), ",", ".") & """, " & " kvarh              = """ & Replace(CStr(dblUferP), ",", ".") & """, " & " kvarh_fp           = """ & Replace(CStr(dblUferFP), ",", ".") & """, " & " dem_exc_ponta      = """ & Replace(CStr(dblDmcrP), ",", ".") & """, " & " dem_exc_fp         = """ & Replace(CStr(dblDmcrFP), ",", ".") & """ " & "WHERE id_consumidor = " & strCons_id & "" & "  AND id_unid       = " & strUnid_id & "" & "  AND mesano        = """ & VB.Left(VB.Right(Me.txtDir.Text, 10), 2) & "/" & Mid(VB.Right(Me.txtDir.Text, 11), 4, 4) & """ "
							Call Executar(strSql)
						End If
					Else
						strSql = "INSERT INTO leitura SET " & " id_consumidor      = """ & strCons_id & """, " & " zlc                = """ & strZona & strLivro & strConta & """, " & " id_unid            = """ & strUnid_id & """, " & " mesano             = """ & VB.Left(VB.Right(Me.txtDir.Text, 10), 2) & "/" & Mid(VB.Right(Me.txtDir.Text, 11), 4, 4) & """, " & " dt_leit_atual      = """ & strDt_leitura & """, " & " consumo_p          = """ & Replace(CStr(dblConsumoP), ",", ".") & """, " & " consumo_fp         = """ & Replace(CStr(dblConsumoFP), ",", ".") & """, " & " demanda_p          = """ & Replace(CStr(dblDemandaP), ",", ".") & """, " & " demanda_fp         = """ & Replace(CStr(dblDemandaFP), ",", ".") & """, " & " kvarh              = """ & Replace(CStr(dblUferP), ",", ".") & """, " & " kvarh_fp           = """ & Replace(CStr(dblUferFP), ",", ".") & """, " & " dem_exc_ponta      = """ & Replace(CStr(dblDmcrP), ",", ".") & """, " & " dem_exc_fp         = """ & Replace(CStr(dblDmcrFP), ",", ".") & """ "
						Call Executar(strSql)
					End If
					' ----- Fecha a RecordSet
					If rsConsulta.State = 1 Then Call rsConsulta.Close()
				End If
				
				lngRow = lngRow + 1
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
			End While
		End If
		lblInfo.Text = "Fim do processamento!"
		Me.cmdImportar.Enabled = True
		
		Exit Sub
		
ErroArquivo: 
		'Fecha o Arquivo
		FileClose(intARQ)
		Call MsgBox("Ocorreu um erro no processo: " & Err.Description, MsgBoxStyle.Exclamation, gstrTituloMensagem)
		Me.cmdImportar.Enabled = True
	End Sub
	
	Private Function getNumRows(ByRef strFile As String) As Short
		Dim intARQ As Short
		Dim nRows As Integer
		Dim strTemp As String
		
		nRows = 0
		intARQ = FreeFile
		
		FileOpen(intARQ, strFile, OpenMode.Input)
		While Not EOF(intARQ)
			On Error GoTo ErroNumRows
			strTemp = LineInput(intARQ)
			nRows = nRows + 1
			System.Windows.Forms.Application.DoEvents()
		End While
		FileClose(intARQ)
		
		getNumRows = nRows
		
		Exit Function
		
ErroNumRows: 
		FileClose(intARQ)
		Call MsgBox("Erro: " & Err.Description, MsgBoxStyle.Information, gstrTituloMensagem)
	End Function
	
	Private Sub frmImportarLeitGrupoA_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
		Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
		' ----- Se pressionar "Esc" fecha a janela
		If KeyAscii = 27 Then
			Me.Close()
			' ----- Altera as teclas Enter/Tab
		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
End Class