Option Strict Off
Option Explicit On
Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Friend Class frmExportaFaturamento
	Inherits System.Windows.Forms.Form
	Private istrExtensaoArq As String
	Private istrNmArq As String
	Private istrPath As String
	Private sCarregouForm As Boolean = False
	Private sExtensao As String

	'UPGRADE_WARNING: Event chkGrupoA.CheckStateChanged 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 chkGrupoA_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkGrupoA.CheckStateChanged
		Try
			If sCarregouForm Then
				Me.chkGrupoB.CheckState = IIf(Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Unchecked, System.Windows.Forms.CheckState.Checked, Me.chkGrupoA.CheckState)
				Call NomeArquivo()
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkGrupoA_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'UPGRADE_WARNING: Event chkGrupoB.CheckStateChanged 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 chkGrupoB_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkGrupoB.CheckStateChanged
		Try
			If sCarregouForm Then
				Me.chkGrupoA.CheckState = IIf(Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Unchecked, System.Windows.Forms.CheckState.Checked, Me.chkGrupoB.CheckState)
				Call NomeArquivo()
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkGrupoB_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub cmdArquivo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdArquivo.Click
		Dim lstrAux As String
		Try
			Call NomeArquivo()
			''UPGRADE_WARNING: Filter has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			'Me.dialArqOpen.Filter = "*." & Me.dialArqOpen.DefaultExt
			'Me.dialArqOpen.FileName = StrReverse(Mid(StrReverse(Me.txtArquivo.Text), CInt(InStr(StrReverse(Me.txtArquivo.Text), "\")))) & istrNmArq & "." & Me.dialArqOpen.DefaultExt
			'Me.dialArqOpen.Title = "Arquivo de exportação de faturas"
			'Me.dialArqOpen.ShowDialog()
			fbdfaturamento.ShowDialog()
			'lstrAux = StrReverse(fbdfaturamento.SelectedPath())
			lstrAux = fbdfaturamento.SelectedPath() & "\"
			Me.txtArquivo.Text = Mid(lstrAux, CInt(InStr(lstrAux, "\"))) & istrNmArq & "." & sExtensao 'Me.dialArqOpen.DefaultExt
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdArquivo_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub cmdExporta_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExporta.Click
		Call Exporta()
	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 frmExportaFaturamento_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 Me.Close()
			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: frmExportaFaturamento_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub frmExportaFaturamento_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Try
			sExtensao = "CSV"
			Me.dtpInicio.Value = VB6.Format(Date.Now, "dd/MM/yyyy")
			Me.dtpFinal.Value = UltimoDiaMes(Month(Me.dtpInicio.Value), Year(Me.dtpInicio.Value)) & "/" & Month(Me.dtpInicio.Value) & "/" & Year(Me.dtpInicio.Value)
			Me.dtpMesAno.Value = Me.dtpInicio.Value
			'Me.txtArquivo.Text = My.Application.Info.DirectoryPath & "\" '& istrNmArq & "." & sExtensao 'Me.dialArqOpen.DefaultExt
			Call NomeArquivo()
			sCarregouForm = True
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmExportaFaturamento_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'UPGRADE_WARNING: Event opbEmAbertos.CheckedChanged 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 opbEmAbertos_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbEmAbertos.CheckedChanged
		Try
			If sCarregouForm Then
				If eventSender.Checked Then
					Me.dtpInicio.Enabled = False
					Me.dtpFinal.Enabled = False
					Me.dtpMesAno.Enabled = True
					Call NomeArquivo()
				End If
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: opbEmAbertos_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'UPGRADE_WARNING: Event opbMesAnoFaturamento.CheckedChanged 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 opbMesAnoFaturamento_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbMesAnoFaturamento.CheckedChanged
		Try
			If sCarregouForm Then
				If eventSender.Checked Then
					Me.dtpInicio.Enabled = False
					Me.dtpFinal.Enabled = False
					Me.dtpMesAno.Enabled = True
					Call NomeArquivo()
				End If
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: opbMesAnoFaturamento_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'UPGRADE_WARNING: Event opbArrecacao.CheckedChanged 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 opbArrecacao_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbArrecacao.CheckedChanged
		Try
			If sCarregouForm Then
				If eventSender.Checked Then
					Me.dtpInicio.Enabled = True
					Me.dtpFinal.Enabled = True
					Me.dtpMesAno.Enabled = False
					Call NomeArquivo()
				End If
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: opbArrecacao_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	'UPGRADE_WARNING: Event opbVencimento.CheckedChanged 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 opbVencimento_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbVencimento.CheckedChanged
		Try
			If sCarregouForm Then
				If eventSender.Checked Then
					Me.dtpInicio.Enabled = True
					Me.dtpFinal.Enabled = True
					Me.dtpMesAno.Enabled = False
					Call NomeArquivo()
				End If
			End If
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: opbVencimento_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub NomeArquivo()
		Dim lstrAux As String
		Dim lstrGrupo As String
		Dim lstrTipo As String
		Dim lstrPeriodo As String

		Try

			If fbdfaturamento.SelectedPath() = "" Then
				Me.txtArquivo.Text = My.Application.Info.DirectoryPath & "\"
			Else
				Me.txtArquivo.Text = fbdfaturamento.SelectedPath() & "\"
			End If

			'lstrGrupo = ""
			'If Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked Then
			'	lstrGrupo = lstrGrupo & "GrupoA"
			'End If
			'If Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Checked Then
			'	lstrGrupo = lstrGrupo & IIf(Trim(lstrGrupo) <> "", "_", "") & "GrupoB"
			'End If
			If Me.opbArrecacao.Checked Then
				lstrTipo = Replace(Trim(Me.opbArrecacao.Text), " ", "_")
				lstrPeriodo = VB6.Format(Me.dtpInicio.Value, "yyyyMMdd") & "_" & VB6.Format(Me.dtpFinal.Value, "yyyyMMdd")
			ElseIf Me.opbVencimento.Checked Then
				lstrTipo = Replace(Trim(Me.opbVencimento.Text), " ", "_")
				lstrPeriodo = VB6.Format(Me.dtpInicio.Value, "yyyyMMdd") & "_" & VB6.Format(Me.dtpFinal.Value, "yyyyMMdd")
			ElseIf Me.opbMesAnoFaturamento.Checked Then
				lstrTipo = Replace(Trim(Me.opbMesAnoFaturamento.Text), " ", "_")
				lstrPeriodo = VB6.Format(Me.dtpMesAno.Value, "yyyyMM")
			ElseIf Me.opbEmAbertos.Checked Then
				lstrTipo = Replace(Trim(Me.opbEmAbertos.Text), " ", "_")
				lstrPeriodo = VB6.Format(Me.dtpMesAno.Value, "yyyyMM")
			End If
			'istrNmArq = "Faturas_" & lstrGrupo & "_" & lstrTipo & "_" & lstrPeriodo
			istrNmArq = "Faturas_" & lstrTipo & "_" & lstrPeriodo
			lstrAux = (Me.txtArquivo.Text)
			'lstrAux = StrReverse(Me.txtArquivo.Text)
			Me.txtArquivo.Text = Mid(lstrAux, CInt(InStr(lstrAux, "\"))) & istrNmArq & "." & sExtensao 'Me.dialArqOpen.DefaultExt
			System.Windows.Forms.Application.DoEvents()
		Catch ex As Exception
			MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: NomeArquivo" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
			Exit Sub
		End Try
	End Sub

	Private Sub Exporta()
		Dim llngAux As Integer
		Dim lstrLin As String
		Dim lintARQ As Short
		Dim lstrSql As String
		Dim i As Integer
		Dim dt As DataTable
		Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
		Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

		Try

			If Trim(Me.txtArquivo.Text) <> "" Then
				Me.lblInfo.Text = " Buscando as faturas, aguarde..."
				Call Me.lblInfo.Refresh()
				Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
				Call LigDes(False)

				lstrSql = "SELECT * FROM `vwexporta_faturamento` "
				lstrSql = lstrSql & " WHERE 1 = 1" '`grupo` IN(
				'If Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked Then
				'	lstrSql = lstrSql & "'A'"
				'End If
				'If Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Checked Then
				'	lstrSql = lstrSql & IIf(Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked, ",", "") & "'B'"
				'End If
				'lstrSql = lstrSql & ")"
				If Me.opbArrecacao.Checked Then
					lstrSql = lstrSql & " AND (`data_pagamento` BETWEEN '" & VB6.Format(Me.dtpInicio.Value, "yyyy-MM-dd") & "' AND '" & VB6.Format(Me.dtpFinal.Value, "yyyy-MM-dd") & "') "
				ElseIf Me.opbVencimento.Checked Then
					lstrSql = lstrSql & " AND (`data_vencimento` BETWEEN '" & VB6.Format(Me.dtpInicio.Value, "yyyy-MM-dd") & "' AND '" & VB6.Format(Me.dtpFinal.Value, "yyyy-MM-dd") & "') "
				ElseIf Me.opbMesAnoFaturamento.Checked Then
					lstrSql = lstrSql & " AND `mesano_referencia` = " & VB6.Format(Me.dtpMesAno.Value, "yyyyMM") & " "
				ElseIf Me.opbEmAbertos.Checked Then
					lstrSql = lstrSql & "   AND (`flgst` <> 'C' OR " & vbCrLf
					lstrSql = lstrSql & "        ( (`flgst`='C' AND `datast` > '" & VB6.Format(CDate(UltimoDiaMes(Month(Me.dtpMesAno.Value), Year(Me.dtpMesAno.Value)) & "/" & VB6.Format(Me.dtpMesAno.Value, "MM/yyyy")), "yyyy-MM-dd") & "') " & vbCrLf
					lstrSql = lstrSql & "         )" & vbCrLf
					lstrSql = lstrSql & "        )" & vbCrLf
					lstrSql = lstrSql & "   AND `mesano_referencia` <= " & CInt(VB6.Format(Me.dtpMesAno.Value, "yyyyMM")) & " " & vbCrLf
					lstrSql = lstrSql & " AND (`data_pagamento` > '" & VB6.Format(CDate(UltimoDiaMes(Month(Me.dtpMesAno.Value), Year(Me.dtpMesAno.Value)) & "/" & VB6.Format(Me.dtpMesAno.Value, "MM/yyyy")), "yyyy-MM-dd") & "' OR `data_pagamento` = '0000-00-00') " & vbCrLf
					lstrSql = lstrSql & "   AND NOT EXISTS(SELECT * FROM `reserva` "
					lstrSql = lstrSql & "                   WHERE `reserva`.`numnf`    = `vwexporta_faturamento`.`numero_fatura` "
					lstrSql = lstrSql & "                     AND `reserva`.`mesano`   = `vwexporta_faturamento`.`mesano_fatura` "
					lstrSql = lstrSql & "                     AND `reserva`.`zona`     = `vwexporta_faturamento`.`zona` "
					lstrSql = lstrSql & "                     AND `reserva`.`livro`    = `vwexporta_faturamento`.`livro` "
					lstrSql = lstrSql & "                     AND `reserva`.`conta`    = `vwexporta_faturamento`.`conta` "
					lstrSql = lstrSql & "                     AND `reserva`.`datares` <= '" & VB6.Format(CDate(UltimoDiaMes(Month(Me.dtpMesAno.Value), Year(Me.dtpMesAno.Value)) & "/" & VB6.Format(Me.dtpMesAno.Value, "MM/yyyy")), "yyyy-MM-dd") & "')"
				End If
				objAtualizaBancoDados.QUERY_NAME = lstrSql
				dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

				If dt.Rows.Count > 0 Then
					lintARQ = FreeFile()
					FileOpen(lintARQ, Me.txtArquivo.Text, OpenMode.Output)
					Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, dt.Rows.Count)
					lstrLin = ""

					If dt.Columns.Count > 0 Then
						For Each columns As DataColumn In dt.Columns
							lstrLin = lstrLin & IIf(IsDBNull(columns.ColumnName), "", columns.ColumnName) & ";"
						Next
						PrintLine(lintARQ, lstrLin)

						For Each row As DataRow In dt.Rows
							lstrLin = ""
							i = 0
							For Each columns2 As DataColumn In dt.Columns
								lstrLin = lstrLin & IIf(IsDBNull(row.Item(i)), "", row.Item(i)) & ";"
								i = i + 1
							Next
							PrintLine(lintARQ, lstrLin)
							Call BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)
						Next
						FileClose(lintARQ)
					End If
				End If

				Call LigDes(True)
				Me.Cursor = System.Windows.Forms.Cursors.Default
				Call MsgBox("Arquivo gerado com sucesso!", MsgBoxStyle.Information, gstrTituloMensagem)
			End If

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

	End Sub

	Private Sub LigDes(ByVal ablnModo As Boolean)
		Try

			If ablnModo Then
				If Me.opbVencimento.Checked Then
					Me.opbArrecacao.Enabled = ablnModo
					Me.opbMesAnoFaturamento.Enabled = ablnModo
					Me.opbEmAbertos.Enabled = ablnModo
					Me.opbVencimento.Enabled = ablnModo
					Me.opbVencimento.Checked = True
				ElseIf Me.opbArrecacao.Checked Then
					Me.opbVencimento.Enabled = ablnModo
					Me.opbMesAnoFaturamento.Enabled = ablnModo
					Me.opbEmAbertos.Enabled = ablnModo
					Me.opbArrecacao.Enabled = ablnModo
					Me.opbArrecacao.Checked = True
				ElseIf Me.opbMesAnoFaturamento.Checked Then
					Me.opbVencimento.Enabled = ablnModo
					Me.opbArrecacao.Enabled = ablnModo
					Me.opbEmAbertos.Enabled = ablnModo
					Me.opbMesAnoFaturamento.Enabled = ablnModo
					Me.opbMesAnoFaturamento.Checked = True
				ElseIf Me.opbEmAbertos.Checked Then
					Me.opbVencimento.Enabled = ablnModo
					Me.opbArrecacao.Enabled = ablnModo
					Me.opbMesAnoFaturamento.Enabled = ablnModo
					Me.opbEmAbertos.Enabled = ablnModo
					Me.opbEmAbertos.Checked = True
				End If
			Else
				Me.opbVencimento.Enabled = ablnModo
				Me.opbArrecacao.Enabled = ablnModo
				Me.opbMesAnoFaturamento.Enabled = ablnModo
				Me.opbEmAbertos.Enabled = ablnModo
			End If
			Me.dtpMesAno.Enabled = IIf((Me.opbMesAnoFaturamento.Enabled And Me.opbMesAnoFaturamento.Checked) Or (Me.opbEmAbertos.Enabled And Me.opbEmAbertos.Checked), True, False)
			Me.dtpInicio.Enabled = IIf((Me.opbVencimento.Enabled And Me.opbVencimento.Checked) Or (Me.opbArrecacao.Enabled And Me.opbArrecacao.Checked), True, False)
			Me.dtpFinal.Enabled = Me.dtpInicio.Enabled
			Me.cmdExporta.Enabled = ablnModo
			Me.cmdArquivo.Enabled = ablnModo
			Me.cmdFechar.Enabled = ablnModo
			Me.chkGrupoA.Enabled = ablnModo
			Me.chkGrupoB.Enabled = ablnModo
			Me.txtArquivo.Enabled = ablnModo
			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 dtpInicio_ValueChanged(sender As Object, e As EventArgs) Handles dtpInicio.ValueChanged
		Me.dtpFinal.Value = UltimoDiaMes(Month(Me.dtpInicio.Value), Year(Me.dtpInicio.Value)) & "/" & Month(Me.dtpInicio.Value) & "/" & Year(Me.dtpInicio.Value)
		Call NomeArquivo()
	End Sub

	Private Sub dtpFinal_ValueChanged(sender As Object, e As EventArgs) Handles dtpFinal.ValueChanged
		Call NomeArquivo()
	End Sub
End Class