using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

namespace MesWork.Pages
{
    /// <summary>
    /// 用户管理页面 — CRUD 操作
    /// 对应存储过程：用户管理_查询、用户管理_增加、用户管理_编辑、用户管理_删除
    /// </summary>
    public partial class UC_UserMgmt : UserControl
    {
        private const string SEARCH_HINT = "输入姓名搜索...";
        private PagerBar _pager;

        public UC_UserMgmt()
        {
            InitializeComponent();
            InitColumns();
            // 用PagerBar替换原始pnl_StatusBar
            _pager = new PagerBar();
            _pager.PageChanged += (s, e) => LoadData(txt_Search.Text == SEARCH_HINT ? "" : txt_Search.Text.Trim());
            this.Controls.Remove(pnl_StatusBar);
            this.Controls.Add(_pager);
            this.Controls.SetChildIndex(_pager, this.Controls.Count - 2);
        }

        /// <summary>
        /// 预设表格列（工号/密码/姓名/性别/权限/创建时间/修改时间）
        /// </summary>
        private void InitColumns()
        {
            dgv_Data.AutoGenerateColumns = false;
            dgv_Data.Columns.Clear();
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "ID", HeaderText = "ID", DataPropertyName = "ID", Visible = false });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "用户名", HeaderText = "工号", DataPropertyName = "用户名", FillWeight = 100 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "姓名", HeaderText = "姓名", DataPropertyName = "姓名", FillWeight = 100 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "性别", HeaderText = "性别", DataPropertyName = "性别", FillWeight = 50 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "权限", HeaderText = "权限", DataPropertyName = "权限", FillWeight = 60 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "创建时间", HeaderText = "创建时间", DataPropertyName = "创建时间", FillWeight = 100 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "修改时间", HeaderText = "修改时间", DataPropertyName = "修改时间", FillWeight = 100 });
        }

        // ====================================================================
        // 数据加载 — SP: 用户管理_查询(@姓名)
        // ====================================================================

        public void LoadData(string keyword = "")
        {
            try
            {
                var (pageCountParam, itemCountParam) = PagerBar.CreateOutputParams();
                var parms = new SqlParameter[]
                {
                    new SqlParameter("@姓名", keyword ?? ""),
                    new SqlParameter("@PageCurrent", _pager.CurrentPage),
                    new SqlParameter("@PageSize", _pager.PageSize),
                    pageCountParam,
                    itemCountParam
                };
                SqlOperation.ExecuteStoredProcedure("用户管理_分页查询", parms, out DataTable dt, out string err);
                if (dt != null) dgv_Data.DataSource = dt;
                _pager.UpdateState(pageCountParam, itemCountParam);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // ====================================================================
        // 搜索框交互
        // ====================================================================

        private void txt_Search_GotFocus(object sender, EventArgs e)
        {
            CrudHelper.SearchBox_GotFocus(txt_Search, SEARCH_HINT);
        }

        private void txt_Search_LostFocus(object sender, EventArgs e)
        {
            CrudHelper.SearchBox_LostFocus(txt_Search, SEARCH_HINT);
        }

        private void txt_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (CrudHelper.SearchBox_KeyDown(e)) btn_Search_Click(sender, e);
        }

        // ====================================================================
        // 按钮事件
        // ====================================================================

        private void btn_Search_Click(object sender, EventArgs e) { _pager.ResetPage(); LoadData(txt_Search.Text == SEARCH_HINT ? "" : txt_Search.Text.Trim()); }
        private void btn_Add_Click(object sender, EventArgs e) => ShowEditDialog(null);
        private void btn_Edit_Click(object sender, EventArgs e)
        {
            if (dgv_Data.CurrentRow == null) { MessageBox.Show("请先选择一条记录", "提示"); return; }
            ShowEditDialog(dgv_Data.CurrentRow);
        }

        /// <summary>
        /// 删除 — SP: 用户管理_删除(@ID)
        /// </summary>
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if (dgv_Data.CurrentRow == null) { MessageBox.Show("请先选择一条记录", "提示"); return; }
            string name = dgv_Data.CurrentRow.Cells["姓名"]?.Value?.ToString() ?? "";
            if (MessageBox.Show($"确认删除用户「{name}」？", "确认删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                try
                {
                    var parms = new SqlParameter[] { new SqlParameter("@ID", int.Parse(dgv_Data.CurrentRow.Cells["ID"]?.Value?.ToString() ?? "0")) };
                    SqlOperation.ExecuteStoredProcedure("用户管理_删除", parms, out string err);
                    LoadData();
                }
                catch (Exception ex) { MessageBox.Show($"删除失败：{ex.Message}"); }
            }
        }

        private void btn_Refresh_Click(object sender, EventArgs e) { _pager.ResetPage(); LoadData(""); }
        private void dgv_Data_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) btn_Edit_Click(sender, e); }

        // ====================================================================
        // 编辑弹窗 — SP: 用户管理_增加 / 用户管理_编辑
        // ====================================================================

        private void ShowEditDialog(DataGridViewRow row)
        {
            bool isEdit = row != null;
            using (var dlg = CrudHelper.CreateEditDialog(isEdit ? "修改用户" : "新增用户", 420, 380))
            {
                int y = 20;
                var txtJobNo = CrudHelper.AddTextField(dlg, "工号：", ref y, isEdit ? row.Cells["用户名"]?.Value?.ToString() : "", inputX: 110, inputWidth: 260);
                var txtPwd = CrudHelper.AddTextField(dlg, "密码：", ref y, "", inputX: 110, inputWidth: 260, isPassword: true);
                var txtName = CrudHelper.AddTextField(dlg, "姓名：", ref y, isEdit ? row.Cells["姓名"]?.Value?.ToString() : "", inputX: 110, inputWidth: 260);
                var cmbGender = CrudHelper.AddComboField(dlg, "性别：", ref y, new[] { "男", "女" }, isEdit ? row.Cells["性别"]?.Value?.ToString() : "男", inputX: 110, inputWidth: 260);
                var cmbPerm = CrudHelper.AddComboField(dlg, "权限：", ref y, new[] { "管理", "操作", "查看" }, isEdit ? row.Cells["权限"]?.Value?.ToString() : "操作", inputX: 110, inputWidth: 260);
                CrudHelper.AddDialogButtons(dlg, ref y);

                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        string sp = isEdit ? "用户管理_编辑" : "用户管理_增加";
                        var pList = new System.Collections.Generic.List<SqlParameter>
                        {
                            new SqlParameter("@用户名", txtJobNo.Text.Trim()),
                            new SqlParameter("@密码", txtPwd.Text),
                            new SqlParameter("@姓名", txtName.Text.Trim()),
                            new SqlParameter("@性别", cmbGender.Text),
                            new SqlParameter("@权限", cmbPerm.Text)
                        };
                        if (isEdit) pList.Insert(0, new SqlParameter("@ID", int.Parse(row.Cells["ID"]?.Value?.ToString() ?? "0")));
                        SqlOperation.ExecuteStoredProcedure(sp, pList.ToArray(), out string err);
                        LoadData();
                    }
                    catch (Exception ex) { MessageBox.Show($"保存失败：{ex.Message}"); }
                }
            }
        }

        protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); if (Visible && dgv_Data.DataSource == null) LoadData(); }
    }
}
