using System;
using System.Windows.Forms;
using 全自动水压检测仪.DATA;
namespace 全自动水压检测仪
{
public partial class UserEditForm : Form
{
private UserRepository _userRepository;
private User _user;
private bool _isEditMode;
public UserEditForm() : this(null) { }
public UserEditForm(User user)
{
InitializeComponent();
_userRepository = new UserRepository();
_user = user;
_isEditMode = user != null;
InitializeFormData();
}
///
/// 初始化表单数据
///
private void InitializeFormData()
{
if (_isEditMode)
{
this.Text = "编辑用户";
txtUsername.Text = _user.Username;
txtUsername.ReadOnly = true; // 编辑模式不能修改用户名
txtPassword.Visible = false;
lblPassword.Visible = false;
cmbUserRole.SelectedIndex = _user.UserRole;
chkStatus.Checked = _user.Status == 1;
}
else
{
this.Text = "添加用户";
cmbUserRole.SelectedIndex = 0; // 默认为普通用户
chkStatus.Checked = true;
}
}
///
/// 保存按钮
///
private void btnSave_Click(object sender, EventArgs e)
{
string username = txtUsername.Text.Trim();
string password = txtPassword.Text;
int userRole = cmbUserRole.SelectedIndex;
int status = chkStatus.Checked ? 1 : 0;
// 验证
if (string.IsNullOrEmpty(username))
{
MessageBox.Show("请输入用户名!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtUsername.Focus();
return;
}
if (!_isEditMode && string.IsNullOrEmpty(password))
{
MessageBox.Show("请输入密码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtPassword.Focus();
return;
}
if (!_isEditMode && password.Length < 6)
{
MessageBox.Show("密码长度不能少于6位!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtPassword.Focus();
return;
}
try
{
if (_isEditMode)
{
// 编辑模式:更新用户信息
_user.Username = username;
_user.UserRole = userRole;
_user.Status = status;
if (_userRepository.UpdateUser(_user))
{
MessageBox.Show("用户信息更新成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("用户信息更新失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
// 添加模式:创建新用户
var newUser = new User
{
Username = username,
UserRole = userRole,
Status = status
};
if (_userRepository.CreateUser(newUser, password))
{
MessageBox.Show("用户创建成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("用户创建失败,用户名可能已存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"操作失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
///
/// 取消按钮
///
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
}