using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Entities;
using HoneyBox.Model.Models.Mall;
using HoneyBox.Model.Models.Payment;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Core.Services;

/// <summary>
/// 商城服务实现
/// Requirements: 15.1-15.3
/// </summary>
public class MallService : IMallService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly IWechatPayService _wechatPayService;
    private readonly ILogger<MallService> _logger;

    public MallService(
        HoneyBoxDbContext dbContext,
        IWechatPayService wechatPayService,
        ILogger<MallService> logger)
    {
        _dbContext = dbContext;
        _wechatPayService = wechatPayService;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task<List<DiamondProductDto>> GetDiamondListAsync(int? userId)
    {
        try
        {
            _logger.LogInformation("获取钻石商品列表: UserId={UserId}", userId);

            // 查询启用的钻石商品，按排序字段排序
            var diamondProducts = await _dbContext.DiamondProducts
                .Where(p => p.Status == 1 && p.ProductsType == "1")
                .OrderBy(p => p.SortOrder)
                .ToListAsync();

            // 查询用户是否有成功的钻石订单（判断首充）
            var diamondOrderCount = 0;
            if (userId.HasValue && userId.Value > 0)
            {
                diamondOrderCount = await _dbContext.DiamondOrders
                    .CountAsync(o => o.UserId == userId.Value && o.Status == DiamondOrderStatus.Success);
            }

            // 转换为DTO，根据首充状态选择图片
            var result = diamondProducts.Select(p => new DiamondProductDto
            {
                ProductsId = p.ProductsId,
                Name = p.Name,
                Price = p.Price,
                Status = p.Status,
                // 如果商品支持首充且用户没有购买记录，显示首充图片
                Image = (p.IsFirst == 1 && diamondOrderCount == 0)
                    ? p.FirstChargeImage
                    : p.NormalImage,
                SelectImage = (p.IsFirst == 1 && diamondOrderCount == 0)
                    ? p.FirstSelectChargeImage
                    : p.NormalSelectImage
            }).ToList();

            _logger.LogInformation("获取钻石商品列表成功: Count={Count}", result.Count);
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取钻石商品列表异常: UserId={UserId}", userId);
            return new List<DiamondProductDto>();
        }
    }

    /// <inheritdoc />
    public async Task<CreateDiamondOrderResult> CreateOrderProductsAsync(int userId, CreateDiamondOrderRequest request)
    {
        try
        {
            _logger.LogInformation("创建钻石订单: UserId={UserId}, ProductId={ProductId}, PayType={PayType}",
                userId, request.ProductId, request.PayType);

            // 1. 验证用户
            var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
            if (user == null)
            {
                return new CreateDiamondOrderResult { Status = 0 };
            }

            // 2. 查询钻石商品
            var diamondProduct = await _dbContext.DiamondProducts
                .FirstOrDefaultAsync(p => p.ProductsId == request.ProductId);

            if (diamondProduct == null)
            {
                _logger.LogWarning("钻石商品不存在: ProductId={ProductId}", request.ProductId);
                return new CreateDiamondOrderResult { Status = 0 };
            }

            if (diamondProduct.Status != 1)
            {
                _logger.LogWarning("钻石商品已下架: ProductId={ProductId}", request.ProductId);
                return new CreateDiamondOrderResult { Status = 0 };
            }

            // 3. 查询用户钻石订单数，判断是否首充
            var diamondOrderCount = await _dbContext.DiamondOrders
                .CountAsync(o => o.UserId == userId && o.Status == DiamondOrderStatus.Success);

            // 4. 生成订单号
            var orderNum = GenerateOrderNum("ZS_");

            // 5. 调用微信支付创建订单
            var payRequest = new WechatPayRequest
            {
                OrderNo = orderNum,
                Amount = diamondProduct.Price,
                Body = $"购买钻石{diamondProduct.Name}",
                Attach = "order_product",
                UserId = userId
            };

            var payResult = await _wechatPayService.CreatePaymentAsync(payRequest);

            if (payResult.Status != 1)
            {
                _logger.LogWarning("创建微信支付订单失败: OrderNum={OrderNum}, Msg={Msg}", orderNum, payResult.Msg);
                return new CreateDiamondOrderResult { Status = 0 };
            }

            // 6. 创建钻石订单记录
            var diamondOrder = new DiamondOrder
            {
                OrderNo = orderNum,
                UserId = userId,
                DiamondId = diamondProduct.Id,
                ProductId = request.ProductId,
                ProductName = diamondProduct.Name,
                AmountPaid = diamondProduct.Price,
                PayMethod = (request.PayType == 1 || request.PayType == 3)
                    ? DiamondPayMethod.Wechat
                    : DiamondPayMethod.Alipay,
                IsFirstCharge = (byte)(diamondOrderCount == 0 ? 1 : 0),
                Status = DiamondOrderStatus.Pending,
                CreatedAt = DateTime.Now
            };

            _dbContext.DiamondOrders.Add(diamondOrder);
            await _dbContext.SaveChangesAsync();

            _logger.LogInformation("钻石订单创建成功: OrderNum={OrderNum}, UserId={UserId}", orderNum, userId);

            return new CreateDiamondOrderResult
            {
                Status = 1,
                OrderNum = orderNum,
                Res = payResult.Data
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建钻石订单异常: UserId={UserId}, ProductId={ProductId}",
                userId, request.ProductId);
            return new CreateDiamondOrderResult { Status = 0 };
        }
    }

    /// <inheritdoc />
    public async Task<DiamondOrderStatusResponse?> GetDiamondOrderLogAsync(int userId, string orderNum)
    {
        try
        {
            _logger.LogInformation("查询钻石订单状态: UserId={UserId}, OrderNum={OrderNum}", userId, orderNum);

            if (string.IsNullOrEmpty(orderNum))
            {
                _logger.LogWarning("订单号为空");
                return null;
            }

            // 查询钻石订单
            var diamondOrder = await _dbContext.DiamondOrders
                .FirstOrDefaultAsync(o => o.OrderNo == orderNum);

            if (diamondOrder == null)
            {
                _logger.LogWarning("钻石订单不存在: OrderNum={OrderNum}", orderNum);
                return null;
            }

            // 验证订单归属
            if (diamondOrder.UserId != userId)
            {
                _logger.LogWarning("无权限查看订单: UserId={UserId}, OrderUserId={OrderUserId}",
                    userId, diamondOrder.UserId);
                return null;
            }

            // 验证订单状态
            if (diamondOrder.Status != DiamondOrderStatus.Success)
            {
                _logger.LogWarning("订单未成功: OrderNum={OrderNum}, Status={Status}",
                    orderNum, diamondOrder.Status);
                return null;
            }

            return new DiamondOrderStatusResponse
            {
                Status = diamondOrder.Status ?? string.Empty,
                RewardLog = diamondOrder.RewardLog
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询钻石订单状态异常: UserId={UserId}, OrderNum={OrderNum}", userId, orderNum);
            return null;
        }
    }

    #region Private Methods

    /// <summary>
    /// 生成订单号
    /// </summary>
    private static string GenerateOrderNum(string prefix)
    {
        var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
        var random = new Random().Next(100000, 999999);
        return $"{prefix}{timestamp}{random}";
    }

    #endregion
}
