using BDU.Tools;
using ATS_DBContext;
using ATS_DBContext.Models;
using ClosedXML.Excel;
using MahApps.Metro.Controls;
using Microsoft.Win32;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace BDU.Windows
{
    [AddINotifyPropertyChangedInterface]
    public partial class TestDataInfomationWindow : MetroWindow
    {
        public ObservableCollection<DataModel> DataList { get; set; } = [];

        public string Search_ParaName { get; set; }

        public string Search_Result { get; set; }

        public bool Search_IsUseTime { get; set; } = true;

        public DateTime Search_StartTime { get; set; } = DateTime.Now.Date;

        public DateTime Search_EndTime { get; set; } = DateTime.Now.AddDays(1).Date;

        public TestDataInfomationWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Search_Click(sender, e);
        }

        private void GroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left) DragMove();
        }

        private async void Search_Click(object sender, RoutedEventArgs e)
        {
            await Task.Run(() =>
            {
                using (ATS_DB db = new())
                {
                    // 始终过滤ProgramID
                    IQueryable<DataModel> query = db.TestData.Where(x => x.ProgramID == MainWindow.Instance.Program.ID);

                    // 参数名称搜索
                    if (!string.IsNullOrEmpty(Search_ParaName))
                    {
                        // 获取匹配的参数ID列表
                        var paramIds = MainWindow.Instance.Program.Parameters.Where(p => p.Name.Contains(Search_ParaName)).Select(p => p.ID).ToList();
                        query = query.Where(x => paramIds.Contains(x.ParameterID));
                    }

                    // 测试结果筛选
                    if (!string.IsNullOrEmpty(Search_Result))
                    {
                        if (Search_Result == "PASS")
                        {
                            query = query.Where(x => x.Result);
                        }
                        if (Search_Result == "FAIL")
                        {
                            query = query.Where(x => !x.Result);
                        }
                    }

                    // 时间范围过滤
                    if (Search_IsUseTime)
                    {
                        query = query.Where(x => x.InsertTime >= Search_StartTime && x.InsertTime < Search_EndTime);
                    }

                    List<DataModel>? results = query.OrderByDescending(x => x.InsertTime).ToList();
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        DataList = new(results);
                    });
                }
            });
        }

        private void TestDataWindow_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    Search_Click(sender, e);
                    break;
            }
        }

        private async void Export_Click(object sender, RoutedEventArgs e)
        {
            // 检查是否有数据可导出
            if (DataList == null || DataList.Count == 0)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            // 显示保存文件对话框
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel文件|*.xlsx",
                FileName = $"测试数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx",
                Title = "导出测试数据"
            };

            if (saveFileDialog.ShowDialog() != true)
                return;

            string filePath = saveFileDialog.FileName;

            try
            {
                // 异步执行导出操作
                await Task.Run(() => ExportToExcel(filePath));

                MessageBox.Show($"测试数据导出成功", "导出成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExportToExcel(string filePath)
        {
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("测试数据");

                // 添加标题行
                worksheet.Cell(1, 1).Value = "参数名称";
                worksheet.Cell(1, 2).Value = "实际值";
                worksheet.Cell(1, 3).Value = "下限值";
                worksheet.Cell(1, 4).Value = "上限值";
                worksheet.Cell(1, 5).Value = "测试结果";
                worksheet.Cell(1, 6).Value = "测试时间";

                // 设置标题行样式
                var titleRow = worksheet.Row(1);
                titleRow.Style.Font.Bold = true;
                titleRow.Style.Fill.BackgroundColor = XLColor.LightGray;

                // 填充数据
                int row = 2;
                foreach (var item in DataList)
                {
                    // 转换参数ID为参数名称
                    string parameterName = "未知参数";
                    var parameter = MainWindow.Instance.Program.Parameters.FirstOrDefault(p => p.ID == item.ParameterID);
                    if (parameter != null)
                    {
                        parameterName = parameter.Name;
                    }

                    worksheet.Cell(row, 1).Value = parameterName;
                    worksheet.Cell(row, 2).Value = item.Value;
                    worksheet.Cell(row, 3).Value = item.LowerLimit;
                    worksheet.Cell(row, 4).Value = item.UpperLimit;
                    worksheet.Cell(row, 5).Value = item.Result ? "PASS" : "FAIL";
                    worksheet.Cell(row, 6).Value = item.InsertTime;

                    row++;
                }

                // 调整列宽
                worksheet.Columns().AdjustToContents();

                // 保存文件
                workbook.SaveAs(filePath);
            }
        }
    }
}