const RARITY_PROBABILITIES = [
    { rarity: 0, probability: 70 }, // 普通
    { rarity: 1, probability: 24 }, // 珍稀
    { rarity: 2, probability: 4.8 }, // 极品
    { rarity: 3, probability: 1.2 }, // 传奇
  ];
  
  const GOLD_PROBABILITIES = [
    { rarity: 0, probability: 1.4 },
    { rarity: 1, probability: 1.2 },
    { rarity: 2, probability: 0.3 },
    { rarity: 3, probability: 0.12 },
  ];
  
  const CARDS_PER_PACK = 5;
  const GUARANTEED_LEGENDARY_PACKS = 30;   
 // 生成卡牌函数
async function generateCard(cardsetId, trx, minRarity = 0) {


    if (minRarity === 3) { 
        const legendaryCards = await strapi.query('api::card.card').findMany({
          where: { cardset: cardsetId, IsBlocked: false, Rarity: 3 },
          populate: ['cardset'],
          transaction: trx,
        });
        const shuffledLegendaries = legendaryCards.sort(() => Math.random() - 0.5);
        return {
          ...shuffledLegendaries[0], 
          FaceRank: 0, // 保底的传奇卡牌不应该是金卡
        };
      }





    let randomNumber = Math.random() * 100;
    let cumulativeProbability = 0;
    let selectedRarity=0;
  
    for (const rarityData of RARITY_PROBABILITIES) {
      if (rarityData.rarity >= minRarity) { // 使用数字比较稀有度
        cumulativeProbability += rarityData.probability;
        if (randomNumber <= cumulativeProbability) {
          selectedRarity = rarityData.rarity;
          break;
        }
      }
    }
  
    // 生成金卡
    let isGold = false;
    randomNumber = Math.random() * 100;
    cumulativeProbability = 0;
    for (const goldData of GOLD_PROBABILITIES) {
      if (goldData.rarity === selectedRarity) {
        cumulativeProbability += goldData.probability;
        if (randomNumber <= cumulativeProbability) {
          isGold = true;
          break;
        }
      }
    }
  
    // let card = await strapi.db.connection('cards')
    //   .where({ cardset: cardsetId, IsBlocked: false, rarity: selectedRarity })
    //   .orderByRaw('RANDOM()')
    //   .first().transacting(trx);

    const cards = await strapi.query('api::card.card').findMany({
        where: { cardset: cardsetId, IsBlocked: false,rarity: selectedRarity },
        populate: ['cardset'],
        transaction: trx,
    });

    let addedCards = cards.sort(() => { return Math.random() > 0.5 ? 1 : -1 });

    let card = addedCards[0];
  
    return {
      ...card,
      FaceRank: isGold ? 1 : 0,
    };
  }



async  open(ctx) {
        const userId = ctx.state.user.id;
        const { cardset } = ctx.request.body;
      
        let addedCards = [];
        let updatedCardPack;
      
        await strapi.db.transaction(async (trx) => {
          try {

            // 1. 获取用户数据和卡包信息
            const user = await strapi.query('plugin::users-permissions.user').findOne({
                where: { id: userId },
                transaction: trx,
            });



            // 1. 获取用户卡包信息和传奇卡保底计数
            let cardPack = await strapi.query('api::card-pack.card-pack').findOne({
                where: {
                    owners: [userId],
                    cardset: cardset.id
                },
                transaction: trx,
            });
      
            if (!cardPack) {
              throw new Error(`User doesn't own any card packs for this cardset`);
            }
    
      
            // 2. 减少卡包数量
            if (cardPack.amount > 0) {
              cardPack.amount -= 1;
              updatedCardPack = await strapi.db.connection('card_packs')
                .where('id', cardPack.id)
                .update({ amount: cardPack.amount }).transacting(trx);
            } else {
              throw new Error('Not enough card packs');
            }
      
            // 3. 生成卡牌
            let hasRareOrHigher = false;
            for (let i = 0; i < CARDS_PER_PACK; i++) {
              let card = await generateCard(cardset.id, trx);
              addedCards.push(card);
              if (card.Rarity >= 1) { // 直接比较数字
                hasRareOrHigher = true;
              }
            }
      
            // 4. 检查是否满足至少一张珍稀或更高级的条件
            // if (!hasRareOrHigher) {
            //   // 替换一张普通卡为珍稀或更高级的卡
            //   const commonCardIndex = addedCards.findIndex((card) => card.Rarity === 0);
            //   if (commonCardIndex !== -1) {
            //     addedCards[commonCardIndex] = await generateCard(cardset.id, trx, 1); // 最低稀有度为 1 (珍稀)
            //   }
            // }

            if (!hasRareOrHigher) {
                // 替换一张普通卡为珍稀或更高级的卡
                const commonCardIndex = addedCards.findIndex((card) => card.rarity === 0);
                if (commonCardIndex !== -1) {
                  // 不断生成卡牌，直到稀有度大于等于 1 且不与已有卡牌重复
                  do {
                    addedCards[commonCardIndex] = await generateCard(cardset.id, trx);
                  } while (
                    addedCards[commonCardIndex].Rarity === 0 || 
                    addedCards.indexOf(addedCards[commonCardIndex]) !== commonCardIndex // 检查是否与其他卡牌重复
                  );
                }
              }
      
            // 5. 处理传奇卡保底
            user.legendaryGuaranteeCounter = (user.legendaryGuaranteeCounter || 0) + 1;
            if (user.legendaryGuaranteeCounter >= GUARANTEED_LEGENDARY_PACKS) {
                const nonLegendaryIndex = addedCards.findIndex((card) => card.Rarity !== 3);
                if (nonLegendaryIndex !== -1) {
                addedCards[nonLegendaryIndex] = await generateCard(cardset.id, trx, 3);
                }
                user.legendaryGuaranteeCounter = 0;
            }
      
            // 6. 更新卡牌拥有信息和传奇卡保底计数
            await Promise.all(
              addedCards.map(async (card) => {

                    const existingOwnership = await strapi.query('api::card-owner-ship.card-owner-ship').findOne({
                    where: {
                        owner: userId,
                        card: card.id,
                        FaceRank:card.FaceRank
                    },
                    transaction: trx,
                });
                    if (existingOwnership) {
                    // Increase the amount if the user already owns the card
                    await strapi.entityService.update('api::card-owner-ship.card-owner-ship', existingOwnership.id, {
                        data: {
                            Amount: existingOwnership.Amount + 1,
                            FaceRank:card.FaceRank
                        },
                        transaction: trx,
                    });
                } else {
                    // Otherwise, create a new entry with Amount equal to 1
                    await strapi.entityService.create('api::card-owner-ship.card-owner-ship', {
                        data: {
                            card: card.id,
                            owner: userId,
                            Amount: 1,
                            FaceRank:card.FaceRank
                        },
                        transaction: trx,
                    });
                }
              })
            );

            await strapi.query('plugin::users-permissions.user').update({
                where: { id: userId },
                data: {
                    legendaryGuaranteeCounter: user.legendaryGuaranteeCounter
                },
                populate: ['cards'], 
                transaction: trx,// 使用 populate 方法获取关联的卡片对象
            });


            await trx.commit();
          } catch (error) {
            console.error('Error opening card pack:', error);
            await trx.rollback();
            throw error;
          }
        });
        console.log(addedCards.length)
        console.log(addedCards)

        return { Cards: addedCards, OpenedCardPack: updatedCardPack };
      }

这个是个开卡包的函数，我已经做了处理确保最少有一个Rarity > 0  的卡， 为什么运行时i还是会得到5张Rarity = 0 的卡牌，帮我解决下这个问题