using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Entities;
using HoneyBox.Model.Models.UserCoupon;
using HoneyBox.Model.Models.Coupon;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace HoneyBox.Core.Services;

/// <summary>
/// 优惠券服务实现
/// </summary>
public class CouponService : ICouponService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<CouponService> _logger;

    // 优惠券等级映射
    private static readonly Dictionary<int, (string Text, string Img)> CouponLevelMap = new()
    {
        { 1, ("特级赏券", "/storage/coupon/coupon_a.png") },
        { 2, ("终极赏券", "/storage/coupon/coupon_b.png") },
        { 3, ("高级赏券", "/storage/coupon/coupon_c.png") },
        { 4, ("普通赏券", "/storage/coupon/coupon_d.png") }
    };

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

    /// <inheritdoc />
    public async Task<UserCouponListResponse> GetCouponListAsync(int userId, int status, int page, int limit = 15)
    {
        _logger.LogInformation("获取优惠券列表: UserId={UserId}, Status={Status}, Page={Page}", userId, status, page);

        var query = _dbContext.UserCoupons.Where(c => c.UserId == userId);

        // 根据状态过滤和排序
        if (status == 1)
        {
            query = query.Where(c => c.Status == 1).OrderByDescending(c => c.Id);
        }
        else if (status == 2)
        {
            query = query.Where(c => c.Status == 2).OrderByDescending(c => c.ShareTime);
        }

        var totalCount = await query.CountAsync();
        var lastPage = (int)Math.Ceiling((double)totalCount / limit);
        if (lastPage < 1) lastPage = 1;

        var coupons = await query
            .Skip((page - 1) * limit)
            .Take(limit)
            .ToListAsync();

        var couponDtos = coupons.Select(c => MapToCouponDto(c)).ToList();

        // 获取今日已领取数量 (type=2 表示领取的优惠券)
        var todayStart = DateTime.Today;
        var yCount = await _dbContext.UserCoupons
            .Where(c => c.UserId == userId && c.Type == 2 && c.CreatedAt >= todayStart)
            .CountAsync();

        // 获取用户吧唧币余额
        var user = await _dbContext.Users.FindAsync(userId);
        var userIntegral = user?.Integral ?? 0;

        return new UserCouponListResponse
        {
            List = couponDtos,
            LastPage = lastPage,
            YCount = yCount,
            ZCount = 50, // 每日领取上限
            UserIntegral = userIntegral,
            KeHcCount = 20, // 最大合成数量
            SunHao = "10%" // 合成损耗率
        };
    }

    /// <inheritdoc />
    public async Task<CouponDetailResponse> GetCouponDetailAsync(int userId, int couponId)
    {
        _logger.LogInformation("获取优惠券详情: UserId={UserId}, CouponId={CouponId}", userId, couponId);

        var coupon = await _dbContext.UserCoupons.FindAsync(couponId);
        if (coupon == null)
        {
            throw new InvalidOperationException("参数错误");
        }

        // 获取等级信息
        var (levelText, levelImg) = GetCouponLevelInfo(coupon.Level ?? 4);

        // 计算剩余可领取金额 (own2 - own)
        var own2 = Math.Round((coupon.Own2 ?? 0) - (coupon.Own ?? 0), 2);

        // 获取已领取数量和总金额
        var ylCount = await _dbContext.UserCoupons
            .Where(c => c.Status == 3 && c.FromId == couponId.ToString())
            .CountAsync();

        var ylIntegralCount = await _dbContext.UserCoupons
            .Where(c => c.Status == 3 && c.FromId == couponId.ToString())
            .SumAsync(c => c.LNum ?? 0);

        // 获取分享者信息
        var shareUser = await _dbContext.Users.FindAsync(coupon.UserId);

        // 获取领取记录列表
        var ylList = await _dbContext.UserCoupons
            .Where(c => c.Status == 3 && c.FromId == couponId.ToString())
            .Join(_dbContext.Users, c => c.UserId, u => u.Id, (c, u) => new { Coupon = c, User = u })
            .Select(x => new CouponClaimRecordDto
            {
                UserId = x.Coupon.UserId,
                Nickname = x.User.Nickname,
                Headimg = x.User.HeadImg,
                LNum = x.Coupon.LNum ?? 0,
                AddTime = x.Coupon.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss"),
                LuckyKing = 0
            })
            .ToListAsync();

        // 找出手气最佳
        if (ylList.Any())
        {
            var maxLNum = ylList.Max(x => x.LNum);
            foreach (var item in ylList.Where(x => x.LNum == maxLNum))
            {
                item.LuckyKing = 1;
            }
        }

        return new CouponDetailResponse
        {
            Id = coupon.Id,
            Level = coupon.Level ?? 4,
            LevelText = levelText,
            LevelImg = levelImg,
            ShareTime = coupon.ShareTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
            UserId = coupon.UserId,
            Num = coupon.Num.ToString(),
            KlNum2 = coupon.KlNum2 ?? 0,
            Own2 = own2,
            YlCount = ylCount,
            YlIntegralCount = ylIntegralCount,
            ShareUserNickname = shareUser?.Nickname ?? "",
            ShareUserHeadimg = shareUser?.HeadImg ?? "",
            YlList = ylList
        };
    }


    /// <inheritdoc />
    public async Task<bool> ShareCouponAsync(int userId, int couponId)
    {
        _logger.LogInformation("分享优惠券: UserId={UserId}, CouponId={CouponId}", userId, couponId);

        var coupon = await _dbContext.UserCoupons
            .FirstOrDefaultAsync(c => c.Id == couponId && c.UserId == userId);

        if (coupon == null)
        {
            throw new InvalidOperationException("参数错误");
        }

        coupon.Status = 2;
        coupon.ShareTime = DateTime.Now;
        coupon.UpdatedAt = DateTime.Now;

        await _dbContext.SaveChangesAsync();
        return true;
    }

    /// <inheritdoc />
    public async Task<ClaimCouponResponse> ClaimCouponAsync(int userId, int couponId)
    {
        _logger.LogInformation("领取优惠券: UserId={UserId}, CouponId={CouponId}", userId, couponId);

        var coupon = await _dbContext.UserCoupons.FindAsync(couponId);
        if (coupon == null)
        {
            throw new InvalidOperationException("参数错误");
        }

        // 不能领取自己的券
        if (coupon.UserId == userId)
        {
            throw new InvalidOperationException("请勿开启自己的劵");
        }

        // 检查是否已领取过
        var isLing = await _dbContext.UserCoupons
            .AnyAsync(c => c.UserId == userId && c.Type == 2 && c.FromId == couponId.ToString());
        if (isLing)
        {
            throw new InvalidOperationException("你已经领取过了");
        }

        // 检查今日领取次数
        var todayStart = DateTime.Today;
        var count = await _dbContext.UserCoupons
            .Where(c => c.UserId == userId && c.Type == 2 && c.CreatedAt >= todayStart)
            .CountAsync();

        var config = await GetConfigAsync("base");
        var maxCi = config?.GetProperty("coupon_ling_max_ci").GetInt32() ?? 50;
        if (count >= maxCi)
        {
            throw new InvalidOperationException($"每天最多领取{maxCi}次");
        }

        // 检查剩余金额
        if ((coupon.Other ?? 0) <= 0)
        {
            throw new InvalidOperationException("来晚了, 已经被人领完了");
        }

        using var transaction = await _dbContext.Database.BeginTransactionAsync();
        try
        {
            // 生成随机金额
            var randMoneyArr = RandMoney((double)(coupon.Other ?? 0), coupon.KlNum ?? 1, 1);
            if (randMoneyArr.Count == 0)
            {
                throw new InvalidOperationException("来晚了, 已经被人领完了");
            }
            var randMoney = randMoneyArr[0];

            // 扣减优惠券剩余金额
            coupon.Other = (coupon.Other ?? 0) - (decimal)randMoney;
            coupon.KlNum = (coupon.KlNum ?? 1) - 1;
            coupon.UpdatedAt = DateTime.Now;

            // 创建领取记录
            var claimRecord = new UserCoupon
            {
                UserId = userId,
                Title = coupon.Title,
                Num = 0,
                LNum = (decimal)randMoney,
                Status = 3,
                Type = 2,
                FromId = couponId.ToString(),
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            _dbContext.UserCoupons.Add(claimRecord);

            // 给领取者增加吧唧币
            await ChangeIntegralAsync(userId, (decimal)randMoney, 3, "欧气券领取", couponId);

            // 给分享者发放奖励
            var klNum = coupon.KlNum ?? 0;
            var own = coupon.Own ?? 0;
            if (own > 0 && klNum > 1)
            {
                var integral = Math.Round((coupon.Own2 ?? 0) / (coupon.KlNum2 ?? 1), 2);
                coupon.Own = own - integral;
                await ChangeIntegralAsync(coupon.UserId, integral, 5, "欧气券分享", couponId);
            }
            else if (own > 0 && klNum == 1)
            {
                coupon.Own = 0;
                await ChangeIntegralAsync(coupon.UserId, own, 5, "欧气券分享", couponId);
            }

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

            return new ClaimCouponResponse
            {
                Amount = (decimal)randMoney,
                LuckyKing = false
            };
        }
        catch
        {
            await transaction.RollbackAsync();
            throw;
        }
    }


    /// <inheritdoc />
    public async Task<SynthesisCalculateResponse> CalculateSynthesisAsync(int userId, string couponIds)
    {
        _logger.LogInformation("计算合成: UserId={UserId}, CouponIds={CouponIds}", userId, couponIds);

        if (string.IsNullOrEmpty(couponIds))
        {
            throw new InvalidOperationException("缺少必要参数");
        }

        var ids = couponIds.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(s => int.TryParse(s.Trim(), out var id) ? id : 0)
            .Where(id => id > 0)
            .ToList();

        if (ids.Count == 0)
        {
            throw new InvalidOperationException("缺少必要参数!");
        }

        if (ids.Count > 20)
        {
            throw new InvalidOperationException("最多只能20个合成");
        }

        decimal sumNum = 0;
        foreach (var id in ids)
        {
            var coupon = await _dbContext.UserCoupons
                .FirstOrDefaultAsync(c => c.UserId == userId && c.Status == 1 && c.Id == id);
            if (coupon == null)
            {
                throw new InvalidOperationException("数据错误!");
            }
            if ((coupon.Level ?? 4) < 3)
            {
                throw new InvalidOperationException("特级,终极赏券不能合成");
            }
            sumNum += coupon.Num;
        }

        if (sumNum <= 0)
        {
            throw new InvalidOperationException("网络故障,请稍后再试!!");
        }

        // 合成损耗10%
        var shNum = sumNum - sumNum * 0.1m;

        // 计算新等级
        var (title, level) = CalculateCouponLevel(sumNum);

        return new SynthesisCalculateResponse
        {
            Coupon = new SynthesisCouponDto
            {
                Title = title,
                Level = level
            },
            SumNum = sumNum,
            ShNum = shNum
        };
    }

    /// <inheritdoc />
    public async Task<bool> SynthesisCouponsAsync(int userId, string couponIds)
    {
        _logger.LogInformation("执行合成: UserId={UserId}, CouponIds={CouponIds}", userId, couponIds);

        if (string.IsNullOrEmpty(couponIds))
        {
            throw new InvalidOperationException("缺少必要参数");
        }

        var ids = couponIds.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(s => int.TryParse(s.Trim(), out var id) ? id : 0)
            .Where(id => id > 0)
            .ToList();

        if (ids.Count == 0)
        {
            throw new InvalidOperationException("缺少必要参数!");
        }

        decimal sumNum = 0;
        foreach (var id in ids)
        {
            var coupon = await _dbContext.UserCoupons
                .FirstOrDefaultAsync(c => c.UserId == userId && c.Status == 1 && c.Id == id);
            if (coupon == null)
            {
                throw new InvalidOperationException("数据错误!");
            }
            if ((coupon.Level ?? 4) < 3)
            {
                throw new InvalidOperationException("特级,终极赏券不能合成");
            }
            sumNum += coupon.Num;
        }

        // 计算新等级和可领取次数
        var (title, level) = CalculateCouponLevel(sumNum);
        var config = await GetConfigAsync("base");
        var klNum = level switch
        {
            1 => config?.GetProperty("coupon_a_xz_max").GetInt32() ?? 10,
            2 => config?.GetProperty("coupon_b_xz_max").GetInt32() ?? 8,
            3 => config?.GetProperty("coupon_c_xz_max").GetInt32() ?? 6,
            _ => config?.GetProperty("coupon_d_xz_max").GetInt32() ?? 4
        };

        // 合成损耗10%
        sumNum = sumNum - sumNum * 0.1m;
        if (sumNum <= 0)
        {
            throw new InvalidOperationException("网络故障,请稍后再试!!");
        }

        // 自己获得80%，其他人获得20%
        var own = (int)(sumNum * 0.8m);
        var other = (int)(sumNum * 0.2m);
        if (own <= 0 || other <= 0)
        {
            throw new InvalidOperationException("网络故障,请稍后再试!!!");
        }

        using var transaction = await _dbContext.Database.BeginTransactionAsync();
        try
        {
            // 将原优惠券状态改为4 (已合成)
            var couponsToUpdate = await _dbContext.UserCoupons
                .Where(c => c.UserId == userId && ids.Contains(c.Id))
                .ToListAsync();

            foreach (var c in couponsToUpdate)
            {
                c.Status = 4;
                c.UpdatedAt = DateTime.Now;
            }

            // 创建新优惠券
            var newCoupon = new UserCoupon
            {
                UserId = userId,
                Level = level,
                Title = title,
                Num = (int)sumNum,
                Status = 1,
                Type = 3,
                FromId = "0",
                Own = own,
                Own2 = own,
                Other = other,
                Other2 = other,
                KlNum = klNum,
                KlNum2 = klNum,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            _dbContext.UserCoupons.Add(newCoupon);

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

            return true;
        }
        catch
        {
            await transaction.RollbackAsync();
            throw;
        }
    }


    /// <inheritdoc />
    public async Task<bool> BatchReceiveCouponsAsync(int userId, string couponIds)
    {
        _logger.LogInformation("批量领取优惠券: UserId={UserId}, CouponIds={CouponIds}", userId, couponIds);

        if (string.IsNullOrEmpty(couponIds))
        {
            throw new InvalidOperationException("缺少必要参数");
        }

        var ids = couponIds.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(s => int.TryParse(s.Trim(), out var id) ? id : 0)
            .Where(id => id > 0)
            .ToList();

        if (ids.Count == 0)
        {
            throw new InvalidOperationException("缺少必要参数");
        }

        // 检查是否已领取过
        var existingReceive = await _dbContext.CouponReceives
            .Where(cr => cr.UserId == userId && ids.Contains(cr.CouponId ?? 0))
            .FirstOrDefaultAsync();

        if (existingReceive != null)
        {
            throw new InvalidOperationException("已经领取过了,无法再领取");
        }

        using var transaction = await _dbContext.Database.BeginTransactionAsync();
        try
        {
            foreach (var couponId in ids)
            {
                var coupon = await _dbContext.Coupons.FindAsync(couponId);
                if (coupon != null)
                {
                    var couponReceive = new CouponReceife
                    {
                        UserId = userId,
                        Title = coupon.Title,
                        Price = coupon.Price,
                        ManPrice = coupon.ManPrice,
                        EndTime = DateTime.Now.AddDays(coupon.EffectiveDay ?? 7),
                        CouponId = coupon.Id,
                        Status = 0,
                        State = coupon.Ttype,
                        Ttype = coupon.Ttype ?? 0,
                        CreatedAt = DateTime.Now
                    };
                    _dbContext.CouponReceives.Add(couponReceive);
                }
            }

            // 更新用户的is_use_coupon标记
            var user = await _dbContext.Users.FindAsync(userId);
            if (user != null && user.IsUseCoupon == 0)
            {
                user.IsUseCoupon = 1;
                user.UpdatedAt = DateTime.Now;
            }

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

            return true;
        }
        catch
        {
            await transaction.RollbackAsync();
            throw;
        }
    }

    /// <inheritdoc />
    public async Task<AvailableCouponListResponse> GetAvailableCouponsAsync(int userId)
    {
        _logger.LogInformation("获取可领取优惠券列表: UserId={UserId}", userId);

        // 检查用户是否已领取过优惠券
        var user = await _dbContext.Users.FindAsync(userId);
        if (user == null || user.IsUseCoupon == 1)
        {
            // 已领取过，不再弹出
            return new AvailableCouponListResponse
            {
                Status = 2,
                Goods = new List<AvailableCouponDto>()
            };
        }

        // 获取可领取的优惠券列表 (status=0, type=1)
        var coupons = await _dbContext.Coupons
            .Where(c => c.Status == 0 && c.Type == 1)
            .OrderByDescending(c => c.Id)
            .Take(1000)
            .Select(c => new AvailableCouponDto
            {
                Id = c.Id,
                Title = c.Title,
                Price = c.Price ?? 0,
                ManPrice = c.ManPrice ?? 0,
                EffectiveDay = c.EffectiveDay ?? 7
            })
            .ToListAsync();

        return new AvailableCouponListResponse
        {
            Status = 1,
            Goods = coupons
        };
    }

    /// <inheritdoc />
    public async Task<UsableCouponListResponse> GetUsableCouponsAsync(int userId, UsableCouponListRequest request)
    {
        _logger.LogInformation("获取可使用优惠券列表: UserId={UserId}, Type={Type}, Type1={Type1}", 
            userId, request.Type, request.Type1);

        // 先更新过期的优惠券状态
        var expiredCoupons = await _dbContext.CouponReceives
            .Where(cr => cr.UserId == userId && cr.Status == 0 && cr.EndTime <= DateTime.Now)
            .ToListAsync();

        foreach (var coupon in expiredCoupons)
        {
            coupon.Status = 2; // 已过期
        }

        if (expiredCoupons.Any())
        {
            await _dbContext.SaveChangesAsync();
        }

        IQueryable<CouponReceife> query = _dbContext.CouponReceives.Where(cr => cr.UserId == userId);
        var pageSize = 10;

        if (request.Type == 1)
        {
            // 从个人中心进入
            if (request.Type1 == 1)
            {
                // 可用
                query = query.Where(cr => cr.Status == request.Status);
            }
            else
            {
                // 不可用
                query = query.Where(cr => cr.Status > 0);
            }
        }
        else
        {
            // 从计算金额进入
            if (!request.TotalPrice.HasValue)
            {
                throw new InvalidOperationException("缺少必要参数");
            }

            var totalPrice = request.TotalPrice.Value;

            if (request.Type1 == 1)
            {
                // 可用 - 满足金额条件
                query = query.Where(cr => cr.Status == 0 && cr.ManPrice <= totalPrice);
            }
            else
            {
                // 不可用 - 已使用、已过期、或金额不足
                query = query.Where(cr => cr.Status > 0 || (cr.Status == 0 && cr.ManPrice > totalPrice));
            }
        }

        var totalCount = await query.CountAsync();
        var lastPage = (int)Math.Ceiling((double)totalCount / pageSize);
        if (lastPage < 1) lastPage = 1;

        var coupons = await query
            .OrderByDescending(cr => cr.Id)
            .Skip((request.Page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        var couponDtos = coupons.Select(cr => new UsableCouponDto
        {
            Id = cr.Id,
            Title = cr.Title,
            Price = cr.Price ?? 0,
            ManPrice = cr.ManPrice ?? 0,
            EndTime = cr.EndTime?.ToString("yyyy-MM-dd") ?? "",
            Status = cr.Status,
            CouponId = cr.CouponId ?? 0,
            Mark = GetCouponMark(cr.Status, cr.ManPrice ?? 0, request.TotalPrice ?? 0)
        }).ToList();

        return new UsableCouponListResponse
        {
            Data = couponDtos,
            LastPage = lastPage
        };
    }

    /// <inheritdoc />
    public async Task<UserCouponListResponse> GetCouponCenterListAsync(int userId, CouponCenterListRequest request)
    {
        _logger.LogInformation("获取领券中心列表: UserId={UserId}, Type={Type}", userId, request.Type);

        // 这个方法实际上是获取用户的潮券列表，与GetCouponListAsync类似
        return await GetCouponListAsync(userId, request.Type, request.Page, request.Limit);
    }

    /// <inheritdoc />
    public async Task<ClaimCouponResponse> ReceiveCouponCenterAsync(int userId, int couponId)
    {
        _logger.LogInformation("领取领券中心优惠券: UserId={UserId}, CouponId={CouponId}", userId, couponId);

        // 这个方法实际上是领取潮券，与ClaimCouponAsync相同
        return await ClaimCouponAsync(userId, couponId);
    }

    /// <summary>
    /// 获取优惠券状态标记
    /// </summary>
    private static string GetCouponMark(byte status, decimal manPrice, decimal totalPrice)
    {
        return status switch
        {
            1 => "已使用",
            2 => "已过期",
            0 when manPrice > totalPrice => "未满足",
            0 => "去使用",
            _ => ""
        };
    }

    #region Private Methods

    /// <summary>
    /// 获取优惠券等级信息
    /// </summary>
    private static (string Text, string Img) GetCouponLevelInfo(int level)
    {
        return CouponLevelMap.TryGetValue(level, out var info) ? info : ("普通赏券", "/storage/coupon/coupon_d.png");
    }

    /// <summary>
    /// 映射到优惠券DTO
    /// </summary>
    private static UserCouponDto MapToCouponDto(UserCoupon coupon)
    {
        var (levelText, levelImg) = GetCouponLevelInfo(coupon.Level ?? 4);
        return new UserCouponDto
        {
            Id = coupon.Id,
            Status = coupon.Status,
            Level = coupon.Level ?? 4,
            LevelText = levelText,
            LevelImg = levelImg,
            Title = coupon.Title,
            Num = coupon.Num.ToString(),
            KlNum = coupon.KlNum ?? 0,
            KlNum2 = coupon.KlNum2 ?? 0,
            YiLing = (coupon.KlNum2 ?? 0) - (coupon.KlNum ?? 0)
        };
    }

    /// <summary>
    /// 计算优惠券等级
    /// </summary>
    private static (string Title, int Level) CalculateCouponLevel(decimal sumNum)
    {
        return sumNum switch
        {
            >= 5000 => ("特级赏券", 1),
            >= 2000 => ("终极赏券", 2),
            >= 500 => ("高级赏券", 3),
            _ => ("普通赏券", 4)
        };
    }

    /// <summary>
    /// 红包随机金额算法
    /// </summary>
    private static List<double> RandMoney(double total, int personalNum, double minMoney = 1)
    {
        var moneyRight = total;
        var randMoney = new List<double>();
        var random = new Random();

        for (int i = 1; i <= personalNum; i++)
        {
            double money;
            if (moneyRight == personalNum)
            {
                money = 1;
            }
            else if (i == personalNum)
            {
                money = moneyRight;
            }
            else
            {
                var max = moneyRight - (personalNum - i) * minMoney;
                if (max < 2) max = 2;
                money = random.Next((int)minMoney, (int)(max / 2) + 1);
            }

            money = Math.Round(money, 2);
            randMoney.Add(money);
            moneyRight = Math.Round(moneyRight - money, 2);
        }

        // 打乱顺序
        for (int i = randMoney.Count - 1; i > 0; i--)
        {
            int j = random.Next(i + 1);
            (randMoney[i], randMoney[j]) = (randMoney[j], randMoney[i]);
        }

        return randMoney;
    }

    /// <summary>
    /// 获取配置
    /// </summary>
    private async Task<JsonElement?> GetConfigAsync(string key)
    {
        var config = await _dbContext.Configs.FirstOrDefaultAsync(c => c.ConfigKey == key);
        if (config?.ConfigValue == null) return null;

        try
        {
            return JsonSerializer.Deserialize<JsonElement>(config.ConfigValue);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 变更用户吧唧币
    /// </summary>
    private async Task ChangeIntegralAsync(int userId, decimal amount, byte type, string content, int? couponId = null)
    {
        var user = await _dbContext.Users.FindAsync(userId);
        if (user == null) return;

        user.Integral += amount;
        user.UpdatedAt = DateTime.Now;

        var profitIntegral = new ProfitIntegral
        {
            UserId = userId,
            ChangeMoney = amount,
            Money = user.Integral,
            Type = type,
            Content = content,
            ShareUid = couponId ?? 0,
            CreatedAt = DateTime.Now
        };
        _dbContext.ProfitIntegrals.Add(profitIntegral);
    }

    #endregion

    /// <inheritdoc />
    public async Task<int> GetPendingCouponCountAsync(int userId)
    {
        _logger.LogInformation("获取待领取优惠券数量: UserId={UserId}", userId);

        // 检查用户是否已领取过优惠券
        var user = await _dbContext.Users.FindAsync(userId);
        if (user == null || user.IsUseCoupon == 1)
        {
            // 已领取过，返回0
            return 0;
        }

        // 获取可领取的优惠券数量 (status=0, type=1)
        var count = await _dbContext.Coupons
            .Where(c => c.Status == 0 && c.Type == 1)
            .CountAsync();

        return count;
    }
}
