using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BLL.Interfaces;
using DAL.Interfaces;
using MDL.Models;
using Microsoft.Extensions.Logging;
using DB.Database;
using Common.Util;

namespace BLL.Services
{
    public class ArrivalHandoverFormService : IArrivalHandoverFormService
    {
        private readonly IArrivalHandoverFormRepository _repository;
        private readonly ILabelReplaceRepository _labelReplaceRepository;
        private readonly IArrivalScanRecordRepository _arrivalScanRecordRepository;
        private readonly ISqlSugarProvider _provider;
        private readonly ILogger<ArrivalHandoverFormService> _logger;

        public ArrivalHandoverFormService(IArrivalHandoverFormRepository repository, ILabelReplaceRepository labelReplaceRepository, IArrivalScanRecordRepository arrivalScanRecordRepository, ISqlSugarProvider provider, ILogger<ArrivalHandoverFormService> logger)
        {
            _repository = repository;
            _labelReplaceRepository = labelReplaceRepository;
            _arrivalScanRecordRepository = arrivalScanRecordRepository;
            _provider = provider;
            _logger = logger;
        }

        public async Task<int> CreateArrivalHandoverFormAsync(ArrivalHandoverFormEntity form)
        {
            _logger.LogInformation("Creating arrival handover form: {HandoverNumber}", form.HandoverNumber);
            try
            {
                return await _repository.InsertAsync(form);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating arrival handover form");
                throw;
            }
        }

