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

namespace MesWork.Pages
{
    /// <summary>
    /// 报告查询页面 — 历史称重数据检索与 Excel 导出
    /// 对应存储过程：称重记录_分页查询（使用 sp_xt_pagesplit 真分页）
    /// </summary>
    public partial class UC_Report : UserControl
    {
        private PagerBar _pager;

        public UC_Report()
        {
            InitializeComponent();
            InitColumns();
            dtp_Start.Value = DateTime.Today.AddDays(-7);
            dtp_End.Value = DateTime.Today;
            // 用PagerBar替换原始pnl_StatusBar
            _pager = new PagerBar();
            _pager.PageChanged += (s, e) => LoadData();
            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 = 80 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "订单号", HeaderText = "订货号", DataPropertyName = "订单号", FillWeight = 80 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "进站重量", HeaderText = "进站重量(KG)", DataPropertyName = "进站重量", FillWeight = 80 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "离站重量", HeaderText = "离站重量(KG)", DataPropertyName = "离站重量", FillWeight = 80 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "加油量", HeaderText = "加油量", DataPropertyName = "加油量", FillWeight = 60 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "抽油量", HeaderText = "抽油量", DataPropertyName = "抽油量", FillWeight = 60 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "放油量", HeaderText = "放油量", DataPropertyName = "放油量", FillWeight = 70 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "残留量", HeaderText = "残留量", DataPropertyName = "残留量", FillWeight = 60 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "残油量上下限", HeaderText = "残油量上下限", DataPropertyName = "残油量上下限", FillWeight = 90 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "油密度", HeaderText = "油密度", DataPropertyName = "油密度", FillWeight = 60 });
            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 });
        }

        /// <summary>
        /// 查询按钮：重置到第1页后查询
        /// </summary>
        private void btn_Query_Click(object sender, EventArgs e)
        {
            _pager.ResetPage();
            LoadData();
        }

        /// <summary>
        /// 核心查询方法
        /// </summary>
        private void LoadData()
        {
            try
            {
                var (pageCountParam, itemCountParam) = PagerBar.CreateOutputParams();
                var parms = new SqlParameter[]
                {
                    new SqlParameter("@发动机号", txt_EngineNo.Text.Trim()),
                    new SqlParameter("@机型号", txt_ModelNo.Text.Trim()),
                    new SqlParameter("@开始时间", dtp_Start.Value.ToString("yyyy-MM-dd")),
                    new SqlParameter("@结束时间", dtp_End.Value.AddDays(1).ToString("yyyy-MM-dd")),
                    new SqlParameter("@PageCurrent", _pager.CurrentPage),
                    new SqlParameter("@PageSize", _pager.PageSize),
                    pageCountParam,
                    itemCountParam
                };
                SqlOperation.ExecuteStoredProcedure("称重记录_分页查询", parms, out DataTable dt, out string err);
                if (dt != null)
                {
                    AddResidualOilLimitColumn(dt);
                    dgv_Data.DataSource = dt;
                }
                _pager.UpdateState(pageCountParam, itemCountParam);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 将残油量上下限合并为报表显示列。
        /// </summary>
        private void AddResidualOilLimitColumn(DataTable dt)
        {
            if (!dt.Columns.Contains("残油量上下限"))
            {
                dt.Columns.Add("残油量上下限", typeof(string));
            }
            if (dt.Columns.Contains("残留量"))
            {
                dt.Columns["残油量上下限"].SetOrdinal(dt.Columns["残留量"].Ordinal + 1);
            }

            foreach (DataRow row in dt.Rows)
            {
                row["残油量上下限"] = $"{FormatLimit(row, "残油量下限")}~{FormatLimit(row, "残油量上限")}";
            }
        }

        private string FormatLimit(DataRow row, string columnName)
        {
            if (!row.Table.Columns.Contains(columnName) || row[columnName] == DBNull.Value)
            {
                return "";
            }

            if (decimal.TryParse(row[columnName].ToString(), out decimal value))
            {
                return value.ToString("0.###");
            }

            return row[columnName].ToString();
        }

        private void RemoveHiddenExportColumns(DataTable dt)
        {
            string[] hiddenColumns = { "称重类型", "托盘号", "残油量上限", "残油量下限" };
            foreach (string columnName in hiddenColumns)
            {
                if (dt.Columns.Contains(columnName))
                {
                    dt.Columns.Remove(columnName);
                }
            }
        }

        /// <summary>
        /// 导出 Excel（重新查询全量数据后导出）
        /// </summary>
        private void btn_Export_Click(object sender, EventArgs e)
        {
            if (dgv_Data.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出，请先查询", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            using (var sfd = new SaveFileDialog())
            {
                sfd.Filter = "Excel 文件|*.xlsx";
                sfd.FileName = $"称重报告_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 用当前查询条件重新查询全量数据（不受分页限制）
                        var (pageCountParam, itemCountParam) = PagerBar.CreateOutputParams();
                        var parms = new SqlParameter[]
                        {
                            new SqlParameter("@发动机号", txt_EngineNo.Text.Trim()),
                            new SqlParameter("@机型号", txt_ModelNo.Text.Trim()),
                            new SqlParameter("@开始时间", dtp_Start.Value.ToString("yyyy-MM-dd")),
                            new SqlParameter("@结束时间", dtp_End.Value.AddDays(1).ToString("yyyy-MM-dd")),
                            new SqlParameter("@PageCurrent", 1),
                            new SqlParameter("@PageSize", 9999999),
                            pageCountParam,
                            itemCountParam
                        };
                        SqlOperation.ExecuteStoredProcedure("称重记录_分页查询", parms, out DataTable dt, out string err);

                        if (dt != null && dt.Rows.Count > 0)
                        {
                            AddResidualOilLimitColumn(dt);
                            RemoveHiddenExportColumns(dt);
                            bool exported = NPOITest.ExeclHelper.DataTableToExcel(dt, "称重记录", sfd.FileName);
                            if (exported)
                            {
                                MessageBox.Show($"导出成功！共 {dt.Rows.Count} 条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{sfd.FileName}\"");
                            }
                            else
                            {
                                MessageBox.Show("导出失败，请检查文件是否被占用", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("查询全量数据失败，请重试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
