using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Localization;
using MS.Common.IDCode;
using MS.Component.Jwt.UserClaim;
using MS.DbContexts;
using MS.Entities;
using MS.Entities.AuthService_Models;
using MS.Entities.Core;
using MS.Entities.Enum;
using MS.Entities.Models;
using MS.Models;
using MS.Models.ViewModel;
using MS.UnitOfWork;
using MS.WebCore.Core;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace MS.Services.PosTrxService
{
    public class PosTrxService : BaseService, IPosTrxService
    {
        Expression<Func<PosTrxLineItems, bool>> whereClause;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly JsonSerializerOptions _jsonSerializerOptions;
        public PosTrxService(IUnitOfWork<MSDbContext> unitOfWork, IMapper mapper, IdWorker idWorker, IClaimsAccessor claimsAccessor, IStringLocalizer localizer, IHttpContextAccessor httpContextAccessor, IUnitOfWork<AccountingContext> AccountingContext, IUnitOfWork<SQLiteContext> SQLiteContext, IUnitOfWork<AuthContext> AuthContext) : base(unitOfWork, mapper, idWorker, claimsAccessor, localizer, AccountingContext, SQLiteContext, AuthContext)
        {
            _httpContextAccessor = httpContextAccessor;
            _jsonSerializerOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true // 根据需要进行配置
            };
        }
        public async Task<ExecuteResult> NozzleTotalizerShiftReportAsync(string startTime,
                                                         string endTime,
                                                         string currentBuId)
        {
            ExecuteResult<NozzleTotalizerDto> result = new ExecuteResult<NozzleTotalizerDto>();
            Guid _currentBuId = new Guid(currentBuId);
            DateTime _startTime = DateTime.Parse(startTime);
            DateTime _endTime = DateTime.Parse(endTime);
            try
            {
                var nozzleTotalizers = new List<NozzleTotalizerDto>();
                nozzleTotalizers = await NozzleAsync(startTime, endTime, currentBuId);
                result.SetData(nozzleTotalizers);
            }
            catch (Exception ex)
            {
                ExecuteResult result_ = new ExecuteResult();
                result_.Message = ex.ToString();
                return result_;
            }
            return result;
        }
        public async Task<List<NozzleTotalizerDto>> NozzleAsync(string startTime,
                                                         string endTime,
                                                         string currentBuId)
        {
            Guid _currentBuId = new Guid(currentBuId);
            DateTime _startTime = DateTime.Parse(startTime);
            DateTime _endTime = DateTime.Parse(endTime);

            //调用业务方法TargetBusinessUnitId .GetAllAsync()
            var shiftsQuery = await _unitOfWork.GetRepository<PosTrxes>().GetAllAsync(x => x.TargetBusinessUnitId == _currentBuId &&
                             x.TransactionType == 6);

            var query = _unitOfWork.GetRepository<PosTrxLineItems>().FromSql(string.Format(@"SELECT
  p.*
FROM
  ""PosTrxLineItems"" AS p
  INNER JOIN ""PosTrxes"" AS p0 ON p.""PosTrxId"" = p0.""Id""
WHERE
  (
    (
      (
        (
          p0.""TargetBusinessUnitId"" = '{0}'
        )
        AND (p.""FuelItemSoldOnPumpNozzleId"" IS NOT NULL)
      )
      AND (p0.""TransactionStatus"" = 1)
    )
    AND NOT (p.""Voided"")
  )
  AND NOT (p.""IsDeleted"")", _currentBuId));

            var totalizerQuery = query.Where(_ => _.FuelItemPumpTotalizerVolume != null &&
                                                          _.FuelItemPumpTotalizerVolume != -1);
            var tostartTime = _startTime.AddDays(-90);
            var toendTime = _endTime.AddDays(-90);
            var startTotalizers = await totalizerQuery
              .Where(_ => _.PosTrx.CreatedDateTime <= _startTime && _.PosTrx.CreatedDateTime >= toendTime)
              .GroupBy(_ => new { _.FuelItemSoldOnPumpNozzleId })
              .Select(_ => new
              {
                  nozzleId = _.Key.FuelItemSoldOnPumpNozzleId
                  ,
                  totalizer = _.Max(i => i.FuelItemPumpTotalizerVolume)
              })
              .OrderBy(_ => _.nozzleId)
               .AsNoTracking()
              .ToListAsync();

            var endTotalizers = await totalizerQuery
.Where(_ => _.PosTrx.CreatedDateTime <= _endTime && _.PosTrx.CreatedDateTime >= toendTime)
.GroupBy(_ => new { _.FuelItemSoldOnPumpNozzleId })
.Select(_ => new
{
    nozzleId = _.Key.FuelItemSoldOnPumpNozzleId
  ,
    totalizer = _.Max(i => i.FuelItemPumpTotalizerVolume)
})
.OrderBy(_ => _.nozzleId)
.AsNoTracking()
.ToListAsync();

            //合并
            //var startTotalizers = await query
            //.Where(_ => _.FuelItemPumpTotalizerVolume != null &&
            //_.FuelItemPumpTotalizerVolume != -1 &&
            //_.PosTrx.CreatedDateTime <= DateTime.Parse("2023-04-09 05:45:34") &&
            //_.PosTrx.CreatedDateTime >= DateTime.Parse("2023-01-10 05:45:34").AddDays(-90))
            //.Include(x => x.PosTrx)
            //.GroupBy( a=> new { a.FuelItemSoldOnPumpNozzleId })
            //.Select( _ => new
            //{
            //    nozzleId = _.Key.FuelItemSoldOnPumpNozzleId,
            //    totalizer = _.Max(i => i.FuelItemPumpTotalizerVolume)
            //})
            //.OrderBy( _=> _.nozzleId)
            //.AsNoTracking()
            //.ToListAsync();
            //result.SetData(row);

            Expression<Func<PosTrxLineItems, bool>> where = null;
            var trxQuery = _unitOfWork.GetRepository<PosTrxLineItems>().FromSql(string.Format(@"		SELECT p.*
FROM ""PosTrxLineItems"" AS p
INNER JOIN ""PosTrxes"" AS p0
    ON p.""PosTrxId"" = p0.""Id""
WHERE ((((((p0.""TargetBusinessUnitId"" = '{0}')
        AND (p.""FuelItemSoldOnPumpNozzleId"" IS NOT NULL))
        AND (p0.""TransactionStatus"" = 1))
        AND NOT (p.""Voided""))
        AND NOT (p.""IsDeleted""))
        AND (
    (SELECT p2.""PaymentId""
    FROM ""PosTrxMops"" AS p1
    INNER JOIN ""PosMops"" AS p2
        ON p1.""PosMopId"" = p2.""Id""
    WHERE p0.""Id"" = p1.""PosTrxId"" LIMIT 1) not in(12,30)))
        AND ((p0.""CreatedDateTime"" >= '{1}')
        AND (p0.""CreatedDateTime"" <= '{2}'))", _currentBuId, startTime, endTime));

            var pumpTestTrxQuery = _unitOfWork.GetRepository<PosTrxLineItems>().FromSql(string.Format(@"		SELECT p.*
FROM ""PosTrxLineItems"" AS p
INNER JOIN ""PosTrxes"" AS p0
    ON p.""PosTrxId"" = p0.""Id""
WHERE ((((((p0.""TargetBusinessUnitId"" = '{0}')
        AND (p.""FuelItemSoldOnPumpNozzleId"" IS NOT NULL))
        AND (p0.""TransactionStatus"" = 1))
        AND NOT (p.""Voided""))
        AND NOT (p.""IsDeleted""))
        AND (
    (SELECT p2.""PaymentId""
    FROM ""PosTrxMops"" AS p1
    INNER JOIN ""PosMops"" AS p2
        ON p1.""PosMopId"" = p2.""Id""
    WHERE p0.""Id"" = p1.""PosTrxId"" LIMIT 1) = 12))
        AND ((p0.""CreatedDateTime"" >= '{1}')
        AND (p0.""CreatedDateTime"" <= '{2}'))", _currentBuId, startTime, endTime));

            var selfUseTrxQuery = _unitOfWork.GetRepository<PosTrxLineItems>().FromSql(string.Format(@"		SELECT p.*
FROM ""PosTrxLineItems"" AS p
INNER JOIN ""PosTrxes"" AS p0
    ON p.""PosTrxId"" = p0.""Id""
WHERE ((((((p0.""TargetBusinessUnitId"" = '{0}')
        AND (p.""FuelItemSoldOnPumpNozzleId"" IS NOT NULL))
        AND (p0.""TransactionStatus"" = 1))
        AND NOT (p.""Voided""))
        AND NOT (p.""IsDeleted""))
        AND (
    (SELECT p2.""PaymentId""
    FROM ""PosTrxMops"" AS p1
    INNER JOIN ""PosMops"" AS p2
        ON p1.""PosMopId"" = p2.""Id""
    WHERE p0.""Id"" = p1.""PosTrxId"" LIMIT 1) = 30))
        AND ((p0.""CreatedDateTime"" >= '{1}')
        AND (p0.""CreatedDateTime"" <= '{2}'))", _currentBuId, startTime, endTime));
            var shifts = shiftsQuery.Where(_ => _.CreatedDateTime <= _endTime).OrderByDescending(_ => _.ShiftId)
                          .Select(_ => new { _.Id, _.ShiftId }).ToList();
            if (shifts == null || !shifts.Any())
            {
                // return result;
            }
            var nozzles = new[] { new { nozzleId = 1, fuelName = "", itemPrice = 0.00M } }.ToList();
            nozzles.Clear();
            foreach (var shift in shifts)
            {
                nozzles = await _unitOfWork.GetRepository<PosTrxLineItems>().FromSql(string.Format(@"		SELECT
  p.*
FROM
  ""PosTrxLineItems"" AS p
  INNER JOIN ""PosTrxes"" AS p0 ON p.""PosTrxId"" = p0.""Id""
WHERE
        (
          p.""PosTrxId"" = '{0}'
        )", shift.Id))
                    .Include(_ => _.PosTrx)
                    .Include(_ => _.PosItem)
                    .GroupBy(_ => new { _.FuelItemSoldOnPumpNozzleId, _.PosItemId, _.PosItem.ItemName, _.ItemPrice })
                    .Select(_ => new
                    {
                        nozzleId = _.Key.FuelItemSoldOnPumpNozzleId.Value,
                        fuelName = _.Key.ItemName,
                        itemPrice = _.Key.ItemPrice ?? 0.00M,
                    })?.ToListAsync();

                if (nozzles != null && nozzles.Any())
                    break;
            }
            var trxes = await trxQuery.GroupBy(_ => _.FuelItemSoldOnPumpNozzleId)
                                  .Select(_ => new
                                  {
                                      nozzleId = _.Key,
                                      Qty = _.Sum(i => i.Qty),
                                      TotalAmount = _.Sum(i => i.GrossAmount),
                                      NetAmount = _.Sum(i => i.NetAmount),
                                  })?.ToListAsync();

            var pumpTestTrxes = await pumpTestTrxQuery.GroupBy(_ => _.FuelItemSoldOnPumpNozzleId)
                                                      .Select(_ => new
                                                      {
                                                          nozzleId = _.Key,
                                                          Qty = _.Sum(i => i.Qty)
                                                      })?.ToListAsync();

            var selfUseTrxes = await selfUseTrxQuery.GroupBy(_ => _.FuelItemSoldOnPumpNozzleId)
                                                      .Select(_ => new
                                                      {
                                                          nozzleId = _.Key,
                                                          Qty = _.Sum(i => i.Qty)
                                                      })?.ToListAsync();
            var nozzleTotalizers = new List<NozzleTotalizerDto>();
            foreach (var nozzle in nozzles)
            {
                var nozzleId = nozzle.nozzleId;
                var totalizer = new NozzleTotalizerDto();
                decimal startTotlaizer = startTotalizers?.FirstOrDefault(_ => _.nozzleId == nozzleId)?.totalizer ?? 0.00M;
                decimal endTotlaizer = endTotalizers?.FirstOrDefault(_ => _.nozzleId == nozzleId)?.totalizer ?? 0.00M;
                var volumeOnPump = endTotlaizer - startTotlaizer;

                var nozzleTrxes = trxes?.FirstOrDefault(_ => _.nozzleId == nozzleId);
                var saleQty = nozzleTrxes?.Qty ?? 0.00M;
                var totalAmount = nozzleTrxes?.TotalAmount ?? 0.00M;
                var netAmount = nozzleTrxes?.NetAmount ?? 0.00M;
                var discount = totalAmount - netAmount;

                var volumeForPumpTest = pumpTestTrxes?.FirstOrDefault(_ => _.nozzleId == nozzleId)?.Qty ?? 0.00M;
                var volumeForSelfUse = selfUseTrxes?.FirstOrDefault(_ => _.nozzleId == nozzleId)?.Qty ?? 0.00M;

                nozzleTotalizers.Add(new NozzleTotalizerDto
                {
                    IsShift = true,
                    NozzleId = nozzleId,
                    GradeName = nozzle.fuelName,
                    CurrentPrice = nozzle.itemPrice,
                    VolumeOnPumpStart = startTotlaizer,
                    VolumeOnPumpEnd = endTotlaizer,
                    VolumeOnPump = volumeOnPump,
                    VolumeOnPos = saleQty,
                    VolumeDifferent = volumeOnPump == saleQty,
                    PumpTestVolume = volumeForPumpTest,
                    SelfUseVolume = volumeForSelfUse,
                    TotalVolume = saleQty + volumeForPumpTest + volumeForSelfUse,
                    TotalPaid = totalAmount,
                    TotalNetAmount = netAmount,
                    TotalDiscount = discount
                });
            }
            return nozzleTotalizers;
        }

        public void StoreListInSession(List<NozzleTotalizerDto> nozzleTotalizers)
        {
            HttpContext httpContext = _httpContextAccessor.HttpContext;
            string json = System.Text.Json.JsonSerializer.Serialize(nozzleTotalizers, _jsonSerializerOptions);
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            httpContext.Session.Set("NozzleTotalizers", bytes);
        }
        public async Task<List<NozzleTotalizerDto>> GetListFromSessionAsync(string startTime,
                                                         string endTime,
                                                         string currentBuId)
        {
            var nozzleTotalizers = await NozzleAsync(startTime, endTime, currentBuId); // 将 nozzleTotalizers 列表序列化为字节数组 
            //byte[] bytes = null;
            //using (var memoryStream = new MemoryStream())
            //{
            //    var formatter = new BinaryFormatter();
            //    formatter.Serialize(memoryStream, nozzleTotalizers);
            //    bytes = memoryStream.ToArray();
            //}
            //if (bytes != null)
            //{
            //    string json = Encoding.UTF8.GetString(bytes);
            //    return System.Text.Json.JsonSerializer.Deserialize<List<NozzleTotalizerDto>>(json, _jsonSerializerOptions);
            //}
            return nozzleTotalizers;
        }
        public async Task<ExecuteResult> GetTransactionStatus(string SeqNo, string NozzleId, string sn, string FuelItemFdcReleaseTokenAttribute, string FuelItemOriginalGrossAmount, DateTime? FuelItemTransactionEndTime = null)
        {
          //  MS.WebCore.Logger.Logger.WriteLog(string.Format(@" GetTransactionStatus：SeqNo {0} NozzleId{1}
         //  sn {2} "));
            ExecuteResult<TransactionStatusDto> result = new ExecuteResult<TransactionStatusDto>();
            string _startTime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss");
            string where = string.Empty;
            if (!string.IsNullOrEmpty(FuelItemFdcReleaseTokenAttribute))
            {
                where += string.Format(@" and ptli.""FuelItemFdcReleaseTokenAttribute""  = '{0}'", FuelItemFdcReleaseTokenAttribute);
            }
            if (!string.IsNullOrEmpty(FuelItemOriginalGrossAmount))
            {
                where += string.Format(@" and ptli.""FuelItemOriginalGrossAmount""  = '{0}'", FuelItemOriginalGrossAmount);
            }
            
       

            try
            {
                var SiteDevices = _AuthContext.GetRepository<SiteDevices>().GetAll()
                      .Where(a => a.HardwareIdentity == sn).FirstOrDefault();
                var buid = SiteDevices.AsSubjectOfBusinessUnitId;

                if (FuelItemTransactionEndTime != null && buid != null &&  buid.ToString() != "5914f34a-b69d-42b9-9fd4-0b8f6fba715e")
                {
                    string sdate = FuelItemTransactionEndTime.Value.AddSeconds(1).ToString("yyyy-MM-dd HH:mm:ss");
                    string edate = FuelItemTransactionEndTime.Value.AddSeconds(-2).ToString("yyyy-MM-dd HH:mm:ss");
                    where += string.Format(@" and ptli.""FuelItemTransactionEndTime"" >= '{0}' and ptli.""FuelItemTransactionEndTime"" <= '{1}'"
    , edate, sdate);
                }
                else
                {
                    where += string.Format(@" and a.""CreatedDateTime"" >= '{0}'", _startTime);
                }

//                var  nozzles = await _unitOfWork.GetRepository<PosTrxMops>().FromSql(string.Format(@"	select ptm.""ResultCode"" ,ptm.""ResultMessage""
//,a.""orderType"" from ""PosTrxes"" as a join ""PosTrxLineItems"" ptli on a.""Id"" = ptli.""PosTrxId"" 
//left join ""PosTrxMops"" ptm ON  a
//.""Id"" = ptm.""PosTrxId"" where ptli.""FuelItemFdcTransactionSeqNo""='{0}'
//and a.""TargetBusinessUnitId""='{1}'  and ptli.""FuelItemSoldOnPumpNozzleId"" = '{2}'   and ptli.""Voided"" = false 
//and ptli.""FuelItemOriginalGrossAmount""  > 0 {4}"
//, SeqNo, buid, NozzleId, _startTime, where))//and ptli.""Voided"" = false 
//                .GroupBy(_ => new { _.ResultCode, _.ResultMessage,_.order })
//                  .Select(_ => new TransactionStatusDto
//                  {
//                      ResultCode = _.Key.ResultCode,
//                      ResultMessage = _.Key.ResultMessage,
//                      orderType = _.Key
//                  })?.ToListAsync();
                var nozzles = _unitOfWork.DbContext.posTrxMopsDtos
           .FromSqlRaw(string.Format(@"	select ptm.""ResultCode"" ,ptm.""ResultMessage""
,a.""orderType"" from ""PosTrxes"" as a join ""PosTrxLineItems"" ptli on a.""Id"" = ptli.""PosTrxId"" 
left join ""PosTrxMops"" ptm ON  a
.""Id"" = ptm.""PosTrxId"" where ptli.""FuelItemFdcTransactionSeqNo""='{0}'
and a.""TargetBusinessUnitId""='{1}'  and ptli.""FuelItemSoldOnPumpNozzleId"" = '{2}'   and ptli.""Voided"" = false 
and ptli.""FuelItemOriginalGrossAmount""  > 0 {4}"
, SeqNo, buid, NozzleId, _startTime, where)).GroupBy(_ => new { _.ResultCode, _.ResultMessage, _.orderType }).Select(_ => new TransactionStatusDto
{
    ResultCode = _.Key.ResultCode,
    ResultMessage = _.Key.ResultMessage,
    orderType = _.Key.orderType
})?.ToList();
                result.SetData(nozzles);
            }
            catch (Exception ex)
            {
                ExecuteResult result_ = new ExecuteResult();
                result_.Message = ex.ToString();
                return result_;
            }
            return result;
        }

        //public void ExportToExcel(List<NozzleTotalizerDto> nozzleTotalizers, string filePath)
        //{
        //    IWorkbook workbook = new XSSFWorkbook();
        //    ISheet sheet = workbook.CreateSheet("Sheet1"); // 添加表头
        //    IRow headerRow = sheet.CreateRow(0);
        //    headerRow.CreateCell(0).SetCellValue("IsShift");
        //    headerRow.CreateCell(1).SetCellValue("NozzleId");
        //    headerRow.CreateCell(2).SetCellValue("GradeName");
        //    headerRow.CreateCell(3).SetCellValue("CurrentPrice");
        //    headerRow.CreateCell(4).SetCellValue("VolumeOnPumpStart");
        //    headerRow.CreateCell(5).SetCellValue("VolumeOnPumpEnd");
        //    headerRow.CreateCell(6).SetCellValue("VolumeOnPump");
        //    headerRow.CreateCell(7).SetCellValue("VolumeOnPos");
        //    headerRow.CreateCell(8).SetCellValue("VolumeDifferent");
        //    headerRow.CreateCell(9).SetCellValue("PumpTestVolume");
        //    headerRow.CreateCell(10).SetCellValue("SelfUseVolume");
        //    headerRow.CreateCell(11).SetCellValue("TotalVolume");
        //    headerRow.CreateCell(12).SetCellValue("TotalPaid");
        //    headerRow.CreateCell(13).SetCellValue("TotalNetAmount");
        //    headerRow.CreateCell(14).SetCellValue("TotalDiscount");
        //    for (int i = 0; i < nozzleTotalizers.Count; i++)
        //    {
        //        NozzleTotalizerDto nozzleTotalizer = nozzleTotalizers[i];
        //        IRow dataRow = sheet.CreateRow(i + 1);
        //        dataRow.CreateCell(0).SetCellValue(nozzleTotalizer.IsShift);
        //        dataRow.CreateCell(1).SetCellValue("");
        //        dataRow.CreateCell(2).SetCellValue(nozzleTotalizer.GradeName);
        //        dataRow.CreateCell(3).SetCellValue((double)nozzleTotalizer.CurrentPrice);
        //        dataRow.CreateCell(4).SetCellValue((double)nozzleTotalizer.VolumeOnPumpStart);
        //        dataRow.CreateCell(5).SetCellValue((double)nozzleTotalizer.VolumeOnPumpEnd);
        //        dataRow.CreateCell(6).SetCellValue((double)nozzleTotalizer.VolumeOnPump);
        //        dataRow.CreateCell(7).SetCellValue((double)nozzleTotalizer.VolumeOnPos);
        //        dataRow.CreateCell(8).SetCellValue(nozzleTotalizer.VolumeDifferent);
        //        dataRow.CreateCell(9).SetCellValue((double)nozzleTotalizer.PumpTestVolume);
        //        dataRow.CreateCell(10).SetCellValue((double)nozzleTotalizer.SelfUseVolume);
        //        dataRow.CreateCell(11).SetCellValue((double)nozzleTotalizer.TotalVolume);
        //        dataRow.CreateCell(12).SetCellValue((double)nozzleTotalizer.TotalPaid);
        //        dataRow.CreateCell(13).SetCellValue((double)nozzleTotalizer.TotalNetAmount);
        //        dataRow.CreateCell(14).SetCellValue((double)nozzleTotalizer.TotalDiscount); // 添加其他数据列...
        //    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     // }
        //                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          // 保存Excel文件 
        //    using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        //    {
        //        workbook.Write(fileStream, true);
        //    }
        //}
        public async Task<MemoryStream> ExportToExcelAsync<T>(List<T> data)
        {
            // Create a new workbook and sheet 
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Sheet1");
            // Get the properties of the data type 
            var properties = typeof(T).GetProperties();
            // Create the header row 
            IRow headerRow = sheet.CreateRow(0);
            for (int i = 0; i < properties.Length; i++)
            {
                ICell cell = headerRow.CreateCell(i);
                cell.SetCellValue(properties[i].Name);
            }
            // Create the data rows 
            for (int rowIndex = 0; rowIndex < data.Count; rowIndex++)
            {
                IRow dataRow = sheet.CreateRow(rowIndex + 1);
                for (int colIndex = 0; colIndex < properties.Length; colIndex++)
                {
                    object value = properties[colIndex].GetValue(data[rowIndex]);
                    ICell cell = dataRow.CreateCell(colIndex);
                    cell.SetCellValue(value != null ? value.ToString() : "");
                }
            }
            var stream = new MemoryStream();
            workbook.Write(stream);
            stream.Seek(0, SeekOrigin.Begin);

            // 执行操作，使用流中的数据

            stream.Position = 0; // 重置流的位置

            var resultStream = new MemoryStream(stream.ToArray()); // 创建包含相同数据的新的MemoryStream

            stream.Close(); // 手动关闭流
            stream.Dispose(); // 手动释放流的资源

            return resultStream;
        }
        //public async Task<MemoryStream> ExportToExcelAsync<T>(List<T> data)
        //{
        //    using (var package = new ExcelPackage())
        //    {
        //        var worksheet = package.Workbook.Worksheets.Add("Sheet1");

        //        // 写入表头
        //        var properties = typeof(T).GetProperties();
        //        for (int i = 0; i < properties.Length; i++)
        //        {
        //            var property = properties[i];
        //            worksheet.Cells[1, i + 1].Value = property.Name;
        //        }

        //        // 写入数据
        //        for (int i = 0; i < data.Count; i++)
        //        {
        //            var item = data[i];
        //            for (int j = 0; j < properties.Length; j++)
        //            {
        //                var property = properties[j];
        //                var value = property.GetValue(item);
        //                worksheet.Cells[i + 2, j + 1].Value = value;
        //            }
        //        }

        //        // 根据需要设置其他样式或格式

        //        // 保存为Excel文件
        //        var stream = new MemoryStream();
        //        package.SaveAs(stream);
        //        stream.Position = 0;
        //        return stream;
        //    }
        //}
    }
}
