using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Commonlib
{
    public class ExcelHelper
    {
        public static DataTable ReadExcelToDataTable(string filePath)
        {
            DataTable dataTable = new DataTable();

            // 打开 Excel 文件
            IWorkbook workbook;
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                if (filePath.EndsWith(".xlsx"))
                    workbook = new XSSFWorkbook(fileStream); // 读取 .xlsx 文件
                else if (filePath.EndsWith(".xls"))
                    workbook = new HSSFWorkbook(fileStream); // 读取 .xls 文件
                else
                    throw new Exception("文件格式不支持，只支持 .xls 和 .xlsx");
            }

            // 读取第一个工作表
            var sheet = workbook.GetSheetAt(0);
            if (sheet == null)
                throw new Exception("工作表为空！");

            // 获取表头
            var headerRow = sheet.GetRow(0);
            if (headerRow == null)
                throw new Exception("未找到表头行！");

            for (int i = 0; i < headerRow.LastCellNum; i++)
            {
                var columnName = headerRow.GetCell(i)?.ToString() ?? $"Column{i}";
                dataTable.Columns.Add(columnName);
            }

            // 读取数据行
            for (int i = 1; i <= sheet.LastRowNum; i++) // 从第 1 行（索引为 1）开始读取
            {
                var row = sheet.GetRow(i);
                if (row == null) continue;

                var dataRow = dataTable.NewRow();
                for (int j = 0; j < row.LastCellNum; j++)
                {
                    var cell = row.GetCell(j);
                    dataRow[j] = cell != null ? GetCellValue(cell) : DBNull.Value;
                }
                dataTable.Rows.Add(dataRow);
            }

            return dataTable;
        }

        static object GetCellValue(ICell cell)
        {
            switch (cell.CellType)
            {
                case CellType.Numeric:
                    return DateUtil.IsCellDateFormatted(cell) ? cell.DateCellValue : cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Formula:
                    return cell.CellFormula;
                case CellType.Blank:
                    return string.Empty;
                default:
                    return cell.ToString();
            }
        }


        public static void CreateNewExcel(string filePath, DataTable dataTable)
        {
            IWorkbook workbook;
            if (filePath.EndsWith(".xlsx"))
                workbook = new XSSFWorkbook(); // 创建 .xlsx 文件
            else
                workbook = new HSSFWorkbook(); // 创建 .xls 文件

            var sheet = workbook.CreateSheet("销售订单");

            // 写入表头
            var headerRow = sheet.CreateRow(0);
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
            }

            // 写入数据
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
                }
            }

            // 设置列宽和行高
            SetColumnWidthAndRowHeight(workbook, 0, 0, 1);
            SetColumnWidthAndRowHeight(workbook, 0, 1, 1);
            SetColumnWidthAndRowHeight(workbook, 0, 2, 1);
            SetColumnWidthAndRowHeight(workbook, 0, 3, 1);
            SetColumnWidthAndRowHeight(workbook, 0, 4, 1);

            // 保存文件
            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }

        }


        public static void AppendExcel(string filepath)
        {
            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取流

            POIFSFileSystem ps = new POIFSFileSystem(fs);//需using NPOI.POIFS.FileSystem;
            IWorkbook workbook = new HSSFWorkbook(ps);
            ISheet sheet = workbook.GetSheetAt(0);//获取工作表
            IRow row = sheet.GetRow(0); //得到表头
            FileStream fout = new FileStream(filepath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流
            row = sheet.CreateRow((sheet.LastRowNum + 1));//在工作表中添加一行

            ICell cell1 = row.CreateCell(0);
            cell1.SetCellValue("测试数据");//赋值

            fout.Flush();
            workbook.Write(fout);//写入文件
            workbook = null;
            fout.Close();
        }
        public static void EncryptExcel(string path, string password)
        {
            // 创建HSSF格式工作簿（仅支持.xls）
            var workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet("Data");

            // 设置工作簿保护密码
            workbook.WriteProtectWorkbook(password, "owner");

            // 保存加密文件
            using (var fs = new FileStream(path, FileMode.Create))
            {
                workbook.Write(fs);
            }
        }


        public static void SetColumnWidthAndRowHeight(IWorkbook workbook, int sheetIndex, int columnIndex, int rowIndex)
        {
            var sheet = workbook.GetSheetAt(sheetIndex);

            // 设置列宽（单位是 1/256 字符宽度）
            sheet.SetColumnWidth(columnIndex, 30 * 256); // 设置第 1 列宽度为 20

            // 设置行高（单位是点数）
            var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
            row.HeightInPoints = 25; // 设置行高为 25 点
        }

        public void SetCellStyle(IWorkbook workbook, int sheetIndex, int rowIndex, int colIndex)
        {
            var sheet = workbook.GetSheetAt(sheetIndex);
            var cell = sheet.GetRow(rowIndex).GetCell(colIndex) ?? sheet.GetRow(rowIndex).CreateCell(colIndex);

            var style = workbook.CreateCellStyle();

            // 设置字体
            var font = workbook.CreateFont();
            font.FontHeightInPoints = 12;
            font.FontName = "Arial";
            font.IsBold = true;
            style.SetFont(font);

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            // 设置背景颜色
            style.FillForegroundColor = IndexedColors.LightBlue.Index;
            style.FillPattern = FillPattern.SolidForeground;

            cell.CellStyle = style;
            cell.SetCellValue("示例文本");
        }
        public void FullExample(string filePath, DataTable dataTable)
        {
            IWorkbook workbook = filePath.EndsWith(".xlsx") ? (IWorkbook)new XSSFWorkbook() : new HSSFWorkbook();
            var sheet = workbook.CreateSheet("Sheet1");

            // 设置表头
            var headerRow = sheet.CreateRow(0);
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
            }

            // 写入数据
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
                }
            }

            // 设置列宽和行高
            SetColumnWidthAndRowHeight(workbook, 0, 1, 1);


            // 设置单元格样式
            SetCellStyle(workbook, 0, 1, 1);

            // 保存文件
            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }
        }
    }
}
