using Modbus.Device;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 全自动水压检测仪.Data;
using 材料热传导系数;

namespace 全自动水压检测仪
{
    public partial class Report : UIForm
    {
        public List<ConductivityTestData> CurrentReport { get; set; }
        Function ma;
        private DataGridView dataGridView;
        private Button btnExport;
        private Button btnReturn;
        private Button btnDelete;
        private ConductivityRepository _repository;
        public Report()
        {
            InitializeComponent();
            SetupFormStyle();
            CreateDataGridView();
            CreateButtons();
            this.SuspendLayout();
            this.ClientSize = new System.Drawing.Size(1000, 600);
            this.Name = "ReportForm";
            this.Text = "测试数据报表";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);

        }

        public Report(List<ConductivityTestData> CurrentReport)
        {
            InitializeComponent();
            SetupFormStyle();
            CreateDataGridView();
            CreateButtons();
            this.SuspendLayout();
            this.ClientSize = new System.Drawing.Size(1000, 600);
            this.Name = "ReportForm";
            this.Text = "测试数据报表";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.CurrentReport = CurrentReport;
            _repository = new ConductivityRepository();
        }

        /// <summary>
        /// 设置窗体基础样式
        /// </summary>
        private void SetupFormStyle()
        {
            this.BackColor = SystemColors.Control; // 使用系统默认窗体背景色
            this.Font = new Font("Microsoft YaHei", 9F, FontStyle.Regular, GraphicsUnit.Point);
        }

        /// <summary>
        /// 创建数据表格
        /// </summary>
        private void CreateDataGridView()
        {
            // 初始化DataGridView
            dataGridView = new DataGridView();
            dataGridView.Dock = DockStyle.Fill;
            dataGridView.Margin = new Padding(10);
            dataGridView.BackgroundColor = this.BackColor;
            dataGridView.BorderStyle = BorderStyle.None;
            dataGridView.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
            dataGridView.GridColor = Color.LightGray;

            // 禁止排序、编辑、添加行
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridView.AllowUserToOrderColumns = false;
            dataGridView.AllowUserToResizeRows = false;
            dataGridView.ReadOnly = true;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            // 设置表头样式
            dataGridView.ColumnHeadersHeight = 40;
            dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.LightSkyBlue;
            dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
            dataGridView.ColumnHeadersDefaultCellStyle.Font = new Font(this.Font, FontStyle.Bold);
            dataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

            // 设置单元格样式
            dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView.DefaultCellStyle.Font = this.Font;
            dataGridView.DefaultCellStyle.BackColor = Color.White;
            dataGridView.DefaultCellStyle.SelectionBackColor = Color.LightSteelBlue;
            dataGridView.DefaultCellStyle.SelectionForeColor = Color.Black;

            dataGridView.AutoGenerateColumns = false;
            // 创建列
            CreateGridColumns();

            // 添加到窗体
            this.Controls.Add(dataGridView);
        }

