Option Strict Off
Option Explicit On
Friend Class frmCadUsuario
	Inherits System.Windows.Forms.Form
	Dim istrSql As String
	Dim iblnNovo As Boolean
	
	Private Sub frmCadUsuario_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
		Me.cmdNovo.Enabled = True
		Me.cmdEditar.Enabled = False
		Me.cmdExcluir.Enabled = False
		
		Call SetJanelaDados(False)
		Call CarregaTabelaComboBox((Me.cmbGrupo), "`usuarios_grupos`", "`descricao`", "`id`", "`descricao` ASC")
		Call MontaGrid()
		Call EncheGrid()
		
		cmdNovo.Enabled = True
		cmdEditar.Enabled = False
		cmdExcluir.Enabled = False
	End Sub
	
	Private Sub frmCadUsuario_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 = System.Windows.Forms.Keys.Escape Then
			If fmeDados.Visible = True Then
				Call cmdCancelar_Click(cmdCancelar, New System.EventArgs())
			Else
				Call cmdFechar_Click(cmdFechar, New System.EventArgs())
			End If
		ElseIf KeyAscii = System.Windows.Forms.Keys.Return 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 MontaGrid()
		With Me.mfgDados
			Call .Clear()
			.Rows = 1
			.set_ColAlignment(1, 4)
			.set_ColAlignment(5, 4)
			.set_ColWidth(0, 0)
			.set_TextMatrix(0, 0, "Código")
			.set_ColWidth(1, 840)
			.set_TextMatrix(0, 1, "Matrícula")
			.set_ColWidth(2, 2800)
			.set_TextMatrix(0, 2, "Nome")
			.set_ColWidth(3, 1700)
			.set_TextMatrix(0, 3, "Usuário")
			.set_ColWidth(4, 2900)
			.set_TextMatrix(0, 4, "Grupo")
			.set_ColWidth(5, 2000)
		End With
	End Sub
	
	Private Sub EncheGrid()
		Dim llngIdU As Integer
		Dim lstrMat As String
		Dim lstrNom As String
		Dim lstrUsu As String
		Dim llngIdG As Integer
		Dim lstrNmG As String
		Dim lintIdx As Short
		Dim lblnOpc As Boolean
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		istrSql = ""
		istrSql = istrSql & "  SELECT `usuarios`.`id`, " & vbCrLf
		istrSql = istrSql & "         `usuarios`.`matricula`, " & vbCrLf
		istrSql = istrSql & "         `usuarios`.`nome`, " & vbCrLf
		istrSql = istrSql & "         `usuarios`.`usuario`, " & vbCrLf
		istrSql = istrSql & "         `usuarios`.`idgrupos`, " & vbCrLf
		istrSql = istrSql & "         `usuarios`.`opcao` " & vbCrLf
		istrSql = istrSql & "    FROM `usuarios` " & vbCrLf
		istrSql = istrSql & "ORDER BY `nome` ASC"
		Call Conectar(istrSql, lrstAux)
		With lrstAux
			If .State > 0 Then
				If .RecordCount > 0 Then
					While Not .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"'
						llngIdU = CInt(IIf(IsDbNull(.Fields("id").value), 0, .Fields("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"'
						lstrMat = Trim(CStr(IIf(IsDbNull(.Fields("matricula").value), "", .Fields("matricula").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"'
						lstrNom = Trim(CStr(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"'
						lstrUsu = Trim(CStr(IIf(IsDbNull(.Fields("usuario").value), "", .Fields("usuario").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"'
						llngIdG = CInt(IIf(IsDbNull(.Fields("idgrupos").value), 0, .Fields("idgrupos").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"'
						lblnOpc = (CInt(IIf(IsDbNull(.Fields("opcao").value), 0, .Fields("opcao").value)) = 1)
						With Me.mfgDados
							.Rows = .Rows + 1
							.set_TextMatrix(.Rows - 1, 0, llngIdU)
							.set_TextMatrix(.Rows - 1, 1, lstrMat)
							.set_TextMatrix(.Rows - 1, 2, lstrNom)
							.set_TextMatrix(.Rows - 1, 3, lstrUsu)
							With Me.cmbGrupo
								For lintIdx = 0 To .Items.Count - 1
									If VB6.GetItemData(Me.cmbGrupo, lintIdx) = llngIdG Then
										lstrNmG = VB6.GetItemString(Me.cmbGrupo, lintIdx)
										lintIdx = .Items.Count
									End If
								Next lintIdx
							End With
							.set_TextMatrix(.Rows - 1, 4, lstrNmG)
						End With
						Call .MoveNext()
					End While
				End If
				Call .Close()
			End If
		End With
		If mfgDados.Rows > 1 Then mfgDados.Row = 1
		'UPGRADE_NOTE: Object lrstAux 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"'
		lrstAux = Nothing
	End Sub
	
	Private Sub mfgDados_ClickEvent(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mfgDados.ClickEvent
		Me.cmdNovo.Enabled = True
		Me.cmdEditar.Enabled = True
		Me.cmdExcluir.Enabled = True
		
		If Me.mfgDados.Rows > 1 Then
			Call LocalizaUsuario()
		End If
	End Sub
	
	Private Sub LocalizaUsuario()
		Dim llngIdG As Integer
		Dim llngIdU As Integer
		Dim lintIdx As Short
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		
		Call LimpaCampos()
		iblnNovo = False
		llngIdU = CInt(Me.mfgDados.get_TextMatrix(Me.mfgDados.Row, 0))
		If llngIdU > 0 Then
			istrSql = ""
			istrSql = istrSql & "  SELECT `usuarios`.`id`, " & vbCrLf
			istrSql = istrSql & "         `usuarios`.`matricula`, " & vbCrLf
			istrSql = istrSql & "         `usuarios`.`nome`, " & vbCrLf
			istrSql = istrSql & "         `usuarios`.`usuario`, " & vbCrLf
			istrSql = istrSql & "         `usuarios`.`idgrupos`, " & vbCrLf
			istrSql = istrSql & "         `usuarios`.`opcao`, " & vbCrLf
			istrSql = istrSql & "         `usuarios`.`recman` " & vbCrLf
			istrSql = istrSql & "    FROM `usuarios` " & vbCrLf
			istrSql = istrSql & "   WHERE `usuarios`.`id` = " & llngIdU & " "
			Call Conectar(istrSql, lrstAux)
			With lrstAux
				If .State > 0 Then
					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.txtMatricula.Text = Trim(CStr(IIf(IsDbNull(.Fields("matricula").value), "", .Fields("matricula").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.txtNome.Text = Trim(CStr(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.txtUsuario.Text = Trim(CStr(IIf(IsDbNull(.Fields("usuario").value), "", .Fields("usuario").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"'
						llngIdG = CInt(IIf(IsDbNull(.Fields("idgrupos").value), 0, .Fields("idgrupos").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.chkOpcao.CheckState = IIf(IIf(IsDbNull(.Fields("opcao").value), 0, .Fields("opcao").value) = True, 1, 0)
						'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.chkRecManual.CheckState = IIf(IIf(IsDbNull(.Fields("recman").value), 0, .Fields("recman").value) = True, 1, 0)
						With Me.cmbGrupo
							For lintIdx = 0 To .Items.Count - 1
								If VB6.GetItemData(Me.cmbGrupo, lintIdx) = llngIdG Then
									.SelectedIndex = lintIdx
									lintIdx = .Items.Count
								End If
							Next lintIdx
						End With
					Else
						Call MsgBox("Não foi possível encontrar este registro!" & vbCrLf & vbCrLf & "Por favor, selecione outro registro e tente novamente!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
					End If
					Call .Close()
				Else
					Call MsgBox("Ocorreu um erro ao tentar carregar o registro!" & vbCrLf & vbCrLf & "Por favor, tente novamente!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
				End If
			End With
		Else
			Call MsgBox("Selecione um registro, por favor!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
		End If
		'UPGRADE_NOTE: Object lrstAux 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"'
		lrstAux = Nothing
	End Sub
	
	Private Sub LimpaCampos()
		Me.txtMatricula.Text = ""
		Me.txtNome.Text = ""
		Me.txtUsuario.Text = ""
		Me.txtSenha.Text = ""
		Me.txtConfirmaSenha.Text = ""
		Me.cmbGrupo.SelectedIndex = -1
	End Sub
	
	Private Sub SetJanelaDados(ByVal ablnAux As Boolean)
		Me.fmeDados.Visible = ablnAux
		Me.fmeDados.Enabled = ablnAux
		Me.mfgDados.Enabled = Not ablnAux
		Me.cmdNovo.Enabled = Not ablnAux
		Me.cmdEditar.Enabled = Not ablnAux
		Me.cmdFechar.Enabled = Not ablnAux
	End Sub
	
	Private Function checaDuplicidade(ByVal astrUsuario As String) As Boolean
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT 1 " & vbCrLf
		lstrSql = lstrSql & "  FROM `usuarios` " & vbCrLf
		lstrSql = lstrSql & " WHERE `usuarios`.`usuario` = '" & astrUsuario & "'"
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State > 0 Then
				If .RecordCount > 0 Then
					checaDuplicidade = True
				Else
					checaDuplicidade = False
				End If
				Call .Close()
			Else
				checaDuplicidade = False
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux 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"'
		lrstAux = Nothing
	End Function
	
	Private Sub mfgDados_DblClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mfgDados.DblClick
		If mfgDados.Rows > 1 Then Call cmdEditar_Click(cmdEditar, New System.EventArgs())
	End Sub
	
	Private Sub txtMatricula_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMatricula.Enter
		With Me.txtMatricula
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtNome_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtNome.Enter
		With Me.txtNome
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtUsuario_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtUsuario.Enter
		With Me.txtUsuario
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtSenha_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtSenha.Enter
		With Me.txtSenha
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub txtConfirmaSenha_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConfirmaSenha.Enter
		With Me.txtConfirmaSenha
			.SelectionStart = 0
			.SelectionLength = Len(.Text)
		End With
	End Sub
	
	Private Sub cmdNovo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdNovo.Click
		iblnNovo = True
		Call LimpaCampos()
		Call SetJanelaDados(True)
		Call Me.txtNome.Focus()
	End Sub
	
	Private Sub cmdEditar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdEditar.Click
		iblnNovo = False
		Call SetJanelaDados(True)
		Call Me.txtNome.Focus()
	End Sub
	
	Private Sub cmdExcluir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExcluir.Click
		Dim lblnAux As Boolean
		Dim llngIdU As Integer
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lblnAux = True
		llngIdU = CInt(Me.mfgDados.get_TextMatrix(Me.mfgDados.Row, 0))
		istrSql = ""
		istrSql = istrSql & "SELECT 1 "
		istrSql = istrSql & "  FROM `executor` "
		istrSql = istrSql & " WHERE `executor`.`idusuarios` = " & llngIdU
		Call Conectar(istrSql, lrstAux)
		With lrstAux
			If .State > 0 Then
				If .RecordCount > 0 Then
					Call MsgBox("Existe usuário não pode ser excluído, porque existe registro(s) no cadastro de executor desde usuário!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
					lblnAux = False
				End If
				Call .Close()
			End If
		End With
		If lblnAux Then
			If MsgBox("Esta operação não possui retorno!" & vbCrLf & vbCrLf & "Tem certeza de que deseja excluir o usuário selecionado?", MsgBoxStyle.YesNo + MsgBoxStyle.Question, "Excluir") = MsgBoxResult.Yes Then
				istrSql = ""
				istrSql = istrSql & "DELETE FROM `usuarios_permissao_menu` "
				istrSql = CStr(CDbl(istrSql & "      WHERE `usuarios_permissao_menu`.`idusuarios` ") = llngIdU)
				Call myConC.BeginTrans()
				Call Executar(istrSql)
				Call myConC.CommitTrans()
				istrSql = ""
				istrSql = istrSql & "DELETE FROM `usuarios` "
				istrSql = CStr(CDbl(istrSql & "      WHERE `usuarios`.`id` ") = llngIdU)
				Call myConC.BeginTrans()
				Call Executar(istrSql)
				Call myConC.CommitTrans()
				Call frmCadUsuario_Load(Me, New System.EventArgs())
			End If
		End If
	End Sub
	
	Private Sub cmdSalvar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSalvar.Click
		Dim llngIdU As Integer
		Dim lmd5Aux As clsMd5
		lmd5Aux = New clsMd5
		If Me.mfgDados.Rows > 1 Then
			llngIdU = CInt(Me.mfgDados.get_TextMatrix(Me.mfgDados.Row, 0))
		End If
		If Trim(Me.txtNome.Text) = "" Then
			Call MsgBox("Por favor, digite o nome completo do usuário!", MsgBoxStyle.Information, gstrTituloMensagem)
			Call Me.txtNome.Focus()
		Else
			If Trim(txtUsuario.Text) = "" Then
				Call MsgBox("Por favor, digite o nome de usuário!", MsgBoxStyle.Information, gstrTituloMensagem)
				Call Me.txtUsuario.Focus()
			Else
				If Me.cmbGrupo.SelectedIndex = -1 Then
					Call MsgBox("Por favor, selecione o grupo do usuário!", MsgBoxStyle.Information, gstrTituloMensagem)
					Call Me.cmbGrupo.Focus()
				Else
					If Me.txtSenha.Text <> Me.txtConfirmaSenha.Text Then
						Call MsgBox("As informações não puderam ser gravadas." & vbCrLf & vbCrLf & "A senha e a confirmação de senha estão diferentes. Por favor, digite novamente!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
						Call Me.txtSenha.Focus()
					Else
						istrSql = ""
						If iblnNovo = True Then
							istrSql = istrSql & "INSERT INTO `usuarios` SET "
						Else
							istrSql = istrSql & "     UPDATE `usuarios` SET "
						End If
						istrSql = istrSql & "            `matricula` = '" & Trim(Me.txtMatricula.Text) & "', "
						istrSql = istrSql & "            `nome`      = '" & Trim(Me.txtNome.Text) & "', "
						istrSql = istrSql & "            `usuario`   = '" & Trim(Me.txtUsuario.Text) & "', "
						If Len(Trim(Me.txtSenha.Text)) > 0 Then
							istrSql = istrSql & "            `senha`     = '" & LCase(lmd5Aux.DigestStrToHexStr(Trim(Me.txtSenha.Text))) & "', "
						End If
						istrSql = istrSql & "            `idgrupos`  = " & VB6.GetItemData(Me.cmbGrupo, Me.cmbGrupo.SelectedIndex) & ", "
						istrSql = istrSql & "            `opcao`     = " & Me.chkOpcao.CheckState & ", "
						istrSql = istrSql & "            `recman`    = " & Me.chkRecManual.CheckState & " "
						If iblnNovo = True Then
							If checaDuplicidade(Me.txtUsuario.Text) Then
								Call MsgBox("Este nome de usuário já está em uso." & vbCrLf & vbCrLf & "Por favor, digite um outro nome de usuário!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
								Call Me.txtUsuario.Focus()
								istrSql = ""
							End If
						Else
							istrSql = istrSql & "WHERE `id` = " & llngIdU & " "
						End If
						If Len(Trim(istrSql)) > 0 Then
							Call Executar(istrSql)
							Call frmCadUsuario_Load(Me, New System.EventArgs())
						End If
					End If
				End If
			End If
		End If
		'UPGRADE_NOTE: Object lmd5Aux 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"'
		lmd5Aux = Nothing
	End Sub
	
	Private Sub cmdCancelar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancelar.Click
		Call SetJanelaDados(False)
	End Sub
	
	Private Sub cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click
		Call Me.Close()
	End Sub
End Class