using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.Win32;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment;

namespace BDU.Tools
{
    public static class DataGridExportToExcel
    {
        public static DataTable DataGridToDataTable(DataGrid dataGrid)
        {
            DataTable dt = new DataTable();

            // 添加列（仅可见列）
            foreach (var column in dataGrid.Columns.Where(c => c.Visibility == Visibility.Visible))
            {
                dt.Columns.Add(column.Header.ToString());
            }

            // 提取数据
            foreach (var item in dataGrid.Items)
            {
                DataRow row = dt.NewRow();
                int colIndex = 0;

                foreach (var column in dataGrid.Columns.Where(c => c.Visibility == Visibility.Visible))
                {
                    if (column is DataGridBoundColumn boundColumn)
                    {
                        // 新增强型数据提取逻辑
                        row[colIndex] = GetBoundColumnValue(boundColumn, item);
                    }
                    else
                    {
                        // 其他列类型处理
                        row[colIndex] = GetCellContentValue(column, item);
                    }
                    colIndex++;
                    if (colIndex > dt.Columns.Count - 1)
                    {
                        break;
                    }
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

        private static string GetBoundColumnValue(DataGridBoundColumn column, object item)
        {
            try
            {
                // 获取绑定路径
                var bindingPath = (column.Binding as Binding)?.Path.Path;
                if (string.IsNullOrEmpty(bindingPath)) return "";

                // 支持嵌套属性（如 "Address.City"）
                var value = item;
                foreach (var prop in bindingPath.Split('.'))
                {
                    var propInfo = value?.GetType().GetProperty(prop);
                    value = propInfo?.GetValue(value);
                }

                return value?.ToString() ?? "";
            }
            catch
            {
                return "";
            }
        }

        private static string? GetCellContentValue(DataGridColumn column, object item)
        {
            // 备选方案：尝试通过UI元素获取内容
            try
            {
                var content = column.GetCellContent(item);
                return content switch
                {
                    TextBlock tb => tb.Text,
                    CheckBox cb => cb.IsChecked.ToString(),
                    ComboBox cmb => cmb.SelectedValue?.ToString(),
                    _ => content?.ToString() ?? ""
                };
            }
            catch
            {
                return "";
            }
        }

        private static string? OpenExcelSaveFileDialog(string? excelTitle = null)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel Files(*.xls)|*.xls|Excel Files(*.xlsx)|*.xlsx";
            saveFileDialog.Title = $"导出{excelTitle}为表格";
            saveFileDialog.ShowDialog();
            if (!string.IsNullOrEmpty(saveFileDialog.FileName))
            {
                return saveFileDialog.FileName;
            }
            else
            {
                return null;
            }
        }

        public static void ExportDataGridToExcel(DataGrid dataGrid, string? title = null)
        {
            try
            {
                string? filePath = OpenExcelSaveFileDialog(title);
                if (!string.IsNullOrEmpty(filePath))
                {
                    IWorkbook workbook = new HSSFWorkbook();
                    ISheet sheet = workbook.CreateSheet(title ?? "sheet1");
                    DataTable dataTable = DataGridToDataTable(dataGrid);
                    IRow headerRow = sheet.CreateRow(0);

                    // 创建可重用的单元格样式
                    ICellStyle headerStyle = workbook.CreateCellStyle();
                    headerStyle.VerticalAlignment = VerticalAlignment.Center;

                    // 创建数据单元格基础样式
                    ICellStyle dataCellStyle = workbook.CreateCellStyle();
                    dataCellStyle.VerticalAlignment = VerticalAlignment.Center;

                    // 创建带自动换行的样式
                    ICellStyle wrappedCellStyle = workbook.CreateCellStyle();
                    wrappedCellStyle.VerticalAlignment = VerticalAlignment.Center;
                    wrappedCellStyle.WrapText = true;

                    // 创建表头
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        ICell cell = headerRow.CreateCell(i);
                        cell.SetCellValue(dataTable.Columns[i].ColumnName);
                        cell.CellStyle = headerStyle;  // 重用表头样式
                    }

                    // 填充数据行
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        IRow row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dataTable.Columns.Count; j++)
                        {
                            ICell cell = row.CreateCell(j);
                            var value = dataTable.Rows[i][j]?.ToString() ?? string.Empty;
                            cell.SetCellValue(value);

                            // 根据内容决定使用哪种样式
                            if (value.Contains("\n"))
                            {
                                cell.CellStyle = wrappedCellStyle;  // 重用带换行的样式
                            }
                            else
                            {
                                cell.CellStyle = dataCellStyle;  // 重用基础样式
                            }
                        }
                    }

                    // 自动调整列宽
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }

                    // 保存文件
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        workbook.Write(fileStream);
                        MessageBox.Show($"{title}表格导出成功");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{title}表格导出失败：{ex.Message}");
            }
        }
    }
}
