using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BLL.Interfaces;
using Common.Util;
using DAL.Interfaces;
using MDL.Models;

namespace BLL.Services
{
    /// <summary>
    /// Excel导入服务实现类
    /// </summary>
    public class ExcelImportService : IExcelImportService
    {
        private readonly ICargoDataRepository _cargoDataRepository;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cargoDataRepository">货物数据仓库</param>
        public ExcelImportService(ICargoDataRepository cargoDataRepository)
        {
            _cargoDataRepository = cargoDataRepository;
        }
        
        /// <summary>
        /// 导入货物数据（中性面单、大包号、提单号）
        /// </summary>
        public async Task<ImportResult> ImportCargoDataAsync(Stream excelStream, int? customerId = null, string importedBy = "System")
        {
            var startTime = System.DateTime.UtcNow;
            var result = new ImportResult();
            var cargoDataList = new List<CargoDataEntity>();
            
            try
            {
                // 读取Excel文件
                var excelRows = ExcelHelper.ReadCargoDataFromExcel(excelStream);
                result.TotalCount = excelRows.Count;
                
                // 验证和转换数据
                for (int i = 0; i < excelRows.Count; i++)
                {
                    var excelRow = excelRows[i];
                    
                    // 验证数据行
                    if (!ExcelHelper.ValidateExcelRow(excelRow))
                    {
                        result.FailedCount++;
                        result.Errors.Add(new ImportError
                        {
                            RowNumber = excelRow.RowNumber,
                            ErrorMessage = "数据验证失败：中性面单不能为空，且大包号与提单号不能同时为空",
                            OriginalData = new Dictionary<string, string>
                            {
                                { "中性面单单号", excelRow.NeutralWaybillNumber },
                                { "大包号", excelRow.MasterPackageNumber ?? string.Empty },
                                { "提单号", excelRow.BillOfLadingNumber ?? string.Empty }
                            }
                        });
                        continue;
                    }
                    
                    // 转换为数据实体
                    var cargoData = new CargoDataEntity
                    {
                        NeutralWaybillNumber = excelRow.NeutralWaybillNumber,
                        MasterPackageNumber = excelRow.MasterPackageNumber,
                        BillOfLadingNumber = excelRow.BillOfLadingNumber,
                        CustomerId = customerId,
                        ImportedBy = importedBy,
                        ImportedAt = System.DateTime.UtcNow,
                        Status = "Y"
                    };
                    
                    cargoDataList.Add(cargoData);
                }
                
                if (cargoDataList.Count > 0)
                {
                    // 批量插入数据
                    var insertedCount = await _cargoDataRepository.BatchInsertAsync(cargoDataList);
                    result.SuccessCount = insertedCount;
                    
                    // 如果插入数量与有效数据数量不一致，记录差异
                    if (insertedCount < cargoDataList.Count)
                    {
                        result.FailedCount += cargoDataList.Count - insertedCount;
                        result.Errors.Add(new ImportError
                        {
                            RowNumber = 0,
                            ErrorMessage = $"部分数据导入失败，成功导入{insertedCount}条，失败{result.FailedCount}条",
                            OriginalData = new Dictionary<string, string>()
                        });
                    }
                }
                
                // 计算导入耗时
                var endTime = System.DateTime.UtcNow;
                result.ElapsedMilliseconds = (long)(endTime - startTime).TotalMilliseconds;
                result.Success = result.Errors.Count == 0;
                
                return result;
            }
            catch (System.Exception ex)
            {
                // 记录异常信息
                result.Success = false;
                result.Errors.Add(new ImportError
                {
                    RowNumber = 0,
                    ErrorMessage = $"导入过程中发生异常：{ex.Message}",
                    OriginalData = new Dictionary<string, string>()
                });
                
                // 计算导入耗时
                var endTime = System.DateTime.UtcNow;
                result.ElapsedMilliseconds = (long)(endTime - startTime).TotalMilliseconds;
                
                return result;
            }
        }
        
        /// <summary>
        /// 导出Excel模板
        /// </summary>
        public async Task<byte[]> ExportTemplateAsync()
        {
            // 由于是同步方法，使用Task.FromResult包装
            return await Task.FromResult(ExcelHelper.CreateCargoDataTemplate());
        }
        
        /// <summary>
        /// 查询货物数据
        /// </summary>
        public async Task<IEnumerable<CargoDataEntity>> QueryCargoDataAsync(string? searchKey = null, int? customerId = null, int pageIndex = 1, int pageSize = 100)
        {
            return await _cargoDataRepository.QueryAsync(searchKey, customerId, pageIndex, pageSize);
        }
        
        /// <summary>
        /// 根据中性面单单号查询货物数据
        /// </summary>
        public async Task<CargoDataEntity?> GetCargoDataByWaybillNumberAsync(string neutralWaybillNumber)
        {
            return await _cargoDataRepository.GetByWaybillNumberAsync(neutralWaybillNumber);
        }
        
        /// <summary>
        /// 验证Excel数据行
        /// </summary>
        public bool ValidateExcelRow(ExcelImportRow excelRow)
        {
            return ExcelHelper.ValidateExcelRow(excelRow);
        }
    }
}