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

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

			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: frmEmissaoRessIndTotAno_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub frmEmissaoRessIndTotAno_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: frmEmissaoRessIndTotAno_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 & Format(Me.dtpMesAno.Value, "dmmyyyy") & "_S" & Format(Me.txtVersao.Text, "00") & ".XML"
			Me.txtArquivo.Text = istrArquivo & VB6.Format(idteBase, "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
			fbdRessAno.ShowDialog()
			txtDir.Text = fbdRessAno.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(2) As String
		Dim lstrDad(10) As String
		Dim lstrRef(10) As String
		Dim lstrTens(3) As String
		Dim lstrRegi(2) As String
		
		Dim lintTri As Short
		Dim lintReg As Short
		Dim lintAux As Short
		Dim lintMes As Short
		Dim lintTip As Short
		Dim lintIniMes As Short
		Dim lintPulMes As Short
		
		Dim lstrTensao As String
		Dim lstrRegiao As String
		Dim lstrIndic As String
		Dim lstrRessa As String
		Dim lstrMesAno As String
		Dim lintLin As Short
		
		Dim ldblDic As Double
		Dim ldblFic As Double
		Dim ldblMic As Double
		Dim ldblQtd As Double

		Dim lstrSql As String
		Dim dt As DataTable
		Dim objAtualizacaoBancoDados As New entidadeAtualizaBancoDados
		Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

		Try

			'--- Indicadores Mensais - Para trimestral basta colocar a letra "T" no final de cada comando - Para anual em vez de "T" é a letra "A".
			lstrAux(1) = "QTUC?1T?2" 'Quantidade de UCs AT,MT,BT compensadas por violação dos limites de continuidade no mês (sendo Urbana e não urbana)
			lstrAux(2) = "PGUC?1T?2" 'Valor pago a UCs AT,MT,BT compensadas por violação dos limites de continuidade no mês (sendo Urbana (U) e não urbana (NU) )

			lstrTens(1) = "A"
			lstrTens(2) = "M"
			lstrTens(3) = "B"
			lstrRegi(1) = "U"
			lstrRegi(2) = "NU"
			'
			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(idteBase, "dd/mm/yyyy") & """ " & "Sequencial=""S" & Me.txtVersao.Text & """>")

			'Loop tensao por que se não tiver no registro entao vai zero aonde é valor
			For lintTip = 1 To 3
				lintIniMes = IIf(lintTip = 1, 1, IIf(lintTip = 2, 3, 12))
				lintPulMes = IIf(lintTip = 1, 1, IIf(lintTip = 2, 3, 1))
				lintTri = 0
				For lintMes = lintIniMes To 12 Step lintPulMes
					lintTri = lintTri + 1
					For lintAux = 1 To 3
						lstrSql = ""
						lstrSql = lstrSql & "SELECT `indicadores`.`mesanoref`, "
						lstrSql = lstrSql & "       `indicadores`.`tensao`, "
						lstrSql = lstrSql & "       `indicadores`.`regiao`, "
						lstrSql = lstrSql & "       COUNT(*) AS `qtde`, "
						lstrSql = lstrSql & "       SUM(`indicadores`.`vfic`) AS `totfic`, "
						lstrSql = lstrSql & "       SUM(`indicadores`.`vdic`) AS `totdic`, "
						lstrSql = lstrSql & "       SUM(`indicadores`.`vdmic`) AS `totdmic` "
						lstrSql = lstrSql & "  FROM `indicadores` "
						lstrSql = lstrSql & " WHERE `indicadores`.`mesanoref` = '" & VB6.Format(lintMes, "00") & "/" & (VB6.Format(Me.dtpMesAno.value, "yyyy")) & "' "
						lstrSql = lstrSql & "   AND (`indicadores`.`vdic` > 0 OR `indicadores`.`vfic` > 0 OR `indicadores`.`vdmic` > 0) "
						lstrSql = lstrSql & "   AND `tipo` = '" & IIf(lintTip = 1, "M", IIf(lintTip = 2, "T", "A")) & "' "
						lstrSql = lstrSql & "   AND `tensao` = '" & lstrTens(lintAux) & "' "
						lstrSql = lstrSql & " GROUP BY `mesanoref`, `tensao`, `regiao` "
						lstrSql = lstrSql & " ORDER BY IF(`regiao` = 'U', 0, 1) ASC "

						objAtualizacaoBancoDados.QUERY_NAME = lstrSql
						dt = repositorioAtualizaBancoDados.Consultar(objAtualizacaoBancoDados)

						If dt.Rows.Count > 0 Then

							Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, dt.Rows.Count, " Tipo: " & IIf(lintTip = 1, "M", IIf(lintTip = 2, "T", "A")) & " Mês: " & lintMes)
							For Each row As DataRow In dt.Rows

								lstrTensao = IIf(IsDBNull(row.Item("tensao")), "B", row.Item("tensao")) 'B,M,A
								lstrRegiao = IIf(IsDBNull(row.Item("regiao")), "U", row.Item("regiao")) 'U,R
								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)
								ldblDic = CDbl(IIf(IsDBNull(row.Item("totdic")), 0, row.Item("totdic")))
								ldblFic = CDbl(IIf(IsDBNull(row.Item("totfic")), 0, row.Item("totfic")))
								ldblMic = CDbl(IIf(IsDBNull(row.Item("totdmic")), 0, row.Item("totdmic")))
								ldblQtd = CDbl(IIf(IsDBNull(row.Item("qtde")), 0, row.Item("qtde")))
								If ldblDic <> 0 Then
									lstrDad(2) = Replace(FormatNumber(ldblDic, 2), ",", ".") 'DIC
									lstrDad(1) = Replace(FormatNumber(ldblQtd, 0), ",", ".")
								ElseIf ldblFic <> 0 Then
									lstrDad(2) = Replace(FormatNumber(ldblFic, 2), ",", ".") 'FIC
									lstrDad(1) = Replace(FormatNumber(ldblQtd, 0), ",", ".")
								ElseIf ldblMic <> 0 Then
									lstrDad(2) = Replace(FormatNumber(ldblMic, 2), ",", ".") 'DMIC
									lstrDad(1) = Replace(FormatNumber(ldblQtd, 0), ",", ".")
								Else
									lstrDad(2) = "0.00"
								End If
								If lstrDad(2) <> "0.00" Then
									For lintLin = 1 To 2
										PrintLine(lintNuArq, vbTab & "<indicador>")
										PrintLine(lintNuArq, vbTab & vbTab & "<codigo_conjunto>" & lstrCodConj & "</codigo_conjunto>")
										PrintLine(lintNuArq, vbTab & vbTab & "<codigo_UC/>")
										PrintLine(lintNuArq, vbTab & vbTab & "<sigla_indice>" & Replace(Replace(lstrAux(lintLin), "?1", lstrTens(lintAux)), "?2", IIf(lstrTens(lintAux) = "A", "", IIf(lstrRegiao = "U", lstrRegiao, "NU"))) & IIf(lintTip = 2, "T", IIf(lintTip = 3, "A", "")) & "</sigla_indice>")
										PrintLine(lintNuArq, vbTab & vbTab & "<valor_indicador>" & lstrDad(lintLin) & "</valor_indicador>")
										PrintLine(lintNuArq, vbTab & vbTab & "<periodo_competencia>" & VB.Left(IIf(lintTip = 1, lstrMesAno, IIf(lintTip = 2, lintTri, "01")), 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) = "0"
							lstrDad(2) = "0.00"
							For lintReg = 1 To IIf(lstrTens(lintAux) = "A", 1, 2)
								For lintLin = 1 To 2
									PrintLine(lintNuArq, vbTab & "<indicador>")
									PrintLine(lintNuArq, vbTab & vbTab & "<codigo_conjunto>" & lstrCodConj & "</codigo_conjunto>")
									PrintLine(lintNuArq, vbTab & vbTab & "<codigo_UC/>")
									PrintLine(lintNuArq, vbTab & vbTab & "<sigla_indice>" & Replace(Replace(lstrAux(lintLin), "?1", lstrTens(lintAux)), "?2", IIf(lstrTens(lintAux) = "A", "", lstrRegi(lintReg))) & IIf(lintTip = 2, "T", IIf(lintTip = 3, "A", "")) & "</sigla_indice>")
									PrintLine(lintNuArq, vbTab & vbTab & "<valor_indicador>" & lstrDad(lintLin) & "</valor_indicador>")
									PrintLine(lintNuArq, vbTab & vbTab & "<periodo_competencia>" & (VB6.Format(IIf(lintTip = 1, lintMes, IIf(lintTip = 2, lintTri, 1)), "00")) & "</periodo_competencia>")
									PrintLine(lintNuArq, vbTab & vbTab & "<ano_competencia>" & (VB6.Format(Me.dtpMesAno.Value, "yyyy")) & "</ano_competencia>")
									PrintLine(lintNuArq, vbTab & "</indicador>")
								Next lintLin
							Next lintReg
						End If

					Next lintAux
				Next lintMes
			Next lintTip
			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