Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Friend Class frmEmissaoRessInd
	Inherits System.Windows.Forms.Form
	'APLTIQXXXXINDICADORES_DDMMAAAA_SXX.xml
	Private istrCaminho As String
	Private istrArquivo As String

	Private Sub frmEmissaoRessInd_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Try
			Me.dtpMesAno.Value = Date.Now() 'BuscaDataBD()

			istrCaminho = GetConfig("caminho.xml")
			If Len(Trim(istrCaminho)) = 0 Or Trim(istrCaminho) = "-1" Then
				istrCaminho = My.Application.Info.DirectoryPath
			End If
			If VB.Right(Trim(istrCaminho), 1) <> "\" Then
				istrCaminho = istrCaminho & "\"
			End If
			istrArquivo = "APLTIQ" & VB6.Format(VB.Left(gstrEmpresa_CodRes89, 4), "0000") & "INDICADORES_"
			Me.txtVersao.Text = "01"
			Call NomeArquivoXML()
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmEmissaoRessInd_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub frmEmissaoRessInd_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
		Try
			Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
			If KeyAscii = System.Windows.Forms.Keys.Escape Then
				Call cmdFechar_Click(cmdFechar, New System.EventArgs())
			ElseIf KeyAscii = System.Windows.Forms.Keys.Return Then
				TabEnter(KeyAscii, eventArgs)
			End If
			eventArgs.KeyChar = Chr(KeyAscii)
			If KeyAscii = 0 Then
				eventArgs.Handled = True
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmEmissaoRessInd_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub NomeArquivoXML()
		Try
			Me.txtDir.Text = istrCaminho
			Me.txtArquivo.Text = istrArquivo & VB6.Format(Me.dtpMesAno.Value, "ddmmyyyy") & "_S" & VB6.Format(Me.txtVersao.Text, "00") & ".XML"
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: NomeArquivoXML" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub
	Private Sub cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click
		Call Me.Close()
	End Sub
	Private Sub txtDir_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDir.TextChanged
		Try
			With Me.txtDir
				istrCaminho = .Text
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtDir_TextChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

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

	Private Sub txtDir_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDir.Leave
		Try
			With Me.txtDir
				If Len(Trim(.Text)) = 0 Then
					Call MsgBox("Este campo é de preenchimento obrigatório!", MsgBoxStyle.Information, gstrTituloMensagem)
					Call NomeArquivoXML()
					.Focus()
				Else
					istrCaminho = .Text
				End If
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtDir_Leave" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

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

	Private Sub txtVersao_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtVersao.Leave
		Try
			With Me.txtVersao
				.Text = VB6.Format(.Text, "00")
				Call NomeArquivoXML()
			End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtVersao_Leave" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub DTPMesAno_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles DTPMesAno.Leave
		Call NomeArquivoXML()
	End Sub

	Private Sub cmdSalvarArq_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSalvarArq.Click
		Try
			fbdressarcimento.ShowDialog()
			txtDir.Text = fbdressarcimento.SelectedPath & "\"
			'With Me.cmdSalvarArq
			'Me.Enabled = False
			'frmDir.frmQuemChama = Me
			'frmDir.intTipo = 0
			'Call frmDir.SetBounds(VB6.TwipsToPixelsX(VB6.PixelsToTwipsX(Me.Left) + VB6.PixelsToTwipsX(.Left) + 400), VB6.TwipsToPixelsY(VB6.PixelsToTwipsY(Me.Top) + VB6.PixelsToTwipsY(.Top) + 400), 0, 0, Windows.Forms.BoundsSpecified.X Or Windows.Forms.BoundsSpecified.Y)
			'Call frmDir.Show()
			'End With
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdSalvarArq_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub cmdGerar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdGerar.Click
		Try
			Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
			Call LigDes(False)
			Call GerarXML()
			Call LigDes(True)
			System.Windows.Forms.Application.DoEvents()
			Me.Cursor = System.Windows.Forms.Cursors.Default
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdGerar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub LigDes(ByRef aModo As Boolean)
		Try
			Me.lblMesAno.Enabled = aModo
			Me.dtpMesAno.Enabled = aModo
			Me.lblCaminho.Enabled = aModo
			Me.txtDir.Enabled = aModo
			Me.lblArquivo.Enabled = aModo
			Me.txtArquivo.Enabled = aModo
			Me.lblVersao.Enabled = aModo
			Me.txtVersao.Enabled = aModo
			Me.lblVersao.Enabled = aModo
			Me.cmdSalvarArq.Enabled = aModo
			Me.cmdGerar.Enabled = aModo
			Me.cmdFechar.Enabled = aModo
			System.Windows.Forms.Application.DoEvents()
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: LigDes" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub GerarXML()
		Dim lstrCodConj As String
		Dim lstrNMArq As String
		Dim lintNuArq As Short
		Dim lstrAux(9) As String
		Dim lstrDad(9) As String
		Dim lstrRef(9) As String
		
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrItens As String
		Dim lstrIndic As String
		Dim lstrRessa As String
		Dim lstrMesAno As String
		Dim lstrClasse As String
		Dim lintLin As Short
		
		Dim ldblDic As Double
		Dim ldblFic As Double
		Dim ldblMic As Double

		Dim lstrSql As String

		Dim dt As DataTable
		Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
		Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

		Try

			lstrAux(1) = "CODMUNUC" 'Código do municipio IBGE.
			lstrAux(2) = "TNS" 'Tensão contrata do consumidor (127,220,380,...).
			lstrAux(3) = "LOCUC" 'Localização da unidade consumidora (1:Urbano, 2: Não Urbano).
			lstrAux(4) = "CODCLSUC" 'Código da classe da unidade consumidora.
			lstrAux(5) = "CM" 'Cálculo do Somatório do resultado de Consumo e ou demanda e ou reativos X tusd de cada.
			lstrAux(6) = "FICVLD" 'Valor realizado do indicador FIC mensal.
			lstrAux(7) = "DICVLD" 'Valor realizado do indicador dIC mensal.
			lstrAux(8) = "DMICVLD" 'Valor realizado do indicador DMIC mensal.
			lstrAux(9) = "COMPCONT" 'Compensação pela violação do DIC, FIC ou DMIC mensais.
			'
			lstrCodConj = gstrEmpresa_Conjunto
			'
			'Gerar o arquivo mesmo sem informação
			lintNuArq = FreeFile
			lstrNMArq = Me.txtDir.Text & IIf(VB.Right(Trim(Me.txtDir.Text), 1) <> "\", "\", "") & Me.txtArquivo.Text
			FileOpen(lintNuArq, lstrNMArq, OpenMode.Output)
			PrintLine(lintNuArq, "<?xml version=""1.0"" encoding=""ISO8859-1""?>")
			PrintLine(lintNuArq, "<TIQ Tipo=""indicadores"" " & "CodigoConcessionario=""" & gstrEmpresa_CodRes89 & """ " & "Sigla=""" & gstrEmpresa_Sigla & """ " & "DataGeracaoArquivo=""" & VB6.Format(Me.dtpMesAno.Value, "dd/mm/yyyy") & """ " & "Sequencial=""S" & Me.txtVersao.Text & """>")

			lstrSql = ""
			lstrSql = lstrSql & "SELECT indicadores.mesanoref, "
			lstrSql = lstrSql & "       indicadores.zona, "
			lstrSql = lstrSql & "       indicadores.livro, "
			lstrSql = lstrSql & "       indicadores.conta, "
			lstrSql = lstrSql & "       indicadores.vcm, "
			lstrSql = lstrSql & "       indicadores.vfic, "
			lstrSql = lstrSql & "       indicadores.vdic, "
			lstrSql = lstrSql & "       indicadores.vdmic, "
			lstrSql = lstrSql & "       indicadores.rfic, "
			lstrSql = lstrSql & "       indicadores.rdic, "
			lstrSql = lstrSql & "       indicadores.rdmic, "
			lstrSql = lstrSql & "       IFNULL(uc_faturamento.tensao,'220') as tensao, "
			lstrSql = lstrSql & "       IFNULL(uc_faturamento.clas,'9101') as codclas, "
			lstrSql = lstrSql & "       IFNULL(uc_faturamento.regiao,'U') as regiao, "
			lstrSql = lstrSql & "       (select ibge from munic where munic.zona = indicadores.zona) as ibge "
			lstrSql = lstrSql & "  FROM indicadores "
			lstrSql = lstrSql & " LEFT JOIN uc_faturamento ON(uc_faturamento.zona = indicadores.zona and uc_faturamento.livro = indicadores.livro and uc_faturamento.conta = indicadores.conta and indicadores.grupo = 'A') "
			'lstrSql = lstrSql & " LEFT JOIN unida ON(unida.zona = indicadores.zona and unida.livro = indicadores.livro and unida.conta = indicadores.conta and indicadores.grupo = 'A') "
			'lstrSql = lstrSql & " LEFT JOIN unidb ON(unidb.zona = indicadores.zona and unidb.livro = indicadores.livro and unidb.conta = indicadores.conta and indicadores.grupo = 'B') "
			lstrSql = lstrSql & " WHERE indicadores.mesanoref = '" & (VB6.Format(Me.dtpMesAno.value, "mm/yyyy")) & "' "
			lstrSql = lstrSql & "  AND (indicadores.vdic>0 OR indicadores.vfic>0 OR indicadores.vdmic>0)"
			lstrSql = lstrSql & "   AND `tipo` = '" & IIf(Me.opbMensal.Checked, "M", IIf(Me.opbTrimestral.Checked, "T", "A")) & "' "
			objAtualizaBancoDados.QUERY_NAME = lstrSql
			dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

			If dt.Rows.Count > 0 Then
				Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, dt.Rows.Count)
				For Each row As DataRow In dt.Rows

					lstrZona = Trim(IIf(IsDBNull(row.Item("zona")), "000", row.Item("zona")))
					lstrLivro = Trim(IIf(IsDBNull(row.Item("livro")), "00", row.Item("livro")))
					lstrConta = Trim(IIf(IsDBNull(row.Item("conta")), "000000", row.Item("conta")))
					lstrIndic = Trim(IIf(IsDBNull(row.Item("mesanoref")), "", row.Item("mesanoref"))) 'mesano de referencia do indicador
					lstrRessa = lstrIndic 'mesano de ressarcimento
					lstrMesAno = IIf(Len(lstrRessa) > 0, lstrRessa, lstrIndic)
					lstrDad(1) = IIf(IsDBNull(row.Item("ibge")), "", row.Item("ibge"))
					lstrDad(2) = IIf(IsDBNull(row.Item("tensao")), "220", row.Item("tensao"))
					lstrDad(3) = IIf(IsDBNull(row.Item("regiao")), "U", row.Item("regiao"))
					lstrDad(3) = IIf(lstrDad(3) = "U", 1, 2)
					lstrClasse = IIf(IsDBNull(row.Item("codclas")), "9101", row.Item("codclas"))
					Select Case CShort(VB.Left(lstrClasse, 1))
						Case Is = 9
							lstrDad(4) = CStr(1) 'Residencial
						Case Is < 4
							lstrDad(4) = CStr(2) 'Industrial
						Case Is = 4
							lstrDad(4) = CStr(3) 'Comercial, Serviços e Outras
						Case Is = 5
							lstrDad(4) = CStr(4) 'Rural
						Case Is = 6
							If CShort(VB.Left(lstrClasse, 2)) = 64 Then
								lstrDad(4) = CStr(6) 'Iluminação Publica
							Else
								lstrDad(4) = CStr(5) 'Poder Publico
							End If
						Case Is = 7
							lstrDad(4) = CStr(7) 'Serviço Publico
						Case Is = 8
							lstrDad(4) = CStr(8) 'Consumo Proprio
							'Case Is = ?
							'lstrDad(4) = 9 'Rural Irrigante
							'Case Is = ?
							'lstrDad(4) = 10 'Rural Aquicultor
					End Select

					lstrDad(5) = Replace(FormatNumber(CDbl(IIf(IsDBNull(row.Item("vcm")), 0, row.Item("vcm"))), 2), ",", ".") 'CM
					lstrDad(6) = Replace(FormatNumber(CDbl(IIf(IsDBNull(row.Item("rfic")), 0, row.Item("rfic"))), 2), ",", ".") 'FICVLD
					lstrDad(7) = Replace(FormatNumber(CDbl(IIf(IsDBNull(row.Item("rdic")), 0, row.Item("rdic"))), 2), ",", ".") 'DICVLD
					lstrDad(8) = Replace(FormatNumber(CDbl(IIf(IsDBNull(row.Item("rdmic")), 0, row.Item("rdmic"))), 2), ",", ".") 'DMICVLD
					ldblDic = CDbl(IIf(IsDBNull(row.Item("vdic")), 0, row.Item("vdic")))
					ldblFic = CDbl(IIf(IsDBNull(row.Item("vfic")), 0, row.Item("vfic")))
					ldblMic = CDbl(IIf(IsDBNull(row.Item("vdmic")), 0, row.Item("vdmic")))

					If ldblDic <> 0 Then
						lstrDad(9) = Replace(FormatNumber(ldblDic, 2), ",", ".") 'DIC
					ElseIf ldblFic <> 0 Then
						lstrDad(9) = Replace(FormatNumber(ldblFic, 2), ",", ".") 'FIC
					ElseIf ldblMic <> 0 Then
						lstrDad(9) = Replace(FormatNumber(ldblMic, 2), ",", ".") 'DMIC
					Else
						lstrDad(9) = "0.00"
					End If
					If lstrDad(9) <> "0.00" Then
						For lintLin = 1 To 9
							PrintLine(lintNuArq, vbTab & "<indicador>")
							PrintLine(lintNuArq, vbTab & vbTab & "<codigo_conjunto>" & lstrCodConj & "</codigo_conjunto>")
							PrintLine(lintNuArq, vbTab & vbTab & "<codigo_UC>" & lstrZona & lstrLivro & lstrConta & "</codigo_UC>")
							PrintLine(lintNuArq, vbTab & vbTab & "<sigla_indice>" & lstrAux(lintLin) & "</sigla_indice>")
							PrintLine(lintNuArq, vbTab & vbTab & "<valor_indicador>" & lstrDad(lintLin) & "</valor_indicador>")
							PrintLine(lintNuArq, vbTab & vbTab & "<periodo_competencia>" & VB.Left(lstrMesAno, 2) & "</periodo_competencia>")
							PrintLine(lintNuArq, vbTab & vbTab & "<ano_competencia>" & VB.Right(lstrMesAno, 4) & "</ano_competencia>")
							PrintLine(lintNuArq, vbTab & "</indicador>")
						Next lintLin
					End If
					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
				Next
			Else
				lstrDad(1) = "4219002"
				lstrDad(2) = "220"
				lstrDad(3) = "1"
				lstrDad(4) = "1"
				lstrDad(5) = "0.00"
				lstrDad(6) = "0.00"
				lstrDad(7) = "0.00"
				lstrDad(8) = "0.00"
				lstrDad(9) = "0.00"
				For lintLin = 1 To 9
					PrintLine(lintNuArq, vbTab & "<indicador>")
					PrintLine(lintNuArq, vbTab & vbTab & "<codigo_conjunto>" & lstrCodConj & "</codigo_conjunto>")
					PrintLine(lintNuArq, vbTab & vbTab & "<codigo_UC>0</codigo_UC>")
					PrintLine(lintNuArq, vbTab & vbTab & "<sigla_indice>" & lstrAux(lintLin) & "</sigla_indice>")
					PrintLine(lintNuArq, vbTab & vbTab & "<valor_indicador>" & lstrDad(lintLin) & "</valor_indicador>")
					PrintLine(lintNuArq, vbTab & vbTab & "<periodo_competencia>" & (VB6.Format(Me.dtpMesAno.Value, "mm")) & "</periodo_competencia>")
					PrintLine(lintNuArq, vbTab & vbTab & "<ano_competencia>" & (VB6.Format(Me.dtpMesAno.Value, "yyyy")) & "</ano_competencia>")
					PrintLine(lintNuArq, vbTab & "</indicador>")
				Next lintLin
			End If

			PrintLine(lintNuArq, "</TIQ>")
			FileClose(lintNuArq)
			Call MsgBox("Arquivo gerado com sucesso!", MsgBoxStyle.Information, gstrTituloMensagem)

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


End Class