using System;



using System.Data;



using System.Data.SqlClient;



using System.Drawing;



using System.Windows.Forms;







namespace MesWork.Pages



{



    /// <summary>



    /// 工件管理页面 — 各机型参数维护（加油量/抽油量/密度）



    /// 对应存储过程：工件管理_查询、工件管理_增加、工件管理_编辑、工件管理_删除



    /// </summary>



    public partial class UC_WorkpieceMgmt : UserControl



    {



        private const string SEARCH_HINT = "输入机型号搜索...";



        private PagerBar _pager;







        public UC_WorkpieceMgmt()



        {



            InitializeComponent();



            InitColumns();



            _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 = 120 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "说明", HeaderText = "说明", DataPropertyName = "说明", FillWeight = 130 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "匹配规则", HeaderText = "匹配规则", DataPropertyName = "匹配规则", FillWeight = 120 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "优先级", HeaderText = "优先级", DataPropertyName = "优先级", FillWeight = 50 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "加油量", HeaderText = "加油量(L)", DataPropertyName = "加油量", FillWeight = 70 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "抽油量", HeaderText = "抽油量(L)", DataPropertyName = "抽油量", FillWeight = 70 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "密度", HeaderText = "密度(kg/L)", DataPropertyName = "密度", FillWeight = 70 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "残油量上限", HeaderText = "残油量上限(L)", DataPropertyName = "残油量上限", FillWeight = 70 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "残油量下限", HeaderText = "残油量下限(L)", DataPropertyName = "残油量下限", FillWeight = 70 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "创建时间", HeaderText = "创建时间", DataPropertyName = "创建时间", FillWeight = 100 });



            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "修改时间", HeaderText = "修改时间", DataPropertyName = "修改时间", FillWeight = 100 });



        }







        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) ShowEditDialog(dgv_Data.CurrentRow);



            else MessageBox.Show("请先选择一条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);



        }



        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); }







        /// <summary>



        /// 新增/修改弹窗



        /// </summary>



        private void ShowEditDialog(DataGridViewRow row)



        {



            bool isEdit = row != null;



            using (var dlg = CrudHelper.CreateEditDialog(isEdit ? "修改工件" : "新增工件", 500, 520))



            {



                int y = 20;



                var txtModel = CrudHelper.AddTextField(dlg, "机型号：", ref y, isEdit ? row.Cells["机型号"]?.Value?.ToString() : "", inputX: 170, inputWidth: 280);



                var txtDesc = CrudHelper.AddTextField(dlg, "说明：", ref y, isEdit ? row.Cells["说明"]?.Value?.ToString() : "", inputX: 170, inputWidth: 280);



                var txtMatchRule = CrudHelper.AddTextField(dlg, "匹配规则：", ref y, isEdit ? row.Cells["匹配规则"]?.Value?.ToString() : "", inputX: 170, inputWidth: 280);



                var txtPriority = CrudHelper.AddTextField(dlg, "优先级：", ref y, isEdit ? row.Cells["优先级"]?.Value?.ToString() : "0", inputX: 170, inputWidth: 280);



                var txtOilIn = CrudHelper.AddTextField(dlg, "加油量(L)：", ref y, isEdit ? row.Cells["加油量"]?.Value?.ToString() : "0", inputX: 170, inputWidth: 280);



                var txtOilOut = CrudHelper.AddTextField(dlg, "抽油量(L)：", ref y, isEdit ? row.Cells["抽油量"]?.Value?.ToString() : "0", inputX: 170, inputWidth: 280);



                var txtDensity = CrudHelper.AddTextField(dlg, "密度(kg/L)：", ref y, isEdit ? row.Cells["密度"]?.Value?.ToString() : "0.85", inputX: 170, inputWidth: 280);



                var txtOilMax = CrudHelper.AddTextField(dlg, "残油量上限(L)：", ref y, isEdit ? row.Cells["残油量上限"]?.Value?.ToString() : "0", inputX: 170, inputWidth: 280);



                var txtOilMin = CrudHelper.AddTextField(dlg, "残油量下限(L)：", ref y, isEdit ? row.Cells["残油量下限"]?.Value?.ToString() : "0", inputX: 170, inputWidth: 280);



                CrudHelper.AddDialogButtons(dlg, ref y);







                if (dlg.ShowDialog() == DialogResult.OK)



                {



                    try



                    {



                        if (!int.TryParse(txtPriority.Text.Trim(), out int priority))
                        {
                            MessageBox.Show("优先级必须是整数", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }



                        string sp = isEdit ? "工件管理_编辑" : "工件管理_增加";



                        var pList = new System.Collections.Generic.List<SqlParameter>



                        {



                            new SqlParameter("@机型号", txtModel.Text.Trim()),



                            new SqlParameter("@说明", txtDesc.Text.Trim()),



                            new SqlParameter("@匹配规则", txtMatchRule.Text.Trim()),



                            new SqlParameter("@优先级", priority),



                            new SqlParameter("@加油量", decimal.Parse(txtOilIn.Text)),



                            new SqlParameter("@抽油量", decimal.Parse(txtOilOut.Text)),



                            new SqlParameter("@密度", decimal.Parse(txtDensity.Text)),



                            new SqlParameter("@残油量上限", decimal.Parse(txtOilMax.Text)),



                            new SqlParameter("@残油量下限", decimal.Parse(txtOilMin.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}"); }



                }



            }



        }







        private void btn_Export_Click(object sender, EventArgs e)



        {



            CrudHelper.ExportToExcel("工件管理", "工件管理", () =>



            {



                string keyword = CrudHelper.GetSearchKeyword(txt_Search, SEARCH_HINT);



                var (pageCountParam, itemCountParam) = PagerBar.CreateOutputParams();



                var parms = new SqlParameter[]



                {



                    new SqlParameter("@机型号", keyword),



                    new SqlParameter("@PageCurrent", 1),



                    new SqlParameter("@PageSize", 9999999),



                    pageCountParam, itemCountParam



                };



                SqlOperation.ExecuteStoredProcedure("工件管理_分页查询", parms, out DataTable dt, out string err);



                return dt;



            }, dgv_Data.Rows.Count > 0);



        }







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



    }



}

