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

namespace MesWork.Pages
{
    /// <summary>
    /// 过站记录查询页面 — 每个产品经过每个工位的明细记录
    /// 对应存储过程：过站记录_分页查询
    /// </summary>
    public partial class UC_StationRecord : UserControl
    {
        private PagerBar _pager;

        public UC_StationRecord()
        {
            InitializeComponent();
            InitColumns();
            dtp_Start.Value = DateTime.Today.AddDays(-7);
            dtp_End.Value = DateTime.Today;
            _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);
        }

        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 = 70 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "工单号", HeaderText = "订货号", DataPropertyName = "工单号", FillWeight = 80 });
            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 = 110,
                DefaultCellStyle = new DataGridViewCellStyle { Format = "yyyy/MM/dd HH:mm:ss" } });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "离站时间", HeaderText = "离开时间", DataPropertyName = "离站时间", FillWeight = 110,
                DefaultCellStyle = new DataGridViewCellStyle { Format = "yyyy/MM/dd HH:mm:ss" } });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "停站时间", HeaderText = "在位(秒)", DataPropertyName = "停站时间", FillWeight = 55 });
            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 = 60 });
            dgv_Data.Columns.Add(new DataGridViewTextBoxColumn { Name = "操作者", HeaderText = "操作员", DataPropertyName = "操作者", FillWeight = 60 });
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            _pager.ResetPage();
            LoadData();
        }

        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) dgv_Data.DataSource = dt;
                _pager.UpdateState(pageCountParam, itemCountParam);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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