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

namespace MesWork.Pages
{
    /// <summary>
    /// 工具标定页面 — 固定维护OP10/OP20重量标定公式。
    /// 对应存储过程：工具管理_分页查询、工具管理_编辑
    /// </summary>
    public partial class UC_ToolMgmt : UserControl
    {
        private const string SEARCH_HINT = "输入工位号或工具名称搜索...";
        private PagerBar _pager;

        public UC_ToolMgmt()
        {
            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);
            btn_Add.Visible = false;
            btn_Delete.Visible = false;
            btn_Edit.Location = btn_Delete.Location;
        }

        /// <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 = 70 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "工具名称", HeaderText = "工具名称", DataPropertyName = "工具名称", FillWeight = 120 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "重量标定", HeaderText = "重量标定", DataPropertyName = "重量标定", FillWeight = 90 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "计算公式", HeaderText = "计算公式", DataPropertyName = "计算公式", FillWeight = 150 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "说明", HeaderText = "说明", DataPropertyName = "说明", FillWeight = 180 });
            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) { }
        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) { }
        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)
        {
            if (row == null) return;

            using (var dlg = CrudHelper.CreateEditDialog("修改工具标定", 520, 360))
            {
                int y = 20;
                var txtStation = CrudHelper.AddTextField(dlg, "工位号：", ref y, row.Cells["工位号"]?.Value?.ToString(), inputWidth: 320);
                txtStation.ReadOnly = true;
                txtStation.BackColor = Color.FromArgb(245, 247, 250);
                var txtName = CrudHelper.AddTextField(dlg, "工具名称：", ref y, row.Cells["工具名称"]?.Value?.ToString(), inputWidth: 320);
                var txtCalVal = CrudHelper.AddTextField(dlg, "重量标定：", ref y, row.Cells["重量标定"]?.Value?.ToString(), inputWidth: 320);
                var txtFormula = CrudHelper.AddTextField(dlg, "计算公式：", ref y, row.Cells["计算公式"]?.Value?.ToString(), inputWidth: 320);
                var txtDesc = CrudHelper.AddTextField(dlg, "说明：", ref y, row.Cells["说明"]?.Value?.ToString(), inputWidth: 320);
                CrudHelper.AddDialogButtons(dlg, ref y);

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (!WeightCalibrationHelper.ValidateFormula(txtFormula.Text.Trim(), out string formulaMsg))
                        {
                            MessageBox.Show(formulaMsg, "公式错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        var pList = new System.Collections.Generic.List<SqlParameter>
                        {
                            new SqlParameter("@ID", int.Parse(row.Cells["ID"]?.Value?.ToString() ?? "0")),
                            new SqlParameter("@工位号", txtStation.Text.Trim()),
                            new SqlParameter("@工具名称", txtName.Text.Trim()),
                            new SqlParameter("@重量标定", txtCalVal.Text.Trim()),
                            new SqlParameter("@计算公式", txtFormula.Text.Trim()),
                            new SqlParameter("@说明", txtDesc.Text.Trim()),
                        };
                        SqlOperation.ExecuteStoredProcedure("工具管理_编辑", pList.ToArray(), out string err);
                        WeightCalibrationHelper.ClearCache();
                        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(); }
    }
}