        /// <summary>
        /// 创建表格列 - 修改为绑定数据源
        /// </summary>
        private void CreateGridColumns()
        {
            dataGridView.Columns.Clear();
            dataGridView.ScrollBars = ScrollBars.Both;


            var config = ConfigurationManager.AppSettings;
            if (config["AllowModified"]?.ToString() == "1")
            {
                // ============ 添加编辑按钮列（放在第一列） ============
                DataGridViewButtonColumn editColumn = new DataGridViewButtonColumn
                {
                    Name = "EditColumn",
                    HeaderText = "操作",
                    Text = "保存",
                    UseColumnTextForButtonValue = true,
                    Width = 60,
                    SortMode = DataGridViewColumnSortMode.NotSortable,
                    DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
                };
                dataGridView.Columns.Add(editColumn);
            }

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Id",
                HeaderText = "编号",
                Width = 50,
                DataPropertyName = "Id",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
            });


            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Id",
                HeaderText = "序号",
                Width = 50,
                DataPropertyName = "row", // 绑定到ConductivityTestData的Id属性
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "lldh",
                HeaderText = "联络单号",
                Width = 140,
                DataPropertyName = "lldh",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "jh",
                HeaderText = "件号",
                Width = 120,
                DataPropertyName = "jh",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
            });


            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "kzh",
                HeaderText = "刻字号",
                Width = 80,
                DataPropertyName = "kzh",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,

                }
            });


            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "quantity",
                HeaderText = "数量",
                Width = 50,
                DataPropertyName = "quantity",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,

                }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "startpressure",
                HeaderText = "初始压力(PSI)",
                Width = 95,
                DataPropertyName = "StartPressure",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "F2" // 保留2位小数
                }
            });


            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "starttime",
                HeaderText = "开始时间",
                Width = 170,
                DataPropertyName = "starttime",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "yyyy-MM-dd HH:mm:ss" // 设置日期格式
                }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "endtime",
                HeaderText = "结束时间",
                Width = 170,
                DataPropertyName = "endtime",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "yyyy-MM-dd HH:mm:ss" // 设置日期格式
                }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "endpressure",
                HeaderText = "结束压力(PSI)",
                Width = 95,
                DataPropertyName = "EndPressure",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "F2"
                }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "dwelltime",
                HeaderText = "保压时间(min)",
                Width = 80,
                DataPropertyName = "DwellTime",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "F1" // 保留1位小数
                }
            });


            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "diffpressure",
                HeaderText = "压差(PSI)",
                Width = 75,
                DataPropertyName = "DiffPressure",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "F2"
                }
            });

            DataGridViewTextBoxColumn temperatureColumn = CreateTemperatureModeColumn();
            dataGridView.Columns.Add(temperatureColumn);

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "temperature",
                HeaderText = "温度",
                Width = 75,
                DataPropertyName = "temperature",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "F2"
                }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "standarderror",
                HeaderText = "标准差值(PSI)",
                Width = 95,
                DataPropertyName = "standarderror",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "F2"
                }
            });

            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "testresult",
                HeaderText = "测试结果",
                Width = 75,
                DataPropertyName = "testresult",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,

                }
            });


            dataGridView.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "CreateTime",
                HeaderText = "时间日期",
                Width = 170,
                DataPropertyName = "CreateTime",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = {
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    Format = "yyyy-MM-dd HH:mm:ss" // 设置日期格式
                }
            });














        }
        /// <summary>
        /// 创建按钮
        /// </summary>
        private void CreateButtons()
        {
            // 按钮容器面板
            Panel btnPanel = new Panel();
            btnPanel.Dock = DockStyle.Bottom;
            btnPanel.Height = 60;
            btnPanel.BackColor = this.BackColor;
            btnPanel.Padding = new Padding(20, 10, 20, 10);

            // 导出报表按钮
            btnExport = new Button
            {
                Text = "导出报表",
                Width = 100,
                Height = 35,
                Font = new Font(this.Font, FontStyle.Regular),
                BackColor = Color.LightSteelBlue,
                FlatStyle = FlatStyle.Flat,
                FlatAppearance = { BorderSize = 1, BorderColor = Color.SteelBlue },
                Left = 20,
                Top = 10,
            };
            btnExport.Click += BtnExport_Click;
            btnExport.Cursor = Cursors.Hand;

            // 返回按钮
            btnReturn = new Button
            {
                Text = "返回",
                Width = 100,
                Height = 35,
                Font = new Font(this.Font, FontStyle.Regular),
                BackColor = Color.LightSteelBlue,
                FlatStyle = FlatStyle.Flat,
                FlatAppearance = { BorderSize = 1, BorderColor = Color.SteelBlue },
                Left = btnExport.Right + 20,
                Top = 10,
            };
            btnReturn.Click += BtnReturn_Click;
            btnReturn.Cursor = Cursors.Hand;




            // 导出报表按钮
            btnDelete = new Button
            {
                Text = "一键清除",
                Width = 100,
                Height = 35,
                Font = new Font(this.Font, FontStyle.Regular),
                BackColor = Color.LightSteelBlue,
                FlatStyle = FlatStyle.Flat,
                FlatAppearance = { BorderSize = 1, BorderColor = Color.SteelBlue },
                Left = 260,
                Top = 10,
            };
            btnDelete.Click += BtnDelete_Click;
            btnDelete.Cursor = Cursors.Hand;




            btnPanel.Controls.Add(btnDelete);
            btnPanel.Controls.Add(btnExport);
            btnPanel.Controls.Add(btnReturn);


            this.Controls.Add(btnPanel);

            btnPanel.BringToFront();
        }

        private DataGridViewTextBoxColumn CreateTemperatureModeColumn()
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn
            {
                Name = "Type",
                HeaderText = "温度模式",
                Width = 100,
                DataPropertyName = "Type",
                SortMode = DataGridViewColumnSortMode.NotSortable,
                DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
            };

            // 添加单元格格式化事件
            dataGridView.CellFormatting += DataGridView_CellFormatting;

            return column;
        }

        /// <summary>
        /// 在导出报表时也需要转换
        /// </summary>
        private string GetTemperatureModeDisplay(int type)
        {
            switch (type)
            {
                case 1:
                    return "常温";
                case 0:
                    return "高温";
                default:
                    return "未知";
            }
        }
        // 单元格格式化事件
        private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 只处理温度模式列
            if (e.ColumnIndex == dataGridView.Columns["Type"].Index && e.RowIndex >= 0)
            {
                if (e.Value != null)
                {
                    string typeValue = e.Value.ToString();

                    // 根据Type值转换显示文本
                    switch (typeValue)
                    {
                        case "1":
                            e.Value = "常温";
                            break;
                        case "0":
                            e.Value = "高温";
                            break;
                        case "常温":
                        case "高温":
                            // 已经是转换后的值，保持不变
                            break;
                        default:
                            e.Value = "未知";
                            break;
                    }

                    e.FormattingApplied = true;
                }
            }
        }

        //private void Report_Load(object sender, EventArgs e)
        //{
        //    // 检查数据源
        //    //if (CurrentReport == null || CurrentReport.Count == 0)
        //    //{
        //    //    MessageBox.Show("没有测试数据可显示", "提示",
        //    //        MessageBoxButtons.OK, MessageBoxIcon.Information);
        //    //    return;
        //    //}

        //    try
        //    {
        //        dataGridView.CellFormatting += DataGridView_CellFormatting;



        //        var result = _repository.GetTestData();
        //        if (result != null && result.Count > 0)
        //        {
        //            CurrentReport = result;
        //        }
        //        int i = 0;
        //        CurrentReport.ForEach(x =>
        //        {
        //            i++;
        //            x.Id = i;
        //        });
        //        dataGridView.DataSource = CurrentReport;

        //        // 刷新显示
        //        dataGridView.Refresh();

        //        this.Text = $"测试数据报表（共{CurrentReport.Count}条记录）";
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"加载数据失败：{ex.Message}", "错误",
        //            MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //}
        private void Report_Load(object sender, EventArgs e)
        {
            try
            {
                dataGridView.CellFormatting += DataGridView_CellFormatting;

                // ============ 启用DataGridView编辑功能 ============
                dataGridView.ReadOnly = false;
                dataGridView.AllowUserToAddRows = false;
                dataGridView.EditMode = DataGridViewEditMode.EditOnEnter;

                // 确保除了Id列和编辑按钮列外都可编辑
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    if (column.Name != "Id" && column.Name != "EditColumn")
                    {
                        column.ReadOnly = false;
                    }
                }
                // ============ 结束设置 ============

                var result = _repository.GetTestData();
                if (result != null && result.Count > 0)
                {
                    CurrentReport = result;
                }
                int i = 0;
                CurrentReport.ForEach(x =>
                {
                    i++;
                    x.row = i;
                });
                dataGridView.DataSource = CurrentReport;

                // 刷新显示
                dataGridView.Refresh();

                this.Text = $"测试数据报表（共{CurrentReport.Count}条记录）";

                // ============ 添加编辑按钮点击事件 ============
                dataGridView.CellClick -= DataGridViewCellClickHandler; // 先移除避免重复
                dataGridView.CellClick += DataGridViewCellClickHandler;
                // ============ 结束添加 ============
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 编辑按钮点击事件处理
        private void DataGridViewCellClickHandler(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是编辑按钮列
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 &&
                dataGridView.Columns[e.ColumnIndex].Name == "EditColumn")
            {
                try
                {
                    // 结束当前单元格的编辑
                    dataGridView.EndEdit();

                    // 获取当前行的数据
                    var row = dataGridView.Rows[e.RowIndex];

                    // 验证必要字段
                    if (row.Cells["jh"].Value == null || string.IsNullOrEmpty(row.Cells["jh"].Value.ToString()))
                    {
                        MessageBox.Show("件号不能为空！", "验证错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 从数据库获取原始数据（通过Id）
                    int id = Convert.ToInt32(row.Cells["Id"].Value);
                    var originalData = _repository.GetTestDataById(id);

                    if (originalData == null)
                    {
                        MessageBox.Show("未找到对应的测试数据！", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 更新数据
                    originalData.lldh = row.Cells["lldh"].Value?.ToString() ?? "";
                    originalData.jh = row.Cells["jh"].Value?.ToString() ?? "";
                    originalData.kzh = row.Cells["kzh"].Value?.ToString() ?? "";

                    // 数值类型（带验证）
                    if (row.Cells["quantity"].Value != null && !string.IsNullOrEmpty(row.Cells["quantity"].Value.ToString()))
                        originalData.quantity = Convert.ToInt32(row.Cells["quantity"].Value);

                    if (row.Cells["startpressure"].Value != null && !string.IsNullOrEmpty(row.Cells["startpressure"].Value.ToString()))
                        originalData.startpressure = Convert.ToDouble(row.Cells["startpressure"].Value);

                    if (row.Cells["endpressure"].Value != null && !string.IsNullOrEmpty(row.Cells["endpressure"].Value.ToString()))
                        originalData.endpressure = Convert.ToDouble(row.Cells["endpressure"].Value);

                    if (row.Cells["dwelltime"].Value != null && !string.IsNullOrEmpty(row.Cells["dwelltime"].Value.ToString()))
                        originalData.dwelltime = Convert.ToDouble(row.Cells["dwelltime"].Value);

                    if (row.Cells["diffpressure"].Value != null && !string.IsNullOrEmpty(row.Cells["diffpressure"].Value.ToString()))
                        originalData.diffpressure = Convert.ToDouble(row.Cells["diffpressure"].Value);

                    if (row.Cells["temperature"].Value != null && !string.IsNullOrEmpty(row.Cells["temperature"].Value.ToString()))
                        originalData.temperature = Convert.ToDouble(row.Cells["temperature"].Value);

                    if (row.Cells["standarderror"].Value != null && !string.IsNullOrEmpty(row.Cells["standarderror"].Value.ToString()))
                        originalData.standarderror = Convert.ToDecimal(row.Cells["standarderror"].Value);

                    originalData.testresult = row.Cells["testresult"].Value?.ToString() ?? "";

                    // 类型转换
                    string typeValue = row.Cells["Type"].Value?.ToString() ?? "";
                    if (typeValue == "常温")
                        originalData.Type = 1;
                    else if (typeValue == "高温")
                        originalData.Type = 0;

                    // 保存到数据库
                    _repository.UpdateTestData(originalData);

                    MessageBox.Show("修改已保存！", "成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 刷新数据（可选）
                    // var result = _repository.GetTestData();
                    // CurrentReport = result;
                    // dataGridView.DataSource = CurrentReport;
                }
                catch (FormatException)
                {
                    MessageBox.Show("数值格式错误，请检查输入的数据！", "格式错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存失败：{ex.Message}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        /// <summary>
        /// 导出报表按钮点击事件
        /// </summary>
        private void BtnExport_Click(object sender, EventArgs e)
        {
            ExportReport();
        }

        /// <summary>
        /// 返回按钮点击事件
        /// </summary>
        private void BtnReturn_Click(object sender, EventArgs e)
        {
            ReturnToMain();
        }

        /// <summary>
        /// 返回按钮点击事件
        /// </summary>
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            DialogResult ask = MessageBox.Show("此操作会清空所有历史数据,请先导出？",
                "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (ask == DialogResult.Yes)
            {
                CurrentReport.Clear();
                dataGridView.DataSource = new List<ConductivityTestData>();
                _repository.DeleteTestAllItems();


                // 刷新显示
                dataGridView.Refresh();
            }
        }




        /// <summary>
        /// 导出报表功能
        /// </summary>
        private void ExportReport()
        {
            //if (CurrentReport == null || CurrentReport.Count == 0)
            //{
            //    MessageBox.Show("没有数据可以导出", "提示",
            //        MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "CSV文件|*.csv|Excel文件|*.xlsx|文本文件|*.txt";
                saveFileDialog.Title = "导出报表";
                saveFileDialog.FileName = $"测试报表_{DateTime.Now:yyyyMMdd_HHmmss}";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveFileDialog.FileName;


                    //switch (Path.GetExtension(filePath).ToLower())
                    //{
                    //case ".csv":
                    //    ExportToCsv(filePath);
                    //    break;
                    //case ".txt":
                    //    ExportToTxt(filePath);
                    //    break;
                    //case ".xlsx":
                    ExportToExcel(filePath);
                    //        break;
                    //    default:
                    //        ExportToCsv(filePath);
                    //        break;
                    //}

                    MessageBox.Show($"报表已成功导出到：\n{filePath}", "导出成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出报表失败：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 导出为Excel文件（简单实现）
        /// </summary>
        //private void ExportToExcel(string filePath)
        //{
        //    using (var package = new ExcelPackage())
        //    {
        //        var worksheet = package.Workbook.Worksheets.Add("测试数据报表");

        //        // 设置默认样式
        //        worksheet.Cells.Style.Font.Name = "微软雅黑";
        //        worksheet.Cells.Style.Font.Size = 11;

        //        int currentRow = 1;

        //        // 主标题
        //        worksheet.Cells[currentRow, 1, currentRow, 9].Merge = true;
        //        var titleCell = worksheet.Cells[currentRow, 1];
        //        titleCell.Value = "测试数据报表";
        //        titleCell.Style.Font.Size = 16;
        //        titleCell.Style.Font.Bold = true;
        //        titleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        //        titleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

        //        currentRow++;

        //        // 副标题
        //        worksheet.Cells[currentRow, 1, currentRow, 9].Merge = true;
        //        var subTitleCell = worksheet.Cells[currentRow, 1];
        //        subTitleCell.Value = $"生成时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss} | 记录数量：{CurrentReport.Count}条";
        //        subTitleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        //        subTitleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

        //        currentRow += 2;

        //        // 表头
        //        string[] headers = { "编号", "联络单号", "件号", "刻字号", "数量", "初始压力(PSI)", "开始时间", "结束时间", "结束压力(PSI)", "保压时间(h)", "压差(PSI)", "温度模式", "温度", "标准差值(PSI)", "测试结果", "时间日期" };

        //        for (int i = 0; i < headers.Length; i++)
        //        {
        //            var cell = worksheet.Cells[currentRow, i + 1];
        //            cell.Value = headers[i];
        //            cell.Style.Font.Bold = true;
        //            cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        //            cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
        //            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
        //            cell.Style.Fill.BackgroundColor.SetColor(Color.LightSkyBlue);
        //            cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);

        //            // 设置列宽
        //            worksheet.Column(i + 1).Width = 15;
        //        }

        //        // 设置表头行高
        //        worksheet.Row(currentRow).Height = 35;

        //        currentRow++;

        //        // 数据行
        //        foreach (var data in CurrentReport)
        //        {
        //            string tempMode = GetTemperatureModeDisplay(data.Type);

        //            worksheet.Cells[currentRow, 1].Value = data.Id;
        //            worksheet.Cells[currentRow, 2].Value = data.lldh ?? "";
        //            worksheet.Cells[currentRow, 3].Value = data.jh ?? "";

        //            worksheet.Cells[currentRow, 4].Value = data.kzh ?? "";
        //            worksheet.Cells[currentRow, 5].Value = data.quantity;
        //            worksheet.Cells[currentRow, 6].Value = data.startpressure;




        //            worksheet.Cells[currentRow, 7].Value = data.starttime;
        //            worksheet.Cells[currentRow, 8].Value = data.endtime;

        //            worksheet.Cells[currentRow, 9].Value = data.endpressure;
        //            worksheet.Cells[currentRow, 10].Value = data.dwelltime;

        //            worksheet.Cells[currentRow, 11].Value = data.diffpressure;
        //            worksheet.Cells[currentRow, 12].Value = tempMode;
        //            worksheet.Cells[currentRow, 13].Value = data.temperature;
        //            worksheet.Cells[currentRow, 14].Value = data.standarderror;
        //            worksheet.Cells[currentRow, 15].Value = data.testresult;

        //            worksheet.Cells[currentRow, 16].Value = data.CreateTime;


        //            // 设置数据行样式
        //            for (int col = 1; col <= 9; col++)
        //            {
        //                var cell = worksheet.Cells[currentRow, col];
        //                cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        //                cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
        //                cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.LightGray);

        //                // 隔行变色
        //                if (currentRow % 2 == 0)
        //                {
        //                    cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
        //                    cell.Style.Fill.BackgroundColor.SetColor(Color.AliceBlue);
        //                }
        //            }

        //            // 设置格式
        //            worksheet.Cells[currentRow, 4].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
        //            worksheet.Cells[currentRow, 5].Style.Numberformat.Format = "0.00";
        //            worksheet.Cells[currentRow, 6].Style.Numberformat.Format = "0.00";
        //            worksheet.Cells[currentRow, 7].Style.Numberformat.Format = "0.00";
        //            worksheet.Cells[currentRow, 8].Style.Numberformat.Format = "0.0";

        //            // 设置行高
        //            worksheet.Row(currentRow).Height = 25;

        //            currentRow++;
        //        }

        //        // 自动调整列宽
        //        worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

        //        // 保存
        //        package.SaveAs(new FileInfo(filePath));
        //    }
        //}

        private void ExportToExcel(string filePath)
        {
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("测试数据报表");

                // 设置默认样式
                worksheet.Cells.Style.Font.Name = "微软雅黑";
                worksheet.Cells.Style.Font.Size = 10;
                worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                int currentRow = 1;

                // 主标题
                worksheet.Cells[currentRow, 1, currentRow, 16].Merge = true;
                var titleCell = worksheet.Cells[currentRow, 1];
                titleCell.Value = "测试数据报表";
                titleCell.Style.Font.Size = 16;
                titleCell.Style.Font.Bold = true;
                titleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                titleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                worksheet.Row(currentRow).Height = 30;

                currentRow++;

                // 副标题
                worksheet.Cells[currentRow, 1, currentRow, 16].Merge = true;
                var subTitleCell = worksheet.Cells[currentRow, 1];
                subTitleCell.Value = $"生成时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss} | 记录数量：{CurrentReport.Count}条";
                subTitleCell.Style.Font.Size = 11;
                subTitleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                subTitleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                worksheet.Row(currentRow).Height = 25;

                currentRow += 2; // 增加空行间距

                // 表头
                string[] headers = { "编号", "联络单号", "件号", "刻字号", "数量", "初始压力(PSI)", "开始时间", "结束时间", "结束压力(PSI)", "保压时间(min)", "压差(PSI)", "温度模式", "温度", "标准差值(PSI)", "测试结果", "创建时间" };

                // 设置表头
                for (int i = 0; i < headers.Length; i++)
                {
                    var cell = worksheet.Cells[currentRow, i + 1];
                    cell.Value = headers[i];
                    cell.Style.Font.Bold = true;
                    cell.Style.Font.Size = 11;
                    cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    cell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(91, 155, 213)); // 更专业的蓝色
                    cell.Style.Font.Color.SetColor(Color.White);
                    cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.FromArgb(217, 217, 217));

                    // 设置列宽（根据内容调整）
                    int columnWidth = 12;
                    switch (headers[i])
                    {
                        case "联络单号":
                        case "开始时间":
                        case "结束时间":
                        case "创建时间":
                            columnWidth = 18;
                            break;
                        case "刻字号":
                            columnWidth = 15;
                            break;
                        case "测试结果":
                            columnWidth = 10;
                            break;
                        case "温度模式":
                            columnWidth = 12;
                            break;
                    }
                    worksheet.Column(i + 1).Width = columnWidth;
                }

                // 设置表头行高
                worksheet.Row(currentRow).Height = 30;

                currentRow++;

                // 数据行
                foreach (var data in CurrentReport)
                {
                    string tempMode = GetTemperatureModeDisplay(data.Type);

                    // 数据赋值
                    worksheet.Cells[currentRow, 1].Value = data.Id;
                    worksheet.Cells[currentRow, 2].Value = data.lldh ?? "";
                    worksheet.Cells[currentRow, 3].Value = data.jh ?? "";
                    worksheet.Cells[currentRow, 4].Value = data.kzh ?? "";
                    worksheet.Cells[currentRow, 5].Value = data.quantity;
                    worksheet.Cells[currentRow, 6].Value = data.startpressure;

                    // 修复时间格式 - 使用正确的日期时间格式
                    if (data.starttime != null)
                    {
                        worksheet.Cells[currentRow, 7].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
                        worksheet.Cells[currentRow, 7].Value = data.starttime;
                    }

                    if (data.endtime != null)
                    {
                        worksheet.Cells[currentRow, 8].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
                        worksheet.Cells[currentRow, 8].Value = data.endtime;
                    }

                    worksheet.Cells[currentRow, 9].Value = data.endpressure;
                    worksheet.Cells[currentRow, 10].Value = data.dwelltime;
                    worksheet.Cells[currentRow, 11].Value = data.diffpressure;
                    worksheet.Cells[currentRow, 12].Value = tempMode;
                    worksheet.Cells[currentRow, 13].Value = data.temperature;
                    worksheet.Cells[currentRow, 14].Value = data.standarderror;
                    worksheet.Cells[currentRow, 15].Value = data.testresult;

                    // 创建时间格式
                    if (data.CreateTime != null)
                    {
                        worksheet.Cells[currentRow, 16].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
                        worksheet.Cells[currentRow, 16].Value = data.CreateTime;
                    }

                    // 设置整行样式
                    for (int col = 1; col <= 16; col++)
                    {
                        var cell = worksheet.Cells[currentRow, col];
                        cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.FromArgb(217, 217, 217));

                        // 隔行变色
                        if (currentRow % 2 == 0)
                        {
                            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                            cell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(248, 250, 252)); // 更柔和的蓝色背景
                        }
                        else
                        {
                            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                            cell.Style.Fill.BackgroundColor.SetColor(Color.White);
                        }
                    }

                    // 设置数值格式（修正之前的格式设置错误）
                    if (data.quantity != null)
                        worksheet.Cells[currentRow, 5].Style.Numberformat.Format = "0";

                    if (data.startpressure != null)
                        worksheet.Cells[currentRow, 6].Style.Numberformat.Format = "0.00";

                    if (data.endpressure != null)
                        worksheet.Cells[currentRow, 9].Style.Numberformat.Format = "0.00";

                    if (data.dwelltime != null)
                        worksheet.Cells[currentRow, 10].Style.Numberformat.Format = "0.0";

                    if (data.diffpressure != null)
                        worksheet.Cells[currentRow, 11].Style.Numberformat.Format = "0.00";

                    if (data.temperature != null)
                        worksheet.Cells[currentRow, 13].Style.Numberformat.Format = "0.0";

                    if (data.standarderror != null)
                        worksheet.Cells[currentRow, 14].Style.Numberformat.Format = "0.00";

                    // 设置数据行高
                    worksheet.Row(currentRow).Height = 22;

                    currentRow++;
                }

                // 添加底部空行
                currentRow++;
                worksheet.Cells[currentRow, 1, currentRow, 16].Merge = true;
                worksheet.Cells[currentRow, 1].Value = "--- 报告结束 ---";
                worksheet.Cells[currentRow, 1].Style.Font.Italic = true;
                worksheet.Cells[currentRow, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                worksheet.Cells[currentRow, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                worksheet.Row(currentRow).Height = 25;

                // 设置整体边框
                var dataRange = worksheet.Cells[3, 1, currentRow - 1, 16];
                dataRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                dataRange.Style.Border.Top.Color.SetColor(Color.FromArgb(217, 217, 217));
                dataRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                dataRange.Style.Border.Bottom.Color.SetColor(Color.FromArgb(217, 217, 217));
                dataRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                dataRange.Style.Border.Left.Color.SetColor(Color.FromArgb(217, 217, 217));
                dataRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                dataRange.Style.Border.Right.Color.SetColor(Color.FromArgb(217, 217, 217));

                // 自动调整列宽（在设置固定宽度后微调）
                worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(5, 20); // 最小5，最大20

                // 保存
                package.SaveAs(new FileInfo(filePath));
            }
        }

        /// <summary>
        /// 返回主界面
        /// </summary>
        private void ReturnToMain()
        {

            this.Close();

        }

        private void Report_FormClosing(object sender, FormClosingEventArgs e)
        {
            //base.OnFormClosing(e);
            dataGridView.CellFormatting -= DataGridView_CellFormatting;
            dataGridView.CellClick -= DataGridViewCellClickHandler; // 移除事件
        }
    }
}