        public async Task<ArrivalHandoverFormEntity> GetArrivalHandoverFormByIdAsync(int id)
        {
            _logger.LogInformation("Getting arrival handover form by id: {Id}", id);
            try
            {
                return await _repository.GetByIdAsync(id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting arrival handover form by id: {Id}", id);
                throw;
            }
        }

        public async Task<ArrivalHandoverFormEntity> GetArrivalHandoverFormByNumberAsync(string handoverNumber)
        {
            _logger.LogInformation("Getting arrival handover form by number: {HandoverNumber}", handoverNumber);
            try
            {
                return await _repository.GetByHandoverNumberAsync(handoverNumber);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting arrival handover form by number: {HandoverNumber}", handoverNumber);
                throw;
            }
        }

        public async Task<List<ArrivalHandoverFormEntity>> GetAllArrivalHandoverFormsAsync()
        {
            _logger.LogInformation("Getting all arrival handover forms");
            try
            {
                return await _repository.GetAllAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all arrival handover forms");
                throw;
            }
        }

        public async Task<int> UpdateArrivalHandoverFormAsync(ArrivalHandoverFormEntity form)
        {
            _logger.LogInformation("Updating arrival handover form: {HandoverNumber}", form.HandoverNumber);
            try
            {
                return await _repository.UpdateAsync(form);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating arrival handover form: {HandoverNumber}", form.HandoverNumber);
                throw;
            }
        }

        public async Task<int> DeleteArrivalHandoverFormAsync(int id)
        {
            _logger.LogInformation("Deleting arrival handover form: {Id}", id);
            try
            {
                return await _repository.DeleteAsync(id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting arrival handover form: {Id}", id);
                throw;
            }
        }

        public async Task<string> GenerateArrivalHandoverNumberAsync()
        {
            _logger.LogInformation("Generating arrival handover number");
            try
            {
                var prefix = "ARR";
                var date = DateTime.Now.ToString("yyyyMMdd");
                var sequence = 1;

                // 生成格式: ARR-20240101-001
                var baseNumber = $"{prefix}-{date}";

                // 检查是否存在相同前缀的交接单
                var allForms = await _repository.GetAllAsync();
                foreach (var form in allForms)
                {
                    if (form.HandoverNumber.StartsWith(baseNumber))
                    {
                        var parts = form.HandoverNumber.Split('-');
                        if (parts.Length == 3 && int.TryParse(parts[2], out var existingSequence))
                        {
                            if (existingSequence >= sequence)
                            {
                                sequence = existingSequence + 1;
                            }
                        }
                    }
                }

                var handoverNumber = $"{baseNumber}-{sequence.ToString("D3")}";

                // 确保生成的编号不重复
                while (await _repository.ExistsByHandoverNumberAsync(handoverNumber))
                {
                    sequence++;
                    handoverNumber = $"{baseNumber}-{sequence.ToString("D3")}";
                }

                return handoverNumber;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error generating arrival handover number");
                throw;
            }
        }

        public async Task<(List<ArrivalHandoverFormEntity> Forms, int TotalCount)> GetArrivalHandoverFormsBatchAsync(
            int page,
            int pageSize,
            string sortBy,
            string sortOrder,
            string handoverNumber,
            string creator,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            _logger.LogInformation("Getting arrival handover forms batch: Page={Page}, PageSize={PageSize}, SortBy={SortBy}, SortOrder={SortOrder}", page, pageSize, sortBy, sortOrder);
            try
            {
                return await _repository.GetArrivalHandoverFormsBatchAsync(page, pageSize, sortBy, sortOrder, handoverNumber, creator, startDate, endDate);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting arrival handover forms batch");
                throw;
            }
        }

        public async Task<(int PackageCount, double LabelRate, long? ArrivalTime, string BillOfLadingNumber, string MasterPackageNumber)> GetReceiptInfoAsync(string arrivalNumber)
        {
            _logger.LogInformation("Getting receipt info: ArrivalNumber={ArrivalNumber}", arrivalNumber);

            int? customerId = null;
            string billOfLadingNumber = "";
            string masterPackageNumber = "";

            try
            {
                // 验证参数
                if (string.IsNullOrEmpty(arrivalNumber))
                {
                    throw new Exception("参数错误：请提供到货编号");
                }

                // 添加mock数据处理
                if (arrivalNumber == "TEST1ZX30Y730494260907")
                {
                    throw new Exception("无预报数据");
                }
                else if (arrivalNumber == "TEST1ZX30Y730494260906")
                {
                    billOfLadingNumber = "TEST1ZX30Y730494260906";
                    return (1200, 0.8, 1744032000000, billOfLadingNumber, "");
                }
                else if (arrivalNumber == "testS169-3-20-2-1")
                {
                    masterPackageNumber = "testS169-3-20-2-1";
                    return (1200, 0.8, 1744032000000, "", masterPackageNumber);
                }

                // 使用SqlSugar直接查询数据库
                var db = _provider.GetClient();

                // 查询label_replace_requests表，使用OR条件查询billOfLadingNumber或masterPackageNumber
                var query = db.Queryable<MDL.Models.LabelReplaceEntity>()
                    .Where(x => x.BillOfLadingNumber == arrivalNumber || x.MasterPackageNumber == arrivalNumber);

                // 获取查询结果
                var labelReplaceEntities = await query.ToListAsync();
                
                // 检查query参数是否为空或集合数量为0
                if (labelReplaceEntities == null || labelReplaceEntities.Count == 0)
                {
                    throw new Exception("无预报数据");
                }

                // 计算包裹数和已有标签率
                var totalCount = labelReplaceEntities.Count;
                var labelCount = labelReplaceEntities.Count(x => !string.IsNullOrWhiteSpace(x.Label));
                double labelRate = totalCount > 0 ? (double)labelCount / totalCount : 0;

                // 从查询结果中获取CustomerId、BillOfLadingNumber或MasterPackageNumber
                customerId = labelReplaceEntities.FirstOrDefault()?.CustomerId;
                billOfLadingNumber = labelReplaceEntities.FirstOrDefault(x => !string.IsNullOrEmpty(x.BillOfLadingNumber))?.BillOfLadingNumber ?? "";
                masterPackageNumber = labelReplaceEntities.FirstOrDefault(x => !string.IsNullOrEmpty(x.MasterPackageNumber))?.MasterPackageNumber ?? "";

                // 查询arrival_handover_forms表获取到货时间
                long? arrivalTime = null;
                var arrivalForm = await db.Queryable<ArrivalHandoverFormEntity>()
                    .Where(x => x.HandoverNumber == arrivalNumber)
                    .FirstAsync();
                
                // 当查询arrival_handover_forms表无数据时，自动创建记录
                if (arrivalForm == null)
                {
                    // 创建新的到货交接单记录
                    arrivalForm = new ArrivalHandoverFormEntity
                    {
                        HandoverNumber = arrivalNumber,
                        Creator = "System",
                        CreatedAt = DateTime.UtcNow,
                        UpdatedAt = DateTime.UtcNow,
                        ReceiptTime = DateTime.UtcNow,
                        LogisticsProviderArrivalTime = DateTime.UtcNow, // 头程送达时间与到货时间保持一致
                        Remarks = string.Empty
                    };

                    // 根据输入类型设置不同的逻辑
                    if (!string.IsNullOrEmpty(billOfLadingNumber))
                    {
                        // 若入参为提单号，确保头程送达时间与到货时间保持一致
                        // 已在上面设置
                    }
                    else if (!string.IsNullOrEmpty(masterPackageNumber))
                    {
                        // 若入参为大箱号，则将大箱号作为到货交接单号，并在备注字段中注明"交接单号为大箱号"
                        arrivalForm.Remarks = "交接单号为大箱号";
                    }

                    // 插入新记录
                    await _repository.InsertAsync(arrivalForm);
                }

                // 获取到货时间
                if (arrivalForm != null && arrivalForm.ReceiptTime.HasValue)
                {
                    arrivalTime = arrivalForm.ReceiptTime.Value.ToTimestamp();
                }

                return (totalCount, labelRate, arrivalTime, billOfLadingNumber, masterPackageNumber);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting receipt info");
                throw;
            }
            finally
            {
                var capturedArrivalNumber = arrivalNumber;
                var capturedCustomerId = customerId;
                var capturedBillOfLadingNumber = billOfLadingNumber;
                var capturedMasterPackageNumber = masterPackageNumber;

                _ = Task.Run(async () =>
                {
                    try
                    {
                        var scanRecord = new ArrivalScanRecordEntity
                        {
                            ArrivalNumber = capturedArrivalNumber,
                            CustomerId = capturedCustomerId,
                            BillOfLadingNumber = capturedBillOfLadingNumber,
                            MasterPackageNumber = capturedMasterPackageNumber,
                            CreatedAt = DateTime.UtcNow,
                            UpdatedAt = DateTime.UtcNow
                        };
                        await _arrivalScanRecordRepository.InsertAsync(scanRecord);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "插入收货扫描记录失败，ArrivalNumber={ArrivalNumber}", capturedArrivalNumber);
                    }
                });
            }
        }

        public async Task<List<ArrivalHandoverFormEntity>> GetArrivalHandoverFormsByHandoverNumberAsync(string handoverNumber)
        {
            _logger.LogInformation("Getting arrival handover forms by handover number: {HandoverNumber}", handoverNumber);
            try
            {
                // 使用SqlSugar直接查询数据库
                var db = _provider.GetClient();
                
                // 查询arrival_handover_forms表，使用handoverNumber作为条件
                var forms = await db.Queryable<ArrivalHandoverFormEntity>()
                    .Where(x => x.HandoverNumber == handoverNumber)
                    .ToListAsync();
                
                return forms;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting arrival handover forms by handover number: {HandoverNumber}", handoverNumber);
                return new List<ArrivalHandoverFormEntity>();
            }
        }
    }
}