using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.User;
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 UserBusinessService : IUserBusinessService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<UserBusinessService> _logger;

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

    #region 用户列表和详情

    /// <inheritdoc />
    public async Task<PagedResult<UserListResponse>> GetUserListAsync(UserListRequest request)
    {
        var query = _dbContext.Users.AsNoTracking();

        // 应用过滤条件
        query = ApplyUserFilters(query, request);

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

        // 获取用户列表
        var users = await query
            .OrderByDescending(u => u.Id)
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToListAsync();

        // 获取用户ID列表
        var userIds = users.Select(u => u.Id).ToList();

        // 获取最后登录IP
        var loginIps = await GetLastLoginIpsAsync(userIds);

        // 获取消费统计
        var consumptionStats = await GetUserConsumptionStatsAsync(userIds);

        // 映射结果
        var list = users.Select(u => MapToUserListResponse(u, loginIps, consumptionStats)).ToList();

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

    /// <inheritdoc />
    public async Task<UserDetailResponse?> GetUserDetailAsync(int userId)
    {
        var user = await _dbContext.Users
            .AsNoTracking()
            .FirstOrDefaultAsync(u => u.Id == userId);

        if (user == null)
        {
            return null;
        }

        // 获取最后登录IP
        var loginIps = await GetLastLoginIpsAsync(new List<int> { userId });

        // 获取消费统计
        var consumptionStats = await GetUserConsumptionStatsAsync(new List<int> { userId });

        var response = new UserDetailResponse
        {
            Id = user.Id,
            Uid = user.Uid,
            Nickname = user.Nickname,
            Avatar = user.HeadImg,
            Mobile = user.Mobile,
            Balance = user.Money,
            Integral = user.Integral,
            Diamond = user.Score,
            EquityLevel = user.Vip,
            CreatedAt = user.CreatedAt,
            LastLoginIp = loginIps.GetValueOrDefault(userId),
            Status = user.Status,
            IsTest = user.IsTest,
            ParentId = user.Pid,
            OpenId = user.OpenId,
            UnionId = user.UnionId,
            GzhOpenId = user.GzhOpenId,
            LastLoginTime = user.LastLoginTime,
            OuQi = user.OuQi,
            DrawNum = user.DrawNum
        };

        // 填充消费统计
        if (consumptionStats.TryGetValue(userId, out var stats))
        {
            response.TotalConsumption = stats.TotalConsumption;
            response.BoxValue = stats.BoxValue;
            response.WeChatPayment = stats.WeChatPayment;
            response.BalancePayment = stats.BalancePayment;
            response.IntegralPayment = stats.IntegralPayment;
            response.RecoveryAmount = stats.RecoveryAmount;
            response.ShippingValue = stats.ShippingValue;
        }

        return response;
    }

    #endregion


    #region 资金变动

    /// <inheritdoc />
    public async Task<bool> ChangeUserMoneyAsync(int userId, UserMoneyChangeRequest request, int operatorId)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 计算实际变动金额（扣除时为负数）
        var changeAmount = request.Operation == OperationType.Add ? request.Amount : -request.Amount;
        var remark = request.Remark ?? (request.Operation == OperationType.Add ? "后台增加" : "后台扣除");

        using var transaction = await _dbContext.Database.BeginTransactionAsync();
        try
        {
            switch (request.Type)
            {
                case MoneyChangeType.Balance:
                    await ChangeBalanceAsync(user, changeAmount, remark, operatorId);
                    break;
                case MoneyChangeType.Integral:
                    await ChangeIntegralAsync(user, changeAmount, remark, operatorId);
                    break;
                case MoneyChangeType.Diamond:
                    await ChangeDiamondAsync(user, changeAmount, remark, operatorId);
                    break;
                default:
                    throw new BusinessException(BusinessErrorCodes.ValidationFailed, "无效的变动类型");
            }

            await _dbContext.SaveChangesAsync();
            await transaction.CommitAsync();

            _logger.LogInformation("用户资金变动成功: UserId={UserId}, Type={Type}, Amount={Amount}, Operator={Operator}",
                userId, request.Type, changeAmount, operatorId);

            return true;
        }
        catch (Exception ex) when (ex is not BusinessException)
        {
            await transaction.RollbackAsync();
            _logger.LogError(ex, "用户资金变动失败: UserId={UserId}", userId);
            throw new BusinessException(BusinessErrorCodes.InternalError, "资金变动失败，请稍后重试");
        }
    }

    private async Task ChangeBalanceAsync(User user, decimal changeAmount, string remark, int operatorId)
    {
        var newBalance = user.Money + changeAmount;
        if (newBalance < 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "余额不足");
        }

        user.Money = newBalance;
        user.UpdatedAt = DateTime.Now;

        // 记录变动日志
        var profitMoney = new ProfitMoney
        {
            UserId = user.Id,
            ChangeMoney = changeAmount,
            Money = newBalance,
            Type = (byte)(changeAmount > 0 ? 1 : 2), // 1-增加 2-扣除
            Content = remark,
            ShareUid = operatorId,
            CreatedAt = DateTime.Now
        };
        _dbContext.ProfitMoneys.Add(profitMoney);
    }

    private async Task ChangeIntegralAsync(User user, decimal changeAmount, string remark, int operatorId)
    {
        var newIntegral = user.Integral + changeAmount;
        if (newIntegral < 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "积分不足");
        }

        user.Integral = newIntegral;
        user.UpdatedAt = DateTime.Now;

        // 记录变动日志
        var profitIntegral = new ProfitIntegral
        {
            UserId = user.Id,
            ChangeMoney = changeAmount,
            Money = newIntegral,
            Type = (byte)(changeAmount > 0 ? 1 : 2),
            Content = remark,
            ShareUid = operatorId,
            CreatedAt = DateTime.Now
        };
        _dbContext.ProfitIntegrals.Add(profitIntegral);
    }

    private async Task ChangeDiamondAsync(User user, decimal changeAmount, string remark, int operatorId)
    {
        var newDiamond = (user.Money2 ?? 0) + changeAmount;
        if (newDiamond < 0)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "哈尼券不足");
        }

        user.Money2 = newDiamond;
        user.UpdatedAt = DateTime.Now;

        // 记录变动日志到 ProfitMoney2 表
        var profitMoney2 = new ProfitMoney2
        {
            UserId = user.Id,
            ChangeMoney = changeAmount,
            Money = newDiamond,
            Type = (byte)(changeAmount > 0 ? 1 : 2),
            Content = remark,
            ShareUid = operatorId,
            CreatedAt = DateTime.Now
        };
        _dbContext.ProfitMoney2s.Add(profitMoney2);
    }

    #endregion


    #region 状态管理

    /// <inheritdoc />
    public async Task<bool> SetUserStatusAsync(int userId, int status)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        user.Status = (byte)status;
        user.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("用户状态变更: UserId={UserId}, Status={Status}", userId, status);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> SetTestAccountAsync(int userId, int isTest)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        user.IsTest = isTest;
        user.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("测试账号设置: UserId={UserId}, IsTest={IsTest}", userId, isTest);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> ClearMobileAsync(int userId)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 保存旧手机号
        user.OldMobile = user.Mobile;
        user.Mobile = null;
        user.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("清空手机号: UserId={UserId}", userId);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> ClearWeChatAsync(int userId)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 生成新的随机openid
        user.OpenId = GenerateRandomOpenId();
        user.UnionId = null;
        user.GzhOpenId = null;
        user.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("清空微信绑定: UserId={UserId}", userId);

        return result;
    }

    private static string GenerateRandomOpenId()
    {
        return $"cleared_{Guid.NewGuid():N}";
    }

    #endregion


    #region 赠送功能

    /// <inheritdoc />
    public async Task<bool> GiftCouponAsync(int userId, GiftCouponRequest request)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 获取优惠券模板 (status=0 表示有效/上架)
        var coupon = await _dbContext.Coupons.FirstOrDefaultAsync(c => c.Id == request.CouponId && c.Status == 0);
        if (coupon == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "优惠券不存在或已禁用");
        }

        // 计算过期时间
        var endTime = coupon.EffectiveDay.HasValue
            ? DateTime.Now.AddDays(coupon.EffectiveDay.Value)
            : DateTime.Now.AddDays(30); // 默认30天

        // 创建优惠券领取记录
        var couponReceives = new List<CouponReceife>();
        for (int i = 0; i < request.Quantity; i++)
        {
            couponReceives.Add(new CouponReceife
            {
                Title = coupon.Title,
                Price = coupon.Price,
                ManPrice = coupon.ManPrice,
                EndTime = endTime,
                UserId = userId,
                CouponId = coupon.Id,
                Status = 0, // 可用状态
                State = 0, // 未使用
                Ttype = coupon.Ttype ?? 0,
                CreatedAt = DateTime.Now
            });
        }

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

        _logger.LogInformation("赠送优惠券: UserId={UserId}, CouponId={CouponId}, Quantity={Quantity}",
            userId, request.CouponId, request.Quantity);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> GiftCardAsync(int userId, GiftCardRequest request)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 获取商品信息
        var goods = await _dbContext.Goods.FirstOrDefaultAsync(g => g.Id == request.GoodsId);
        if (goods == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "商品不存在");
        }

        // 获取奖品信息
        var goodsItem = await _dbContext.GoodsItems.FirstOrDefaultAsync(gi => gi.Id == request.GoodsListId);
        if (goodsItem == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "奖品不存在");
        }

        // 生成订单号
        var orderNum = GenerateOrderNum();
        var now = DateTime.Now;
        var timestamp = (int)((DateTimeOffset)now).ToUnixTimeSeconds();

        // 创建订单（order_type=9 表示赠送）
        var order = new Order
        {
            UserId = userId,
            OrderNum = orderNum,
            OrderTotal = 0,
            OrderZheTotal = 0,
            Price = 0,
            UseMoney = 0,
            UseIntegral = 0,
            UseScore = 0,
            Zhe = 1,
            GoodsId = request.GoodsId,
            Num = request.Quantity,
            GoodsPrice = goods.Price,
            GoodsTitle = goods.Title,
            GoodsImgurl = goods.ImgUrl,
            PrizeNum = request.Quantity,
            Status = 1, // 已支付
            Addtime = timestamp,
            PayTime = timestamp,
            PayType = 0,
            OrderType = 9, // 赠送类型
            KdIs = 0,
            CreatedAt = now,
            UpdatedAt = now
        };

        _dbContext.Orders.Add(order);
        await _dbContext.SaveChangesAsync();

        // 创建订单详情
        var orderItems = new List<OrderItem>();
        for (int i = 0; i < request.Quantity; i++)
        {
            orderItems.Add(new OrderItem
            {
                OrderId = order.Id,
                UserId = userId,
                Status = 0, // 待处理
                GoodsId = request.GoodsId,
                Num = i + 1,
                ShangId = goodsItem.ShangId ?? 0,
                GoodslistId = goodsItem.Id,
                GoodslistTitle = goodsItem.Title,
                GoodslistImgurl = goodsItem.ImgUrl,
                GoodslistPrice = goodsItem.Price,
                GoodslistMoney = goodsItem.Money,
                GoodslistType = goodsItem.Type,
                GoodslistSaleTime = timestamp,
                Addtime = timestamp,
                ChoiceTime = 0,
                InsuranceIs = 0,
                OrderType = 9,
                OrderListId = 0,
                LuckNo = 0,
                PrizeCode = GeneratePrizeCode(),
                Source = 2, // 赠送来源
                FhStatus = 0,
                Doubling = 1,
                ParentGoodsListId = 0,
                IsLingzhu = 0,
                CreatedAt = now,
                UpdatedAt = now
            });
        }

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

        _logger.LogInformation("赠送卡牌: UserId={UserId}, GoodsId={GoodsId}, GoodsListId={GoodsListId}, Quantity={Quantity}",
            userId, request.GoodsId, request.GoodsListId, request.Quantity);

        return result;
    }

    private static string GenerateOrderNum()
    {
        return $"GIFT{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";
    }

    private static string GeneratePrizeCode()
    {
        return $"PC{DateTime.Now:yyyyMMddHHmmss}{Guid.NewGuid().ToString("N")[..8].ToUpper()}";
    }

    #endregion


    #region 统计功能

    /// <inheritdoc />
    public async Task<UserProfitLossResponse> GetUserProfitLossAsync(int userId, DateRange? dateRange)
    {
        var user = await _dbContext.Users
            .AsNoTracking()
            .FirstOrDefaultAsync(u => u.Id == userId);

        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 构建日期过滤条件
        var startDate = dateRange?.StartDate ?? DateTime.MinValue;
        var endDate = dateRange?.EndDate ?? DateTime.MaxValue;

        // 计算总充值金额
        var totalRecharge = await _dbContext.ProfitPays
            .Where(p => p.UserId == userId && p.CreatedAt >= startDate && p.CreatedAt <= endDate)
            .SumAsync(p => (decimal?)p.ChangeMoney) ?? 0;

        // 计算总消费金额（已支付订单）
        var totalConsumption = await _dbContext.Orders
            .Where(o => o.UserId == userId && o.Status == 1 && o.CreatedAt >= startDate && o.CreatedAt <= endDate)
            .SumAsync(o => (decimal?)o.Price) ?? 0;

        // 计算总回收金额
        var totalRecovery = await _dbContext.OrderItemsRecoveries
            .Where(r => r.UserId == userId && r.CreatedAt >= startDate && r.CreatedAt <= endDate)
            .SumAsync(r => (decimal?)r.Money) ?? 0;

        // 计算总发货价值（通过关联订单详情计算）
        var totalShippingValue = await _dbContext.OrderItems
            .Where(oi => oi.UserId == userId && oi.Status == 2 && oi.CreatedAt >= startDate && oi.CreatedAt <= endDate)
            .SumAsync(oi => (decimal?)oi.GoodslistPrice) ?? 0;

        // 计算盒柜价值（未处理的奖品）
        var boxValue = await _dbContext.OrderItems
            .Where(oi => oi.UserId == userId && oi.Status == 0)
            .SumAsync(oi => (decimal?)oi.GoodslistPrice) ?? 0;

        // 计算盈亏：充值 - 消费 + 回收 + 发货价值 + 盒柜价值 + 当前余额
        var profitLoss = totalRecharge - totalConsumption + totalRecovery + totalShippingValue + boxValue;

        return new UserProfitLossResponse
        {
            UserId = userId,
            TotalRecharge = totalRecharge,
            TotalConsumption = totalConsumption,
            TotalRecovery = totalRecovery,
            TotalShippingValue = totalShippingValue,
            CurrentBalance = user.Money,
            CurrentIntegral = user.Integral,
            CurrentDiamond = user.Score,
            ProfitLoss = profitLoss,
            BoxValue = boxValue
        };
    }

    /// <inheritdoc />
    public async Task<PagedResult<UserListResponse>> GetSubordinateUsersAsync(int userId, int page, int pageSize)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var query = _dbContext.Users
            .AsNoTracking()
            .Where(u => u.Pid == userId);

        var total = await query.CountAsync();

        var users = await query
            .OrderByDescending(u => u.Id)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        var userIds = users.Select(u => u.Id).ToList();
        var loginIps = await GetLastLoginIpsAsync(userIds);
        var consumptionStats = await GetUserConsumptionStatsAsync(userIds);

        var list = users.Select(u => MapToUserListResponse(u, loginIps, consumptionStats)).ToList();

        return PagedResult<UserListResponse>.Create(list, total, page, pageSize);
    }

    #endregion


    #region 用户详情相关

    /// <inheritdoc />
    public async Task<PagedResult<UserBoxItem>> GetUserBoxAsync(int userId, UserBoxQuery query)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var orderItemsQuery = _dbContext.OrderItems
            .AsNoTracking()
            .Where(oi => oi.UserId == userId);

        // 应用过滤条件
        if (query.Status.HasValue)
        {
            orderItemsQuery = orderItemsQuery.Where(oi => oi.Status == query.Status.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.GoodslistTitle))
        {
            orderItemsQuery = orderItemsQuery.Where(oi => oi.GoodslistTitle != null && oi.GoodslistTitle.Contains(query.GoodslistTitle));
        }

        if (query.StartTime.HasValue)
        {
            orderItemsQuery = orderItemsQuery.Where(oi => oi.CreatedAt >= query.StartTime.Value);
        }

        if (query.EndTime.HasValue)
        {
            var endDate = query.EndTime.Value.Date.AddDays(1);
            orderItemsQuery = orderItemsQuery.Where(oi => oi.CreatedAt < endDate);
        }

        var total = await orderItemsQuery.CountAsync();

        // 获取订单详情列表
        var orderItems = await orderItemsQuery
            .OrderByDescending(oi => oi.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .ToListAsync();

        // 获取关联的订单信息
        var orderIds = orderItems.Select(oi => oi.OrderId).Distinct().ToList();
        var orders = await _dbContext.Orders
            .AsNoTracking()
            .Where(o => orderIds.Contains(o.Id))
            .ToDictionaryAsync(o => o.Id, o => new { o.OrderNum, o.GoodsTitle });

        // 获取奖品等级信息
        var shangIds = orderItems.Select(oi => oi.ShangId).Distinct().ToList();
        var prizeLevels = await _dbContext.PrizeLevels
            .AsNoTracking()
            .Where(pl => shangIds.Contains(pl.Id))
            .ToDictionaryAsync(pl => pl.Id, pl => pl.Title);

        // 如果有盒子名称过滤，需要在内存中过滤
        var list = orderItems.Select(oi =>
        {
            var orderInfo = orders.GetValueOrDefault(oi.OrderId);
            return new UserBoxItem
            {
                Id = oi.Id,
                GoodslistTitle = oi.GoodslistTitle,
                GoodslistMoney = oi.GoodslistMoney,
                GoodslistPrice = oi.GoodslistPrice,
                GoodslistImgurl = oi.GoodslistImgurl,
                ShangId = oi.ShangId,
                ShangTitle = prizeLevels.GetValueOrDefault(oi.ShangId),
                Addtime = oi.CreatedAt,
                OrderId = oi.OrderId,
                OrderNum = orderInfo?.OrderNum,
                GoodsId = oi.GoodsId,
                GoodTitle = orderInfo?.GoodsTitle,
                Status = oi.Status,
                FhStatus = oi.FhStatus,
                FhRemarks = oi.FhRemarks
            };
        }).ToList();

        // 如果有盒子名称过滤，在内存中过滤
        if (!string.IsNullOrWhiteSpace(query.GoodTitle))
        {
            list = list.Where(item => item.GoodTitle != null && item.GoodTitle.Contains(query.GoodTitle)).ToList();
        }

        return PagedResult<UserBoxItem>.Create(list, total, query.Page, query.PageSize);
    }

    /// <inheritdoc />
    public async Task<PagedResult<UserOrderItem>> GetUserOrdersAsync(int userId, UserOrderQuery query)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var ordersQuery = _dbContext.Orders
            .AsNoTracking()
            .Where(o => o.UserId == userId);

        // 应用过滤条件
        if (query.Status.HasValue)
        {
            ordersQuery = ordersQuery.Where(o => o.Status == query.Status.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.OrderNum))
        {
            ordersQuery = ordersQuery.Where(o => o.OrderNum.Contains(query.OrderNum));
        }

        if (query.StartTime.HasValue)
        {
            ordersQuery = ordersQuery.Where(o => o.CreatedAt >= query.StartTime.Value);
        }

        if (query.EndTime.HasValue)
        {
            var endDate = query.EndTime.Value.Date.AddDays(1);
            ordersQuery = ordersQuery.Where(o => o.CreatedAt < endDate);
        }

        var total = await ordersQuery.CountAsync();

        var orders = await ordersQuery
            .OrderByDescending(o => o.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .Select(o => new UserOrderItem
            {
                Id = o.Id,
                OrderNum = o.OrderNum,
                GoodsId = o.GoodsId,
                GoodsTitle = o.GoodsTitle,
                GoodsImgurl = o.GoodsImgurl,
                GoodsPrice = o.GoodsPrice,
                Num = o.Num,
                OrderTotal = o.OrderTotal,
                OrderZheTotal = o.OrderZheTotal,
                Price = o.Price,
                UseMoney = o.UseMoney,
                UseIntegral = o.UseIntegral,
                UseScore = o.UseScore,
                UseCoupon = o.UseCoupon,
                Zhe = o.Zhe,
                PrizeNum = o.PrizeNum,
                Status = o.Status,
                PayType = o.PayType,
                OrderType = o.OrderType,
                CreatedAt = o.CreatedAt,
                PayTime = o.PayTime > 0 ? DateTimeOffset.FromUnixTimeSeconds(o.PayTime).LocalDateTime : null
            })
            .ToListAsync();

        return PagedResult<UserOrderItem>.Create(orders, total, query.Page, query.PageSize);
    }

    /// <inheritdoc />
    public async Task<PagedResult<MoneyDetailItem>> GetUserMoneyDetailAsync(int userId, MoneyDetailQuery query)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var detailQuery = _dbContext.ProfitMoneys
            .AsNoTracking()
            .Where(pm => pm.UserId == userId);

        // 应用过滤条件
        detailQuery = ApplyMoneyDetailFilters(detailQuery, query);

        var total = await detailQuery.CountAsync();

        var details = await detailQuery
            .OrderByDescending(pm => pm.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .Select(pm => new MoneyDetailItem
            {
                Id = pm.Id,
                ChangeMoney = pm.ChangeMoney,
                Money = pm.Money,
                Type = pm.Type,
                Content = pm.Content,
                Other = pm.Other,
                Addtime = pm.CreatedAt
            })
            .ToListAsync();

        return PagedResult<MoneyDetailItem>.Create(details, total, query.Page, query.PageSize);
    }

    /// <inheritdoc />
    public async Task<PagedResult<MoneyDetailItem>> GetUserIntegralDetailAsync(int userId, MoneyDetailQuery query)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var detailQuery = _dbContext.ProfitIntegrals
            .AsNoTracking()
            .Where(pi => pi.UserId == userId);

        // 应用过滤条件
        if (query.Type.HasValue)
        {
            detailQuery = detailQuery.Where(pi => pi.Type == query.Type.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.ChangeType))
        {
            if (query.ChangeType == "add")
            {
                detailQuery = detailQuery.Where(pi => pi.ChangeMoney > 0);
            }
            else if (query.ChangeType == "sub")
            {
                detailQuery = detailQuery.Where(pi => pi.ChangeMoney < 0);
            }
        }

        if (!string.IsNullOrWhiteSpace(query.Content))
        {
            detailQuery = detailQuery.Where(pi => pi.Content.Contains(query.Content));
        }

        if (query.StartTime.HasValue)
        {
            detailQuery = detailQuery.Where(pi => pi.CreatedAt >= query.StartTime.Value);
        }

        if (query.EndTime.HasValue)
        {
            var endDate = query.EndTime.Value.Date.AddDays(1);
            detailQuery = detailQuery.Where(pi => pi.CreatedAt < endDate);
        }

        var total = await detailQuery.CountAsync();

        var details = await detailQuery
            .OrderByDescending(pi => pi.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .Select(pi => new MoneyDetailItem
            {
                Id = pi.Id,
                ChangeMoney = pi.ChangeMoney,
                Money = pi.Money,
                Type = pi.Type,
                Content = pi.Content,
                Other = pi.Other,
                Addtime = pi.CreatedAt
            })
            .ToListAsync();

        return PagedResult<MoneyDetailItem>.Create(details, total, query.Page, query.PageSize);
    }

    /// <inheritdoc />
    public async Task<PagedResult<MoneyDetailItem>> GetUserMoney2DetailAsync(int userId, MoneyDetailQuery query)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var detailQuery = _dbContext.ProfitMoney2s
            .AsNoTracking()
            .Where(pm => pm.UserId == userId);

        // 应用过滤条件
        if (query.Type.HasValue)
        {
            detailQuery = detailQuery.Where(pm => pm.Type == query.Type.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.ChangeType))
        {
            if (query.ChangeType == "add")
            {
                detailQuery = detailQuery.Where(pm => pm.ChangeMoney > 0);
            }
            else if (query.ChangeType == "sub")
            {
                detailQuery = detailQuery.Where(pm => pm.ChangeMoney < 0);
            }
        }

        if (!string.IsNullOrWhiteSpace(query.Content))
        {
            detailQuery = detailQuery.Where(pm => pm.Content != null && pm.Content.Contains(query.Content));
        }

        if (query.StartTime.HasValue)
        {
            detailQuery = detailQuery.Where(pm => pm.CreatedAt >= query.StartTime.Value);
        }

        if (query.EndTime.HasValue)
        {
            var endDate = query.EndTime.Value.Date.AddDays(1);
            detailQuery = detailQuery.Where(pm => pm.CreatedAt < endDate);
        }

        var total = await detailQuery.CountAsync();

        var details = await detailQuery
            .OrderByDescending(pm => pm.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .Select(pm => new MoneyDetailItem
            {
                Id = pm.Id,
                ChangeMoney = pm.ChangeMoney,
                Money = pm.Money,
                Type = pm.Type,
                Content = pm.Content ?? "",
                Other = pm.Other,
                Addtime = pm.CreatedAt
            })
            .ToListAsync();

        return PagedResult<MoneyDetailItem>.Create(details, total, query.Page, query.PageSize);
    }

    /// <inheritdoc />
    public async Task<PagedResult<MoneyDetailItem>> GetUserScoreDetailAsync(int userId, MoneyDetailQuery query)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var detailQuery = _dbContext.ProfitScores
            .AsNoTracking()
            .Where(ps => ps.UserId == userId);

        // 应用过滤条件
        if (query.Type.HasValue)
        {
            detailQuery = detailQuery.Where(ps => ps.Type == query.Type.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.ChangeType))
        {
            if (query.ChangeType == "add")
            {
                detailQuery = detailQuery.Where(ps => ps.ChangeMoney > 0);
            }
            else if (query.ChangeType == "sub")
            {
                detailQuery = detailQuery.Where(ps => ps.ChangeMoney < 0);
            }
        }

        if (!string.IsNullOrWhiteSpace(query.Content))
        {
            detailQuery = detailQuery.Where(ps => ps.Content.Contains(query.Content));
        }

        if (query.StartTime.HasValue)
        {
            detailQuery = detailQuery.Where(ps => ps.CreatedAt >= query.StartTime.Value);
        }

        if (query.EndTime.HasValue)
        {
            var endDate = query.EndTime.Value.Date.AddDays(1);
            detailQuery = detailQuery.Where(ps => ps.CreatedAt < endDate);
        }

        var total = await detailQuery.CountAsync();

        var details = await detailQuery
            .OrderByDescending(ps => ps.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .Select(ps => new MoneyDetailItem
            {
                Id = ps.Id,
                ChangeMoney = ps.ChangeMoney,
                Money = ps.Money,
                Type = ps.Type,
                Content = ps.Content,
                Other = ps.Other,
                Addtime = ps.CreatedAt
            })
            .ToListAsync();

        return PagedResult<MoneyDetailItem>.Create(details, total, query.Page, query.PageSize);
    }

    /// <inheritdoc />
    public async Task<PagedResult<IpLogItem>> GetUserIpLogsAsync(int userId, int page, int pageSize)
    {
        // 验证用户存在
        var userExists = await _dbContext.Users.AnyAsync(u => u.Id == userId);
        if (!userExists)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        var logsQuery = _dbContext.UserLoginLogs
            .AsNoTracking()
            .Where(l => l.UserId == userId);

        var total = await logsQuery.CountAsync();

        var logs = await logsQuery
            .OrderByDescending(l => l.LoginTime)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(l => new IpLogItem
            {
                Id = l.Id,
                UserId = l.UserId,
                LoginDate = l.LoginDate,
                LoginTime = l.LoginTime,
                LastLoginTime = l.LastLoginTime,
                Device = l.Device,
                Ip = l.Ip,
                Location = l.Location
            })
            .ToListAsync();

        return PagedResult<IpLogItem>.Create(logs, total, page, pageSize);
    }

    /// <summary>
    /// 应用余额流水过滤条件
    /// </summary>
    private IQueryable<ProfitMoney> ApplyMoneyDetailFilters(IQueryable<ProfitMoney> query, MoneyDetailQuery filter)
    {
        if (filter.Type.HasValue)
        {
            query = query.Where(pm => pm.Type == filter.Type.Value);
        }

        if (!string.IsNullOrWhiteSpace(filter.ChangeType))
        {
            if (filter.ChangeType == "add")
            {
                query = query.Where(pm => pm.ChangeMoney > 0);
            }
            else if (filter.ChangeType == "sub")
            {
                query = query.Where(pm => pm.ChangeMoney < 0);
            }
        }

        if (!string.IsNullOrWhiteSpace(filter.Content))
        {
            query = query.Where(pm => pm.Content.Contains(filter.Content));
        }

        if (filter.StartTime.HasValue)
        {
            query = query.Where(pm => pm.CreatedAt >= filter.StartTime.Value);
        }

        if (filter.EndTime.HasValue)
        {
            var endDate = filter.EndTime.Value.Date.AddDays(1);
            query = query.Where(pm => pm.CreatedAt < endDate);
        }

        return query;
    }

    #endregion


    #region Private Helper Methods

    /// <summary>
    /// 应用用户过滤条件
    /// </summary>
    private IQueryable<User> ApplyUserFilters(IQueryable<User> query, UserListRequest request)
    {
        // 关键字搜索（支持用户ID、手机号、昵称）
        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            var keyword = request.Keyword.Trim();
            // 尝试解析为用户ID
            if (int.TryParse(keyword, out var keywordUserId))
            {
                query = query.Where(u =>
                    u.Id == keywordUserId ||
                    (u.Mobile != null && u.Mobile.Contains(keyword)) ||
                    u.Nickname.Contains(keyword));
            }
            else
            {
                query = query.Where(u =>
                    (u.Mobile != null && u.Mobile.Contains(keyword)) ||
                    u.Nickname.Contains(keyword));
            }
        }

        if (request.UserId.HasValue)
        {
            query = query.Where(u => u.Id == request.UserId.Value || u.Uid == request.UserId.ToString());
        }

        if (!string.IsNullOrWhiteSpace(request.Mobile))
        {
            query = query.Where(u => u.Mobile != null && u.Mobile.Contains(request.Mobile));
        }

        if (!string.IsNullOrWhiteSpace(request.Nickname))
        {
            query = query.Where(u => u.Nickname.Contains(request.Nickname));
        }

        if (request.StartDate.HasValue)
        {
            query = query.Where(u => u.CreatedAt >= request.StartDate.Value);
        }

        if (request.EndDate.HasValue)
        {
            var endDate = request.EndDate.Value.Date.AddDays(1);
            query = query.Where(u => u.CreatedAt < endDate);
        }

        if (request.ParentId.HasValue)
        {
            query = query.Where(u => u.Pid == request.ParentId.Value);
        }

        // 最后登录IP过滤需要通过子查询
        if (!string.IsNullOrWhiteSpace(request.LastLoginIp))
        {
            var userIdsWithIp = _dbContext.UserLoginLogs
                .Where(l => l.Ip != null && l.Ip.Contains(request.LastLoginIp))
                .Select(l => l.UserId)
                .Distinct();

            query = query.Where(u => userIdsWithIp.Contains(u.Id));
        }

        return query;
    }

    /// <summary>
    /// 获取用户最后登录IP
    /// </summary>
    private async Task<Dictionary<int, string?>> GetLastLoginIpsAsync(List<int> userIds)
    {
        if (!userIds.Any())
        {
            return new Dictionary<int, string?>();
        }

        var loginLogs = await _dbContext.UserLoginLogs
            .AsNoTracking()
            .Where(l => userIds.Contains(l.UserId))
            .GroupBy(l => l.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                Ip = g.OrderByDescending(l => l.LoginTime).Select(l => l.Ip).FirstOrDefault()
            })
            .ToListAsync();

        return loginLogs.ToDictionary(l => l.UserId, l => l.Ip);
    }

    /// <summary>
    /// 获取用户消费统计
    /// </summary>
    private async Task<Dictionary<int, UserConsumptionStats>> GetUserConsumptionStatsAsync(List<int> userIds)
    {
        if (!userIds.Any())
        {
            return new Dictionary<int, UserConsumptionStats>();
        }

        // 获取订单统计
        var orderStats = await _dbContext.Orders
            .AsNoTracking()
            .Where(o => userIds.Contains(o.UserId) && o.Status == 1)
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                TotalConsumption = g.Sum(o => o.Price),
                WeChatPayment = g.Sum(o => o.Price - o.UseMoney - o.UseIntegral - o.UseScore),
                BalancePayment = g.Sum(o => o.UseMoney),
                IntegralPayment = g.Sum(o => o.UseIntegral)
            })
            .ToListAsync();

        // 获取盒柜价值（未处理的奖品）
        var boxValues = await _dbContext.OrderItems
            .AsNoTracking()
            .Where(oi => userIds.Contains(oi.UserId) && oi.Status == 0)
            .GroupBy(oi => oi.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                BoxValue = g.Sum(oi => oi.GoodslistPrice)
            })
            .ToListAsync();

        // 获取回收金额
        var recoveryAmounts = await _dbContext.OrderItemsRecoveries
            .AsNoTracking()
            .Where(r => userIds.Contains(r.UserId))
            .GroupBy(r => r.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                RecoveryAmount = g.Sum(r => r.Money)
            })
            .ToListAsync();

        // 获取发货价值（通过订单详情计算，status=2表示已发货）
        var shippingValues = await _dbContext.OrderItems
            .AsNoTracking()
            .Where(oi => userIds.Contains(oi.UserId) && oi.Status == 2)
            .GroupBy(oi => oi.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                ShippingValue = g.Sum(oi => oi.GoodslistPrice)
            })
            .ToListAsync();

        // 合并统计数据
        var result = new Dictionary<int, UserConsumptionStats>();
        foreach (var userId in userIds)
        {
            var orderStat = orderStats.FirstOrDefault(o => o.UserId == userId);
            var boxValue = boxValues.FirstOrDefault(b => b.UserId == userId);
            var recovery = recoveryAmounts.FirstOrDefault(r => r.UserId == userId);
            var shipping = shippingValues.FirstOrDefault(s => s.UserId == userId);

            result[userId] = new UserConsumptionStats
            {
                TotalConsumption = orderStat?.TotalConsumption ?? 0,
                WeChatPayment = orderStat?.WeChatPayment ?? 0,
                BalancePayment = orderStat?.BalancePayment ?? 0,
                IntegralPayment = orderStat?.IntegralPayment ?? 0,
                BoxValue = boxValue?.BoxValue ?? 0,
                RecoveryAmount = recovery?.RecoveryAmount ?? 0,
                ShippingValue = shipping?.ShippingValue ?? 0
            };
        }

        return result;
    }

    /// <summary>
    /// 映射用户到列表响应
    /// </summary>
    private UserListResponse MapToUserListResponse(
        User user,
        Dictionary<int, string?> loginIps,
        Dictionary<int, UserConsumptionStats> consumptionStats)
    {
        var response = new UserListResponse
        {
            Id = user.Id,
            Uid = user.Uid,
            Nickname = user.Nickname,
            Avatar = user.HeadImg,
            Mobile = user.Mobile,
            Balance = user.Money,           // 钻石 (balance_name)
            Integral = user.Integral,       // HH币 (currency1_name)
            Diamond = user.Money2 ?? 0,     // 哈尼券 (currency2_name)
            EquityLevel = user.Vip,
            CreatedAt = user.CreatedAt,
            LastLoginIp = loginIps.GetValueOrDefault(user.Id),
            Status = user.Status,
            IsTest = user.IsTest,
            ParentId = user.Pid
        };

        if (consumptionStats.TryGetValue(user.Id, out var stats))
        {
            response.TotalConsumption = stats.TotalConsumption;
            response.BoxValue = stats.BoxValue;
            response.WeChatPayment = stats.WeChatPayment;
            response.BalancePayment = stats.BalancePayment;
            response.IntegralPayment = stats.IntegralPayment;
            response.RecoveryAmount = stats.RecoveryAmount;
            response.ShippingValue = stats.ShippingValue;
        }

        return response;
    }

    #endregion

    #region 统计和操作相关

    /// <inheritdoc />
    public async Task<PagedResult<InviteStatsItem>> GetInviteStatsAsync(InviteStatsQuery query)
    {
        // 查询有下级用户的用户列表
        var usersQuery = _dbContext.Users.AsNoTracking();

        // 应用过滤条件
        if (query.UserId.HasValue)
        {
            usersQuery = usersQuery.Where(u => u.Id == query.UserId.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.Uid))
        {
            usersQuery = usersQuery.Where(u => u.Uid.Contains(query.Uid));
        }

        // 获取有下级的用户ID列表
        var parentIds = await _dbContext.Users
            .AsNoTracking()
            .Where(u => u.Pid > 0)
            .Select(u => u.Pid)
            .Distinct()
            .ToListAsync();

        // 只查询有下级的用户
        usersQuery = usersQuery.Where(u => parentIds.Contains(u.Id));

        // 如果有最小邀请人数过滤，需要先计算
        if (query.MinInviteCount.HasValue)
        {
            var inviteCounts = await _dbContext.Users
                .AsNoTracking()
                .Where(u => u.Pid > 0)
                .GroupBy(u => u.Pid)
                .Select(g => new { Pid = g.Key, Count = g.Count() })
                .Where(x => x.Count >= query.MinInviteCount.Value)
                .Select(x => x.Pid)
                .ToListAsync();

            usersQuery = usersQuery.Where(u => inviteCounts.Contains(u.Id));
        }

        var total = await usersQuery.CountAsync();

        var users = await usersQuery
            .OrderByDescending(u => u.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .ToListAsync();

        var userIds = users.Select(u => u.Id).ToList();

        // 获取每个用户的下级统计
        var inviteStats = await GetInviteStatsForUsersAsync(userIds, query.StartTime, query.EndTime);

        var list = users.Select((u, index) =>
        {
            var stats = inviteStats.GetValueOrDefault(u.Id);
            return new InviteStatsItem
            {
                Index = query.Skip + index + 1,
                UserId = u.Id,
                Uid = u.Uid,
                Nickname = u.Nickname,
                Headimg = u.HeadImg,
                InviteNumber = stats?.InviteNumber ?? 0,
                SumOrder = stats?.SumOrder ?? 0,
                SumPrice = stats?.SumPrice ?? 0,
                CountMobile = stats?.CountMobile ?? 0,
                Info = stats?.Info
            };
        }).ToList();

        return PagedResult<InviteStatsItem>.Create(list, total, query.Page, query.PageSize);
    }

    /// <summary>
    /// 获取用户的下级邀请统计
    /// </summary>
    private async Task<Dictionary<int, InviteStatsItem>> GetInviteStatsForUsersAsync(
        List<int> userIds, DateTime? startTime, DateTime? endTime)
    {
        var result = new Dictionary<int, InviteStatsItem>();

        foreach (var userId in userIds)
        {
            // 获取下级用户
            var subordinatesQuery = _dbContext.Users
                .AsNoTracking()
                .Where(u => u.Pid == userId);

            if (startTime.HasValue)
            {
                subordinatesQuery = subordinatesQuery.Where(u => u.CreatedAt >= startTime.Value);
            }

            if (endTime.HasValue)
            {
                var endDate = endTime.Value.Date.AddDays(1);
                subordinatesQuery = subordinatesQuery.Where(u => u.CreatedAt < endDate);
            }

            var subordinates = await subordinatesQuery.ToListAsync();
            var subordinateIds = subordinates.Select(s => s.Id).ToList();

            // 获取下级用户的订单统计
            var orderStats = await _dbContext.Orders
                .AsNoTracking()
                .Where(o => subordinateIds.Contains(o.UserId) && o.Status == 1)
                .GroupBy(o => o.UserId)
                .Select(g => new
                {
                    UserId = g.Key,
                    OrderCount = g.Count(),
                    TotalPrice = g.Sum(o => o.Price)
                })
                .ToListAsync();

            var orderStatsDict = orderStats.ToDictionary(x => x.UserId);

            var info = subordinates.Select(s =>
            {
                var orderStat = orderStatsDict.GetValueOrDefault(s.Id);
                return new InviteUserInfo
                {
                    UserId = s.Id,
                    Uid = s.Uid,
                    Nickname = s.Nickname,
                    Headimg = s.HeadImg,
                    Mobile = s.Mobile,
                    OrderCount = orderStat?.OrderCount ?? 0,
                    TotalPrice = orderStat?.TotalPrice ?? 0,
                    CreatedAt = s.CreatedAt
                };
            }).ToList();

            result[userId] = new InviteStatsItem
            {
                UserId = userId,
                InviteNumber = subordinates.Count,
                SumOrder = orderStats.Sum(x => x.OrderCount),
                SumPrice = orderStats.Sum(x => x.TotalPrice),
                CountMobile = subordinates.Count(s => !string.IsNullOrEmpty(s.Mobile)),
                Info = info
            };
        }

        return result;
    }

    /// <inheritdoc />
    public async Task<LoginStatsResponse> GetLoginStatsAsync(LoginStatsQuery query)
    {
        var response = new LoginStatsResponse();

        // 确定查询的时间范围
        var year = query.Year ?? DateTime.Now.Year;
        var startDate = query.StartDate ?? new DateTime(year, 1, 1);
        var endDate = query.EndDate ?? DateTime.Now;

        var logsQuery = _dbContext.UserLoginLogs
            .AsNoTracking()
            .Where(l => l.LoginTime >= startDate && l.LoginTime <= endDate);

        switch (query.Type.ToLower())
        {
            case "day":
                // 按日统计
                var dailyStats = await logsQuery
                    .GroupBy(l => l.LoginDate)
                    .Select(g => new
                    {
                        Date = g.Key,
                        Count = g.Count()
                    })
                    .OrderBy(x => x.Date)
                    .ToListAsync();

                response.Labels = dailyStats.Select(x => x.Date.ToString("yyyy-MM-dd")).ToList();
                response.Values = dailyStats.Select(x => x.Count).ToList();
                break;

            case "week":
                // 按周统计
                var weeklyStats = await logsQuery
                    .GroupBy(l => new { l.Year, l.Week })
                    .Select(g => new
                    {
                        g.Key.Year,
                        g.Key.Week,
                        Count = g.Count()
                    })
                    .OrderBy(x => x.Year)
                    .ThenBy(x => x.Week)
                    .ToListAsync();

                response.Labels = weeklyStats.Select(x => $"{x.Year}年第{x.Week}周").ToList();
                response.Values = weeklyStats.Select(x => x.Count).ToList();
                break;

            case "month":
                // 按月统计
                var monthlyStats = await logsQuery
                    .GroupBy(l => new { l.Year, l.Month })
                    .Select(g => new
                    {
                        g.Key.Year,
                        g.Key.Month,
                        Count = g.Count()
                    })
                    .OrderBy(x => x.Year)
                    .ThenBy(x => x.Month)
                    .ToListAsync();

                response.Labels = monthlyStats.Select(x => $"{x.Year}-{x.Month:D2}").ToList();
                response.Values = monthlyStats.Select(x => x.Count).ToList();
                break;
        }

        // 计算总登录次数
        response.TotalLogins = response.Values.Sum();

        // 计算活跃用户数（去重）
        response.ActiveUsers = await logsQuery
            .Select(l => l.UserId)
            .Distinct()
            .CountAsync();

        return response;
    }

    /// <inheritdoc />
    public async Task<PagedResult<ProfitLossItem>> GetProfitLossListAsync(ProfitLossListQuery query)
    {
        var usersQuery = _dbContext.Users.AsNoTracking();

        // 应用过滤条件
        // UserIdStr 实际上是前端传的 UID（用户唯一标识字符串），需要匹配 Uid 字段
        if (!string.IsNullOrWhiteSpace(query.UserIdStr))
        {
            usersQuery = usersQuery.Where(u => u.Uid == query.UserIdStr.Trim());
        }
        else if (query.UserId.HasValue)
        {
            usersQuery = usersQuery.Where(u => u.Id == query.UserId.Value);
        }

        if (!string.IsNullOrWhiteSpace(query.Uid))
        {
            usersQuery = usersQuery.Where(u => u.Uid.Contains(query.Uid));
        }

        var total = await usersQuery.CountAsync();

        var users = await usersQuery
            .OrderByDescending(u => u.Id)
            .Skip(query.Skip)
            .Take(query.PageSize)
            .ToListAsync();

        var userIds = users.Select(u => u.Id).ToList();

        // 获取盈亏统计数据
        var profitLossStats = await GetProfitLossStatsAsync(userIds, query.StartTime, query.EndTime);

        var list = users.Select(u =>
        {
            var stats = profitLossStats.GetValueOrDefault(u.Id);
            var yueMoney = (stats?.UseMoney ?? 0) - (stats?.FhMoney ?? 0) - (stats?.BbMoney ?? 0) - (stats?.SyMoney ?? 0);

            return new ProfitLossItem
            {
                UserId = u.Id,
                Uid = u.Uid,
                Nickname = u.Nickname,
                Headimg = u.HeadImg,
                Mobile = u.Mobile,
                Money = u.Money,
                Integral = u.Integral,
                Money2 = u.Score,
                OrderCount = stats?.OrderCount ?? 0,
                OrderZheTotal = stats?.OrderZheTotal ?? 0,
                Money1 = stats?.Money1 ?? 0,
                Money2Pay = stats?.Money2Pay ?? 0,
                UseMoney = stats?.UseMoney ?? 0,
                FhMoney = stats?.FhMoney ?? 0,
                BbMoney = stats?.BbMoney ?? 0,
                SyMoney = stats?.SyMoney ?? 0,
                YueMoney = yueMoney,
                ProfitStatus = yueMoney >= 0 ? "盈利" : "亏损"
            };
        }).ToList();

        return PagedResult<ProfitLossItem>.Create(list, total, query.Page, query.PageSize);
    }

    /// <summary>
    /// 获取用户盈亏统计数据
    /// </summary>
    private async Task<Dictionary<int, ProfitLossStats>> GetProfitLossStatsAsync(
        List<int> userIds, DateTime? startTime, DateTime? endTime)
    {
        var result = new Dictionary<int, ProfitLossStats>();

        // 构建订单查询
        var ordersQuery = _dbContext.Orders
            .AsNoTracking()
            .Where(o => userIds.Contains(o.UserId) && o.Status == 1);

        if (startTime.HasValue)
        {
            ordersQuery = ordersQuery.Where(o => o.CreatedAt >= startTime.Value);
        }

        if (endTime.HasValue)
        {
            var endDate = endTime.Value.Date.AddDays(1);
            ordersQuery = ordersQuery.Where(o => o.CreatedAt < endDate);
        }

        // 获取订单统计
        var orderStats = await ordersQuery
            .GroupBy(o => o.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                OrderCount = g.Count(),
                OrderZheTotal = g.Sum(o => o.OrderZheTotal),
                UseMoney = g.Sum(o => o.Price),
                Money1 = g.Sum(o => o.Price - o.UseMoney - o.UseIntegral - o.UseScore),
                Money2Pay = g.Sum(o => o.UseScore)
            })
            .ToListAsync();

        // 构建订单详情查询（发货金额）
        var orderItemsQuery = _dbContext.OrderItems
            .AsNoTracking()
            .Where(oi => userIds.Contains(oi.UserId) && oi.Status == 2);

        if (startTime.HasValue)
        {
            orderItemsQuery = orderItemsQuery.Where(oi => oi.CreatedAt >= startTime.Value);
        }

        if (endTime.HasValue)
        {
            var endDate = endTime.Value.Date.AddDays(1);
            orderItemsQuery = orderItemsQuery.Where(oi => oi.CreatedAt < endDate);
        }

        var shippingStats = await orderItemsQuery
            .GroupBy(oi => oi.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                FhMoney = g.Sum(oi => oi.GoodslistPrice)
            })
            .ToListAsync();

        // 获取背包金额（未处理的奖品）
        var boxStats = await _dbContext.OrderItems
            .AsNoTracking()
            .Where(oi => userIds.Contains(oi.UserId) && oi.Status == 0)
            .GroupBy(oi => oi.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                BbMoney = g.Sum(oi => oi.GoodslistPrice)
            })
            .ToListAsync();

        // 获取回收金额（剩余达达券）
        var recoveryQuery = _dbContext.OrderItemsRecoveries
            .AsNoTracking()
            .Where(r => userIds.Contains(r.UserId));

        if (startTime.HasValue)
        {
            recoveryQuery = recoveryQuery.Where(r => r.CreatedAt >= startTime.Value);
        }

        if (endTime.HasValue)
        {
            var endDate = endTime.Value.Date.AddDays(1);
            recoveryQuery = recoveryQuery.Where(r => r.CreatedAt < endDate);
        }

        var recoveryStats = await recoveryQuery
            .GroupBy(r => r.UserId)
            .Select(g => new
            {
                UserId = g.Key,
                SyMoney = g.Sum(r => r.Money)
            })
            .ToListAsync();

        // 合并统计数据
        foreach (var userId in userIds)
        {
            var orderStat = orderStats.FirstOrDefault(x => x.UserId == userId);
            var shippingStat = shippingStats.FirstOrDefault(x => x.UserId == userId);
            var boxStat = boxStats.FirstOrDefault(x => x.UserId == userId);
            var recoveryStat = recoveryStats.FirstOrDefault(x => x.UserId == userId);

            result[userId] = new ProfitLossStats
            {
                OrderCount = orderStat?.OrderCount ?? 0,
                OrderZheTotal = orderStat?.OrderZheTotal ?? 0,
                UseMoney = orderStat?.UseMoney ?? 0,
                Money1 = orderStat?.Money1 ?? 0,
                Money2Pay = orderStat?.Money2Pay ?? 0,
                FhMoney = shippingStat?.FhMoney ?? 0,
                BbMoney = boxStat?.BbMoney ?? 0,
                SyMoney = recoveryStat?.SyMoney ?? 0
            };
        }

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> BindMobileAsync(int userId, string mobile)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 检查手机号是否已被其他用户绑定
        var existingUser = await _dbContext.Users
            .FirstOrDefaultAsync(u => u.Mobile == mobile && u.Id != userId);
        if (existingUser != null)
        {
            throw new BusinessException(BusinessErrorCodes.ValidationFailed, "该手机号已被其他用户绑定");
        }

        user.Mobile = mobile;
        user.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("绑定手机号: UserId={UserId}, Mobile={Mobile}", userId, mobile);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> ResetUserSignAsync(int userId)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 删除用户的签到记录
        var userSigns = await _dbContext.UserSigns
            .Where(s => s.UserId == userId)
            .ToListAsync();

        if (userSigns.Any())
        {
            _dbContext.UserSigns.RemoveRange(userSigns);
        }

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

        _logger.LogInformation("重置用户签到数据: UserId={UserId}, DeletedCount={Count}", userId, userSigns.Count);

        return result;
    }

    /// <inheritdoc />
    public async Task<bool> ClearUidAsync(int userId)
    {
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
        if (user == null)
        {
            throw new BusinessException(BusinessErrorCodes.NotFound, "用户不存在");
        }

        // 生成新的随机UID
        var newUid = GenerateRandomUid();
        user.Uid = newUid;
        user.UpdatedAt = DateTime.Now;

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

        _logger.LogInformation("清空用户UID: UserId={UserId}, NewUid={NewUid}", userId, newUid);

        return result;
    }

    private static string GenerateRandomUid()
    {
        return $"U{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";
    }

    #endregion
}

/// <summary>
/// 用户消费统计内部类
/// </summary>
internal class UserConsumptionStats
{
    public decimal TotalConsumption { get; set; }
    public decimal WeChatPayment { get; set; }
    public decimal BalancePayment { get; set; }
    public decimal IntegralPayment { get; set; }
    public decimal BoxValue { get; set; }
    public decimal RecoveryAmount { get; set; }
    public decimal ShippingValue { get; set; }
}

/// <summary>
/// 用户盈亏统计内部类
/// </summary>
internal class ProfitLossStats
{
    public int OrderCount { get; set; }
    public decimal OrderZheTotal { get; set; }
    public decimal UseMoney { get; set; }
    public decimal Money1 { get; set; }
    public decimal Money2Pay { get; set; }
    public decimal FhMoney { get; set; }
    public decimal BbMoney { get; set; }
    public decimal SyMoney { get; set; }
}
