using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using 全自动水压检测仪.DATA;

namespace 全自动水压检测仪
{
    public partial class UserManagerForm : Form
    {
        private UserRepository _userRepository;
        private List<User> _users;

        public UserManagerForm()
        {
            InitializeComponent();
            _userRepository = new UserRepository();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void UserManagerForm_Load(object sender, EventArgs e)
        {
            LoadUsers();
        }

        /// <summary>
        /// 加载用户列表
        /// </summary>
        private void LoadUsers()
        {
            try
            {
                _users = _userRepository.GetAllUsers();

                // 配置 DataGridView 列
                dgvUsers.Columns.Clear();
                dgvUsers.AutoGenerateColumns = false;

                dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "Id",
                    HeaderText = "ID",
                    Visible = false
                });

                dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "Username",
                    HeaderText = "用户名"
                });

                dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "UserRole",
                    HeaderText = "角色"
                });

                dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "Status",
                    HeaderText = "状态"
                });

                dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "CreateTime",
                    HeaderText = "创建时间",
                    DefaultCellStyle = new DataGridViewCellStyle { Format = "yyyy-MM-dd HH:mm:ss" }
                });

                dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "LastLoginTime",
                    HeaderText = "最后登录时间",
                    DefaultCellStyle = new DataGridViewCellStyle { Format = "yyyy-MM-dd HH:mm:ss", NullValue = "" }
                });

                // 绑定数据
                var displayData = _users.Select(u => new
                {
                    u.Id,
                    u.Username,
                    UserRole = u.UserRole == 1 ? "管理员" : "普通用户",
                    Status = u.Status == 1 ? "启用" : "禁用",
                    u.CreateTime,
                    LastLoginTime = u.LastLoginTime.HasValue ? u.LastLoginTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                }).ToList();

                dgvUsers.DataSource = displayData;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载用户列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 添加用户按钮
        /// </summary>
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            var addUserForm = new UserEditForm();
            if (addUserForm.ShowDialog() == DialogResult.OK)
            {
                LoadUsers();
                MessageBox.Show("用户添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 编辑用户按钮
        /// </summary>
        private void btnEditUser_Click(object sender, EventArgs e)
        {
            if (dgvUsers.CurrentRow == null)
            {
                MessageBox.Show("请先选择要编辑的用户！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int userId = Convert.ToInt32(dgvUsers.CurrentRow.Cells[0].Value);
            User selectedUser = _userRepository.GetUserById(userId);

            if (selectedUser == null)
            {
                MessageBox.Show("未找到用户信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var editUserForm = new UserEditForm(selectedUser);

            if (editUserForm.ShowDialog() == DialogResult.OK)
            {
                LoadUsers();
                MessageBox.Show("用户信息更新成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 删除用户按钮
        /// </summary>
        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            if (dgvUsers.CurrentRow == null)
            {
                MessageBox.Show("请先选择要删除的用户！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int userId = Convert.ToInt32(dgvUsers.CurrentRow.Cells[0].Value);
            string username = dgvUsers.CurrentRow.Cells[1].Value.ToString();

            if (userId == LoginData.CurrentUserId)
            {
                MessageBox.Show("不能删除当前登录的用户！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (MessageBox.Show($"确定要删除用户 {username} 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    if (_userRepository.DeleteUser(userId))
                    {
                        LoadUsers();
                        MessageBox.Show("用户删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("用户删除失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除用户失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 重置密码按钮
        /// </summary>
        private void btnResetPassword_Click(object sender, EventArgs e)
        {
            if (dgvUsers.CurrentRow == null)
            {
                MessageBox.Show("请先选择要重置密码的用户！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int userId = Convert.ToInt32(dgvUsers.CurrentRow.Cells[0].Value);
            string username = dgvUsers.CurrentRow.Cells[1].Value.ToString();

            string newPassword = string.Empty;

            using (var inputForm = new Form())
            {
                inputForm.Text = "重置密码";
                inputForm.FormBorderStyle = FormBorderStyle.FixedDialog;
                inputForm.StartPosition = FormStartPosition.CenterScreen;
                inputForm.Size = new System.Drawing.Size(300, 150);

                var label = new Label
                {
                    Text = $"请输入 {username} 的新密码：",
                    Location = new System.Drawing.Point(10, 10),
                    Size = new System.Drawing.Size(280, 20)
                };

                var textBox = new TextBox
                {
                    Location = new System.Drawing.Point(10, 35),
                    Size = new System.Drawing.Size(260, 25),
                    PasswordChar = '*'
                };

                var btnOk = new Button
                {
                    Text = "确定",
                    DialogResult = DialogResult.OK,
                    Location = new System.Drawing.Point(70, 70),
                    Size = new System.Drawing.Size(80, 30)
                };

                var btnCancel = new Button
                {
                    Text = "取消",
                    DialogResult = DialogResult.Cancel,
                    Location = new System.Drawing.Point(160, 70),
                    Size = new System.Drawing.Size(80, 30)
                };

                inputForm.Controls.AddRange(new Control[] { label, textBox, btnOk, btnCancel });
                inputForm.AcceptButton = btnOk;
                inputForm.CancelButton = btnCancel;

                if (inputForm.ShowDialog() == DialogResult.OK)
                {
                    newPassword = textBox.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(newPassword) || newPassword.Length < 6)
            {
                MessageBox.Show("密码长度不能少于6位！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                if (_userRepository.ResetPassword(userId, newPassword))
                {
                    MessageBox.Show("密码重置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("密码重置失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置密码失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新按钮
        /// </summary>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadUsers();
        }

        /// <summary>
        /// 表格行点击事件
        /// </summary>
        private void dgvUsers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex < dgvUsers.Rows.Count)
            {
                dgvUsers.Rows[e.RowIndex].Selected = true;
            }
        }
    }
}
