using SqlSugar;
using Volo.Abp.Domain.Entities.Auditing;

namespace Yi.Framework.AiHub.Domain.Entities;

/// <summary>
/// 尊享包聚合根
/// 用于给VIP扩展额外购买尊享token包
/// </summary>
[SugarTable("Ai_PremiumPackage")]
[SugarIndex($"index_{nameof(UserId)}", nameof(UserId), OrderByType.Asc)]
public class PremiumPackageAggregateRoot : FullAuditedAggregateRoot<Guid>
{
    public PremiumPackageAggregateRoot()
    {
    }

    public PremiumPackageAggregateRoot(Guid userId, long totalTokens, string packageName)
    {
        UserId = userId;
        TotalTokens = totalTokens;
        RemainingTokens = totalTokens;
        PackageName = packageName;
        IsActive = true;
    }

    /// <summary>
    /// 用户ID
    /// </summary>
    public Guid UserId { get; set; }

    /// <summary>
    /// 包名称
    /// </summary>
    public string PackageName { get; set; }

    /// <summary>
    /// 总用量（总token数）
    /// </summary>
    public long TotalTokens { get; set; }

    /// <summary>
    /// 剩余用量（剩余token数）
    /// </summary>
    public long RemainingTokens { get; set; }

    /// <summary>
    /// 已使用token数
    /// </summary>
    public long UsedTokens { get; set; }

    /// <summary>
    /// 到期时间
    /// </summary>
    public DateTime? ExpireDateTime { get; set; }

    /// <summary>
    /// 是否激活
    /// </summary>
    public bool IsActive { get; set; }

    /// <summary>
    /// 购买金额
    /// </summary>
    public decimal PurchaseAmount { get; set; }

    /// <summary>
    /// 备注
    /// </summary>
    public string? Remark { get; set; }

    /// <summary>
    /// 消耗token
    /// </summary>
    /// <param name="tokenCount">消耗的token数量</param>
    /// <returns>是否消耗成功</returns>
    public bool ConsumeTokens(long tokenCount)
    {
        RemainingTokens -= tokenCount;
        UsedTokens += tokenCount;
        
        return true;
    }

    /// <summary>
    /// 检查是否可用
    /// </summary>
    /// <returns>是否可用</returns>
    public bool IsAvailable(bool isVerifyRemainingToken=true)
    {
        if (!IsActive)
        {
            return false;
        }

        if (isVerifyRemainingToken&&RemainingTokens <= 0)
        {
            return false;
        }

        if (ExpireDateTime.HasValue && ExpireDateTime.Value < DateTime.Now)
        {
            return false;
        }

        return true;
    }

    /// <summary>
    /// 停用尊享包
    /// </summary>
    public void Deactivate()
    {
        IsActive = false;
    }

    /// <summary>
    /// 激活尊享包
    /// </summary>
    public void Activate()
    {
        IsActive = true;
    }

    /// <summary>
    /// 设置到期时间
    /// </summary>
    /// <param name="expireDateTime">到期时间</param>
    public void SetExpireDateTime(DateTime expireDateTime)
    {
        ExpireDateTime = expireDateTime;
    }
}
