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

namespace BLL.Services
{
    public class ShippingHandoverFormService : IShippingHandoverFormService
    {
        private readonly IShippingHandoverFormRepository _repository;
        private readonly IShippingHandoverFormBagTagRepository _shippingHandoverFormBagTagRepository;
        private readonly IBagTagService _bagTagService;
        private readonly ILogger<ShippingHandoverFormService> _logger;

        public ShippingHandoverFormService(
            IShippingHandoverFormRepository repository,
            IShippingHandoverFormBagTagRepository shippingHandoverFormBagTagRepository,
            IBagTagService bagTagService,
            ILogger<ShippingHandoverFormService> logger)
        {
            _repository = repository;
            _shippingHandoverFormBagTagRepository = shippingHandoverFormBagTagRepository;
            _bagTagService = bagTagService;
            _logger = logger;
        }

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

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

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

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

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

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

        public async Task<string> GenerateShippingHandoverNumberAsync(string channel = "GOFO")
        {
            _logger.LogInformation("Generating shipping handover number for channel: {Channel}", channel);
            try
            {
                // 新的命名规则：BOL-{口岸}-{渠道商全称}-{YYYYMMDD}-{序号}
                // 口岸默认是ORD
                string port = "ORD";
                string date = DateTime.Now.ToString("yyyyMMdd");
                string baseNumber = $"BOL-{port}-{channel.ToUpper()}-{date}";
                
                // 计算序号
                int sequence = 1;
                var allForms = await _repository.GetAllAsync();
                foreach (var form in allForms)
                {
                    if (form.HandoverNumber.StartsWith(baseNumber))
                    {
                        var parts = form.HandoverNumber.Split('-');
                        if (parts.Length == 5 && int.TryParse(parts[4], 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")}";
                }

                _logger.LogInformation("Generated shipping handover number: {HandoverNumber}", handoverNumber);
                return handoverNumber;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error generating shipping handover number");
                throw;
            }
        }

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

        public async Task<int> UpdateShippingHandoverFormPODAsync(string handoverNumber, string podLinks)
        {
            _logger.LogInformation("Updating POD for shipping handover form: {HandoverNumber}", handoverNumber);
            try
            {
                var form = await _repository.GetByHandoverNumberAsync(handoverNumber);
                if (form == null)
                {
                    _logger.LogWarning("Shipping handover form not found: {HandoverNumber}", handoverNumber);
                    return 0;
                }

                form.POD = podLinks;
                form.UpdatedAt = DateTime.UtcNow;

                return await _repository.UpdateAsync(form);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating POD for shipping handover form: {HandoverNumber}", handoverNumber);
                throw;
            }
        }

        public async Task<(string HandoverNumber, string Channel, int BagTagCount, int TotalPackageCount, string Status)> GetShippingHandoverFormDetailsAsync(string handoverNumber)
        {
            _logger.LogInformation("Getting shipping handover form details: {HandoverNumber}", handoverNumber);
            try
            {
                // Mock数据
                if (handoverNumber == "TESTBOL001")
                {
                    return ("TESTBOL001", "GOFO", 3, 150, "Draft");
                }
                else if (handoverNumber == "TESTBOL002")
                {
                    return ("TESTBOL002", "USPS", 5, 250, "Draft");
                }
                else if (handoverNumber == "TESTBOL003")
                {
                    return ("TESTBOL003", "UPS", 0, 0, "Draft");
                }

                // 查询出库交接单
                var form = await _repository.GetByHandoverNumberAsync(handoverNumber);
                if (form == null)
                {
                    _logger.LogWarning("Shipping handover form not found: {HandoverNumber}", handoverNumber);
                    throw new Exception("Shipping handover form not found");
                }

                // 查询关联的袋牌
                var bagTags = await _shippingHandoverFormBagTagRepository.GetByShippingHandoverFormIdAsync(form.Id);
                int bagTagCount = bagTags.Count;

                // 计算总包裹数
                int totalPackageCount = 0;
                foreach (var bagTag in bagTags)
                {
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(bagTag.TagNumber);
                    totalPackageCount += waybillCount;
                }

                return (form.HandoverNumber, form.Channel, bagTagCount, totalPackageCount, form.Status.ToString());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting shipping handover form details: {HandoverNumber}", handoverNumber);
                throw;
            }
        }

        public async Task<bool> ConfirmShippingHandoverFormAsync(string handoverNumber, System.DateTime? deliveryTime, string pod)
        {
            _logger.LogInformation("Confirming shipping handover form: {HandoverNumber}", handoverNumber);
            try
            {
                // Mock数据
                if (handoverNumber == "TESTBOL001" || handoverNumber == "TESTBOL002" || handoverNumber == "TESTBOL003")
                {
                    _logger.LogInformation("Mock: Confirmed shipping handover form: {HandoverNumber}", handoverNumber);
                    return true;
                }

                // 查询出库交接单
                var form = await _repository.GetByHandoverNumberAsync(handoverNumber);
                if (form == null)
                {
                    _logger.LogWarning("Shipping handover form not found: {HandoverNumber}", handoverNumber);
                    throw new Exception("Shipping handover form not found");
                }

                // 检查是否已经出库
                if (form.Status == ShippingHandoverFormStatus.Completed)
                {
                    _logger.LogWarning("Shipping handover form already completed: {HandoverNumber}", handoverNumber);
                    throw new Exception("Shipping handover form already completed");
                }

                // 检查POD是否包含至少两张图片
                if (string.IsNullOrEmpty(pod))
                {
                    _logger.LogWarning("POD is required for confirming shipping handover form: {HandoverNumber}", handoverNumber);
                    throw new Exception("POD is required");
                }

                var podLinks = pod.Split(',');
                if (podLinks.Length < 2)
                {
                    _logger.LogWarning("POD must contain at least 2 image links: {HandoverNumber}", handoverNumber);
                    throw new Exception("POD must contain at least 2 image links");
                }

                // 检查是否关联了袋牌
                var bagTags = await _shippingHandoverFormBagTagRepository.GetByShippingHandoverFormIdAsync(form.Id);
                if (bagTags.Count == 0)
                {
                    _logger.LogWarning("No bag tags associated with shipping handover form: {HandoverNumber}", handoverNumber);
                    throw new Exception("At least one bag tag must be associated with the shipping handover form");
                }

                // 更新状态为已出库
                form.Status = ShippingHandoverFormStatus.Completed;
                form.DeliveryTime = deliveryTime;
                form.POD = pod;
                form.UpdatedAt = DateTime.UtcNow;

                // 保存更新
                var result = await _repository.UpdateAsync(form);
                return result > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error confirming shipping handover form: {HandoverNumber}", handoverNumber);
                throw;
            }
        }
    }
}