using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Rank;
using HoneyBox.Admin.Business.Services.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Admin.Business.Services;

/// <summary>
/// 排行榜管理服务实现
/// </summary>
public class RankService : IRankService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<RankService> _logger;

    // 周榜奖品的goods_id标识
    private const int WeekPrizeGoodsId = -1;
    // 月榜奖品的goods_id标识
    private const int MonthPrizeGoodsId = -2;

    public RankService(
        HoneyBoxDbContext dbContext,
        ILogger<RankService> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    #region 周榜奖品管理

    /// <inheritdoc />
    public async Task<PagedResult<RankPrizeResponse>> GetWeekPrizesAsync(RankPrizeListRequest request)
    {
        return await GetPrizesAsync(WeekPrizeGoodsId, request);
    }

    /// <inheritdoc />
    public async Task<RankPrizeResponse?> GetWeekPrizeByIdAsync(int id)
    {
        return await GetPrizeByIdAsync(WeekPrizeGoodsId, id);
    }

    /// <inheritdoc />
    public async Task<int> CreateWeekPrizeAsync(RankPrizeCreateRequest request)
    {
        return await CreatePrizeAsync(WeekPrizeGoodsId, request);
    }

    /// <inheritdoc />
    public async Task<bool> UpdateWeekPrizeAsync(int id, RankPrizeUpdateRequest request)
    {
        return await UpdatePrizeAsync(WeekPrizeGoodsId, id, request);
    }

    /// <inheritdoc />
    public async Task<bool> DeleteWeekPrizeAsync(int id)
    {
        return await DeletePrizeAsync(WeekPrizeGoodsId, id);
    }

    /// <inheritdoc />
    public async Task<PagedResult<RankLogResponse>> GetWeekLogsAsync(RankLogListRequest request)
    {
        var query = _dbContext.RankWeeks.AsNoTracking();

        // 应用用户ID过滤
        if (request.UserId.HasValue)
        {
            query = query.Where(r => r.UserId == request.UserId.Value);
        }

        // 应用手机号过滤
        if (!string.IsNullOrWhiteSpace(request.Mobile))
        {
            var userIds = await _dbContext.Users
                .Where(u => u.Mobile == request.Mobile)
                .Select(u => u.Id)
                .ToListAsync();
            query = query.Where(r => userIds.Contains(r.UserId));
        }

        // 获取总数
        var total = await query.CountAsync();

        // 获取列表
        var records = await query
            .OrderByDescending(r => r.Addtime)
            .ThenBy(r => r.Id)
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        // 获取用户信息
        var userIds2 = records.Select(r => r.UserId).Distinct().ToList();
        var usersData = await _dbContext.Users
            .Where(u => userIds2.Contains(u.Id))
            .Select(u => new { u.Id, u.Uid, u.Nickname, u.HeadImg, u.Mobile })
            .ToListAsync();
        var users = usersData.ToDictionary(u => u.Id, u => new UserBasicInfo { Id = u.Id, Uid = u.Uid, Nickname = u.Nickname, HeadImg = u.HeadImg, Mobile = u.Mobile });

        // 映射结果
        var list = records.Select(r => MapToLogResponse(r, users)).ToList();

        return PagedResult<RankLogResponse>.Create(list, total, request.Page, request.PageSize);
    }

    #endregion

    #region 月榜奖品管理

    /// <inheritdoc />
    public async Task<PagedResult<RankPrizeResponse>> GetMonthPrizesAsync(RankPrizeListRequest request)
    {
        return await GetPrizesAsync(MonthPrizeGoodsId, request);
    }

    /// <inheritdoc />
    public async Task<RankPrizeResponse?> GetMonthPrizeByIdAsync(int id)
    {
        return await GetPrizeByIdAsync(MonthPrizeGoodsId, id);
    }

    /// <inheritdoc />
    public async Task<int> CreateMonthPrizeAsync(RankPrizeCreateRequest request)
    {
        return await CreatePrizeAsync(MonthPrizeGoodsId, request);
    }

    /// <inheritdoc />
    public async Task<bool> UpdateMonthPrizeAsync(int id, RankPrizeUpdateRequest request)
    {
        return await UpdatePrizeAsync(MonthPrizeGoodsId, id, request);
    }

    /// <inheritdoc />
    public async Task<bool> DeleteMonthPrizeAsync(int id)
    {
        return await DeletePrizeAsync(MonthPrizeGoodsId, id);
    }

    /// <inheritdoc />
    public async Task<PagedResult<RankLogResponse>> GetMonthLogsAsync(RankLogListRequest request)
    {
        var query = _dbContext.RankMonths.AsNoTracking();

        // 应用用户ID过滤
        if (request.UserId.HasValue)
        {
            query = query.Where(r => r.UserId == request.UserId.Value);
        }

        // 应用手机号过滤
        if (!string.IsNullOrWhiteSpace(request.Mobile))
        {
            var userIds = await _dbContext.Users
                .Where(u => u.Mobile == request.Mobile)
                .Select(u => u.Id)
                .ToListAsync();
            query = query.Where(r => userIds.Contains(r.UserId));
        }

        // 获取总数
        var total = await query.CountAsync();

        // 获取列表
        var records = await query
            .OrderByDescending(r => r.Addtime)
            .ThenBy(r => r.Id)
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        // 获取用户信息
        var userIds2 = records.Select(r => r.UserId).Distinct().ToList();
        var usersData = await _dbContext.Users
            .Where(u => userIds2.Contains(u.Id))
            .Select(u => new { u.Id, u.Uid, u.Nickname, u.HeadImg, u.Mobile })
            .ToListAsync();
        var users = usersData.ToDictionary(u => u.Id, u => new UserBasicInfo { Id = u.Id, Uid = u.Uid, Nickname = u.Nickname, HeadImg = u.HeadImg, Mobile = u.Mobile });

        // 映射结果
        var list = records.Select(r => MapToLogResponse(r, users)).ToList();

        return PagedResult<RankLogResponse>.Create(list, total, request.Page, request.PageSize);
    }

    #endregion

    #region 用户排行榜

    /// <inheritdoc />
    public async Task<PagedResult<UserRankResponse>> GetUserRankAsync(UserRankListRequest request)
    {
        if (!UserRankTypes.IsValid(request.Type))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "无效的排行榜类型");
        }

        return request.Type switch
        {
            UserRankTypes.Invite => await GetInviteRankAsync(request),
            UserRankTypes.Loss => await GetLossRankAsync(request),
            UserRankTypes.DadaCoin => await GetDadaCoinRankAsync(request),
            UserRankTypes.Diamond => await GetDiamondRankAsync(request),
            UserRankTypes.UUCoin => await GetUUCoinRankAsync(request),
            _ => PagedResult<UserRankResponse>.Create(new List<UserRankResponse>(), 0, request.Page, request.PageSize)
        };
    }

    #endregion

    #region 奖品类型

    /// <inheritdoc />
    public async Task<List<PrizeTypeResponse>> GetPrizeTypesAsync()
    {
        var prizeTypes = await _dbContext.PrizeLevels
            .AsNoTracking()
            .OrderBy(p => p.Sort)
            .ThenBy(p => p.Id)
            .Select(p => new PrizeTypeResponse
            {
                Id = p.Id,
                Title = p.Title ?? "",
                Sort = p.Sort
            })
            .ToListAsync();

        return prizeTypes;
    }

    #endregion


    #region Private Helper Methods - Prize Management

    /// <summary>
    /// 获取奖品列表（通用方法）
    /// </summary>
    private async Task<PagedResult<RankPrizeResponse>> GetPrizesAsync(int goodsId, RankPrizeListRequest request)
    {
        var query = _dbContext.GoodsItems
            .AsNoTracking()
            .Where(g => g.GoodsId == goodsId);

        // 应用关键词过滤
        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            query = query.Where(g => g.Title.Contains(request.Keyword));
        }

        // 获取总数
        var total = await query.CountAsync();

        // 获取列表
        var prizes = await query
            .OrderBy(g => g.Rank)
            .ThenBy(g => g.Id)
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        // 获取奖品等级信息
        var prizeTypeIds = prizes.Where(p => p.ShangId.HasValue).Select(p => p.ShangId!.Value).Distinct().ToList();
        var prizeTypes = await _dbContext.PrizeLevels
            .Where(p => prizeTypeIds.Contains(p.Id))
            .ToDictionaryAsync(p => p.Id, p => p.Title ?? "");

        // 映射结果
        var list = prizes.Select(p => MapToPrizeResponse(p, prizeTypes)).ToList();

        return PagedResult<RankPrizeResponse>.Create(list, total, request.Page, request.PageSize);
    }

    /// <summary>
    /// 获取奖品详情（通用方法）
    /// </summary>
    private async Task<RankPrizeResponse?> GetPrizeByIdAsync(int goodsId, int id)
    {
        var prize = await _dbContext.GoodsItems
            .AsNoTracking()
            .FirstOrDefaultAsync(g => g.Id == id && g.GoodsId == goodsId);

        if (prize == null) return null;

        // 获取奖品等级信息
        string prizeTypeName = "";
        if (prize.ShangId.HasValue)
        {
            var prizeType = await _dbContext.PrizeLevels
                .Where(p => p.Id == prize.ShangId.Value)
                .Select(p => p.Title)
                .FirstOrDefaultAsync();
            prizeTypeName = prizeType ?? "";
        }

        return new RankPrizeResponse
        {
            Id = prize.Id,
            Rank = prize.Rank,
            Title = prize.Title,
            ImgUrl = prize.ImgUrl,
            Price = prize.Price,
            CostPrice = prize.Money,
            PrizeTypeId = prize.ShangId ?? 0,
            PrizeTypeName = prizeTypeName,
            CreatedAt = prize.CreatedAt
        };
    }

    /// <summary>
    /// 创建奖品（通用方法）
    /// </summary>
    private async Task<int> CreatePrizeAsync(int goodsId, RankPrizeCreateRequest request)
    {
        // 验证必填字段
        ValidatePrizeRequest(request);

        // 验证排名唯一性
        var rankExists = await _dbContext.GoodsItems
            .AnyAsync(g => g.GoodsId == goodsId && g.Rank == request.Rank);
        if (rankExists)
        {
            throw new BusinessException(BusinessErrorCodes.Conflict, "该排名已存在");
        }

        var now = DateTime.Now;
        var prizeCode = $"{Guid.NewGuid():N}_{DateTimeOffset.Now.ToUnixTimeSeconds()}";

        var prize = new GoodsItem
        {
            GoodsId = goodsId,
            Num = 0,
            Title = request.Title,
            ImgUrl = request.ImgUrl,
            Stock = 1,
            SurplusStock = 1,
            Price = request.Price,
            Money = request.CostPrice,
            ScMoney = 0,
            RealPro = 0,
            GoodsType = 1,
            Sort = 0,
            ShangId = request.PrizeTypeId,
            RewardNum = 0,
            Rank = request.Rank,
            GiveMoney = 0,
            SpecialStock = -100,
            PrizeCode = prizeCode,
            CreatedAt = now,
            UpdatedAt = now,
            PrizeNum = 0,
            Type = 0,
            LianJiType = 0,
            Doubling = 0,
            GoodsListId = 0,
            IsLingzhu = 0
        };

        _dbContext.GoodsItems.Add(prize);
        await _dbContext.SaveChangesAsync();

        var rankType = goodsId == WeekPrizeGoodsId ? "周榜" : "月榜";
        _logger.LogInformation("创建{RankType}奖品成功: Id={Id}, Title={Title}, Rank={Rank}", 
            rankType, prize.Id, prize.Title, prize.Rank);

        return prize.Id;
    }

    /// <summary>
    /// 更新奖品（通用方法）
    /// </summary>
    private async Task<bool> UpdatePrizeAsync(int goodsId, int id, RankPrizeUpdateRequest request)
    {
        var prize = await _dbContext.GoodsItems
            .FirstOrDefaultAsync(g => g.Id == id && g.GoodsId == goodsId);
        if (prize == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "奖品不存在");
        }

        // 验证必填字段
        ValidatePrizeRequest(request);

        // 验证排名唯一性（排除自身）
        var rankExists = await _dbContext.GoodsItems
            .AnyAsync(g => g.GoodsId == goodsId && g.Rank == request.Rank && g.Id != id);
        if (rankExists)
        {
            throw new BusinessException(BusinessErrorCodes.Conflict, "该排名已存在");
        }

        prize.Rank = request.Rank;
        prize.Title = request.Title;
        prize.ImgUrl = request.ImgUrl;
        prize.Price = request.Price;
        prize.Money = request.CostPrice;
        prize.ShangId = request.PrizeTypeId;
        prize.UpdatedAt = DateTime.Now;

        var result = await _dbContext.SaveChangesAsync() > 0;

        var rankType = goodsId == WeekPrizeGoodsId ? "周榜" : "月榜";
        _logger.LogInformation("更新{RankType}奖品成功: Id={Id}, Title={Title}, Rank={Rank}", 
            rankType, id, prize.Title, prize.Rank);

        return result;
    }

    /// <summary>
    /// 删除奖品（通用方法）
    /// </summary>
    private async Task<bool> DeletePrizeAsync(int goodsId, int id)
    {
        var prize = await _dbContext.GoodsItems
            .FirstOrDefaultAsync(g => g.Id == id && g.GoodsId == goodsId);
        if (prize == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "奖品不存在");
        }

        _dbContext.GoodsItems.Remove(prize);
        var result = await _dbContext.SaveChangesAsync() > 0;

        var rankType = goodsId == WeekPrizeGoodsId ? "周榜" : "月榜";
        _logger.LogInformation("删除{RankType}奖品成功: Id={Id}, Title={Title}", 
            rankType, id, prize.Title);

        return result;
    }

    /// <summary>
    /// 验证奖品请求参数
    /// </summary>
    private void ValidatePrizeRequest(RankPrizeCreateRequest request)
    {
        if (request.Rank <= 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "排名必须大于0");
        }

        if (string.IsNullOrWhiteSpace(request.Title))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖品名称不能为空");
        }

        if (string.IsNullOrWhiteSpace(request.ImgUrl))
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "奖品图片不能为空");
        }

        if (request.Price < 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "售价不能为负数");
        }

        if (request.CostPrice < 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "采购价不能为负数");
        }
    }

    /// <summary>
    /// 映射奖品实体到响应模型
    /// </summary>
    private RankPrizeResponse MapToPrizeResponse(GoodsItem prize, Dictionary<int, string> prizeTypes)
    {
        string prizeTypeName = "";
        if (prize.ShangId.HasValue && prizeTypes.TryGetValue(prize.ShangId.Value, out var prizeType))
        {
            prizeTypeName = prizeType ?? "";
        }

        return new RankPrizeResponse
        {
            Id = prize.Id,
            Rank = prize.Rank,
            Title = prize.Title,
            ImgUrl = prize.ImgUrl,
            Price = prize.Price,
            CostPrice = prize.Money,
            PrizeTypeId = prize.ShangId ?? 0,
            PrizeTypeName = prizeTypeName,
            CreatedAt = prize.CreatedAt
        };
    }

    /// <summary>
    /// 映射周榜中奖记录到响应模型
    /// </summary>
    private RankLogResponse MapToLogResponse(RankWeek record, Dictionary<int, UserBasicInfo> users)
    {
        users.TryGetValue(record.UserId, out var user);
        return new RankLogResponse
        {
            Id = record.Id,
            UserId = record.UserId,
            Uid = user?.Uid ?? "",
            Nickname = user?.Nickname ?? "",
            HeadImg = user?.HeadImg ?? "",
            Mobile = user?.Mobile ?? "",
            Rank = record.Rank,
            PrizeTitle = record.PrizeTitle ?? "",
            PrizeImgUrl = record.PrizeImgUrl ?? "",
            ConsumeAmount = record.Money,
            TimeRange = record.WeekTime,
            CreatedAt = DateTimeOffset.FromUnixTimeSeconds(record.Addtime).LocalDateTime
        };
    }

    /// <summary>
    /// 映射月榜中奖记录到响应模型
    /// </summary>
    private RankLogResponse MapToLogResponse(RankMonth record, Dictionary<int, UserBasicInfo> users)
    {
        users.TryGetValue(record.UserId, out var user);
        return new RankLogResponse
        {
            Id = record.Id,
            UserId = record.UserId,
            Uid = user?.Uid ?? "",
            Nickname = user?.Nickname ?? "",
            HeadImg = user?.HeadImg ?? "",
            Mobile = user?.Mobile ?? "",
            Rank = record.Rank,
            PrizeTitle = record.PrizeTitle ?? "",
            PrizeImgUrl = record.PrizeImgUrl ?? "",
            ConsumeAmount = record.Money,
            TimeRange = record.MonthTime,
            CreatedAt = DateTimeOffset.FromUnixTimeSeconds(record.Addtime).LocalDateTime
        };
    }

    /// <summary>
    /// 用户基本信息（用于映射）
    /// </summary>
    private class UserBasicInfo
    {
        public int Id { get; set; }
        public string? Uid { get; set; }
        public string? Nickname { get; set; }
        public string? HeadImg { get; set; }
        public string? Mobile { get; set; }
    }

    #endregion


    #region Private Helper Methods - User Rank

    /// <summary>
    /// 获取邀请新人排行榜
    /// </summary>
    private async Task<PagedResult<UserRankResponse>> GetInviteRankAsync(UserRankListRequest request)
    {
        // 查询邀请排行
        var query = _dbContext.Users
            .Where(u => u.Pid > 0 && u.IsTest == 0 && u.Status == 1)
            .GroupBy(u => u.Pid)
            .Select(g => new
            {
                UserId = g.Key,
                Value = (decimal)g.Count()
            })
            .Where(x => x.Value > 0)
            .OrderByDescending(x => x.Value);

        var total = await query.CountAsync();

        var rankData = await query
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        return await BuildUserRankResultAsync(rankData, request, total, "人");
    }

    /// <summary>
    /// 获取亏损补贴排行榜
    /// </summary>
    private async Task<PagedResult<UserRankResponse>> GetLossRankAsync(UserRankListRequest request)
    {
        // 获取测试用户ID列表
        var testUserIds = await _dbContext.Users
            .Where(u => u.IsTest > 0)
            .Select(u => u.Id)
            .ToListAsync();

        // 查询订单消费数据
        var orderData = await _dbContext.Orders
            .Where(o => o.Status == 1 && !testUserIds.Contains(o.UserId))
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                ConsumeMoney = g.Sum(o => o.Price)
            })
            .ToListAsync();

        // 获取所有相关用户ID
        var userIds = orderData.Select(o => o.UserId).ToList();

        // 查询出货金额
        var outputData = await _dbContext.OrderItems
            .Where(o => userIds.Contains(o.UserId))
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                OutputMoney = g.Sum(o => o.GoodslistMoney)
            })
            .ToDictionaryAsync(x => x.UserId, x => x.OutputMoney);

        // 查询达达卷金额
        var dadaData = await _dbContext.OrderItemsRecoveries
            .Where(o => userIds.Contains(o.UserId))
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                DadaMoney = g.Sum(o => o.Money)
            })
            .ToDictionaryAsync(x => x.UserId, x => x.DadaMoney);

        // 计算亏损并排序
        var lossData = orderData
            .Select(o =>
            {
                var outputMoney = outputData.GetValueOrDefault(o.UserId, 0);
                var dadaMoney = dadaData.GetValueOrDefault(o.UserId, 0);
                var lossMoney = outputMoney - (o.ConsumeMoney + dadaMoney);
                var lossRate = o.ConsumeMoney > 0 ? Math.Abs(lossMoney) / o.ConsumeMoney * 100 : 0;
                return new 
                { 
                    o.UserId, 
                    LossMoney = lossMoney, 
                    ConsumeMoney = o.ConsumeMoney,
                    OutputMoney = outputMoney,
                    DadaMoney = dadaMoney,
                    LossRate = lossRate
                };
            })
            .Where(x => x.LossMoney < 0) // 只显示亏损用户
            .OrderBy(x => x.LossMoney) // 亏损越多排名越前
            .ToList();

        var total = lossData.Count;

        var pagedData = lossData
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToList();

        // 获取用户信息
        var lossUserIds = pagedData.Select(x => x.UserId).ToList();
        var users = await _dbContext.Users
            .Where(u => lossUserIds.Contains(u.Id))
            .Select(u => new { u.Id, u.Uid, u.Nickname, u.HeadImg })
            .ToDictionaryAsync(u => u.Id);

        // 构建排行榜数据
        var result = new List<UserRankResponse>();
        var offset = request.Skip;
        for (int i = 0; i < pagedData.Count; i++)
        {
            var item = pagedData[i];
            var userInfo = users.GetValueOrDefault(item.UserId);
            if (userInfo != null)
            {
                result.Add(new UserRankResponse
                {
                    Rank = offset + i + 1,
                    UserId = item.UserId,
                    Uid = userInfo.Uid ?? "",
                    Nickname = userInfo.Nickname ?? "",
                    HeadImg = userInfo.HeadImg ?? "",
                    Value = Math.Abs(item.LossMoney),
                    Unit = "元",
                    ConsumeAmount = item.ConsumeMoney,
                    DadaCoinAmount = item.DadaMoney,
                    ShipAmount = item.OutputMoney,
                    LossRate = Math.Round(item.LossRate, 2)
                });
            }
        }

        return PagedResult<UserRankResponse>.Create(result, total, request.Page, request.PageSize);
    }

    /// <summary>
    /// 获取达达券排行榜
    /// </summary>
    private async Task<PagedResult<UserRankResponse>> GetDadaCoinRankAsync(UserRankListRequest request)
    {
        // 获取测试用户ID列表
        var testUserIds = await _dbContext.Users
            .Where(u => u.IsTest > 0 && u.Status == 1)
            .Select(u => u.Id)
            .ToListAsync();

        // 查询达达卷回收排行
        var query = _dbContext.OrderItemsRecoveries
            .Where(o => o.Money > 0 && !testUserIds.Contains(o.UserId))
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                Value = g.Sum(o => o.Money) * 100 // 转换为达达卷单位
            })
            .OrderByDescending(x => x.Value);

        var total = await query.CountAsync();

        var rankData = await query
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        return await BuildUserRankResultAsync(rankData, request, total, "达达券");
    }

    /// <summary>
    /// 获取钻石排行榜
    /// </summary>
    private async Task<PagedResult<UserRankResponse>> GetDiamondRankAsync(UserRankListRequest request)
    {
        // 获取测试用户ID列表
        var testUserIds = await _dbContext.Users
            .Where(u => u.IsTest > 0 && u.Status == 1)
            .Select(u => u.Id)
            .ToListAsync();

        // 查询钻石消费排行
        var query = _dbContext.Orders
            .Where(o => o.Status == 1 && o.UseMoney > 0 && !testUserIds.Contains(o.UserId))
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                Value = g.Sum(o => o.UseMoney)
            })
            .OrderByDescending(x => x.Value);

        var total = await query.CountAsync();

        var rankData = await query
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        return await BuildUserRankResultAsync(rankData, request, total, "钻石");
    }

    /// <summary>
    /// 获取UU币排行榜
    /// </summary>
    private async Task<PagedResult<UserRankResponse>> GetUUCoinRankAsync(UserRankListRequest request)
    {
        // 获取测试用户ID列表
        var testUserIds = await _dbContext.Users
            .Where(u => u.IsTest > 0 && u.Status == 1)
            .Select(u => u.Id)
            .ToListAsync();

        // 查询积分消费排行
        var query = _dbContext.Orders
            .Where(o => o.Status == 1 && o.UseIntegral > 0 && !testUserIds.Contains(o.UserId))
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                Value = g.Sum(o => o.UseIntegral)
            })
            .OrderByDescending(x => x.Value);

        var total = await query.CountAsync();

        var rankData = await query
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        return await BuildUserRankResultAsync(rankData, request, total, "UU币");
    }

    /// <summary>
    /// 构建用户排行榜结果
    /// </summary>
    private async Task<PagedResult<UserRankResponse>> BuildUserRankResultAsync<T>(
        List<T> rankData,
        UserRankListRequest request,
        int total,
        string unit) where T : class
    {
        // 使用反射获取UserId和Value属性
        var userIdProp = typeof(T).GetProperty("UserId");
        var valueProp = typeof(T).GetProperty("Value");

        if (userIdProp == null || valueProp == null)
        {
            return PagedResult<UserRankResponse>.Create(new List<UserRankResponse>(), 0, request.Page, request.PageSize);
        }

        var userIds = rankData.Select(r => (int)userIdProp.GetValue(r)!).ToList();
        var users = await _dbContext.Users
            .Where(u => userIds.Contains(u.Id))
            .Select(u => new { u.Id, u.Uid, u.Nickname, u.HeadImg })
            .ToDictionaryAsync(u => u.Id);

        var result = new List<UserRankResponse>();
        var offset = request.Skip;

        for (int i = 0; i < rankData.Count; i++)
        {
            var item = rankData[i];
            var userId = (int)userIdProp.GetValue(item)!;
            var value = Convert.ToDecimal(valueProp.GetValue(item));
            var userInfo = users.GetValueOrDefault(userId);

            if (userInfo != null)
            {
                result.Add(new UserRankResponse
                {
                    Rank = offset + i + 1,
                    UserId = userId,
                    Uid = userInfo.Uid ?? "",
                    Nickname = userInfo.Nickname ?? "",
                    HeadImg = userInfo.HeadImg ?? "",
                    Value = value,
                    Unit = unit
                });
            }
        }

        return PagedResult<UserRankResponse>.Create(result, total, request.Page, request.PageSize);
    }

    #endregion
}
