/**
 * 争霸赛分组，每300个玩家分一组
 * 最后一组：如果是有100人即往上人数 那就自己一组打
 * 如果不够100  就合到前一组
 */
export async function zbsGroup() {
    let arr = await G.mongodb.collection("hbzb_user_cross").find(
        {"jifen": {$gt: -999999}}
    ).project({
        uid: 1,
        jifen: 1,
        'data.player.cTime': 1
    }).toArray();

    // 移除mongo查询里的排序，↑会造成内存超出报错，
    // 在内存里按照玩家注册时间相近的排序分组
    R.sort((a, b) => b.data.player.cTime - a.data.player.cTime)

    //有积分的玩家总数
    let groups = [];
    let currGroup = [];

    arr.map((u, index) => {
        if (currGroup.length >= 300) {
            //每300个丢一组
            groups.push(currGroup);
            currGroup = [];
        }
        currGroup.push({uid: u.uid, jifen: u.jifen});
    });

    //循环完毕后检查余量
    if (currGroup.length > 0) {
        if (currGroup.length >= 100) {
            //如果有100人 就自己一组
            groups.push(currGroup);
        } else {
            //不够100 就合到前一组
            groups[groups.length] = (groups[groups.length] || []).concat(currGroup);
        }
        currGroup = [];
    }

    //循环groups里的数据，对每一组里按jifen降序排序，然后给每个玩家分组
    groups.map((group, groupIndex) => {
        group.sort((a, b) => {
            return b.jifen - a.jifen;
        });
        for (let i = 0; i < group.length; i++) {
            G.mongodb.collection("hbzb_user_cross").updateOne(
                {uid: group[i].uid},
                {
                    $set: {
                        "zbsgroup": "group" + (groupIndex + 1),
                        "rank": (i + 1),
                    }
                }
            )
        }
    })
}

/**
 * 获取争霸赛阶段排行
 */
export async function getZbsRankList(uid?: string, _zbsgroup?: string): Promise<{ myRank: any; rankList: any[]; }> {
    let myData;
    let zbsgroup = _zbsgroup;

    if (uid) {
        myData = await G.crossmongodb.collection("hbzb_user_cross").findOne({uid: uid});
        if (!myData || !myData?.zbsgroup) return null;
        zbsgroup = myData?.zbsgroup;
    }

    let arr = await G.crossmongodb.collection("hbzb_user_cross").find(
        {"zbsgroup": zbsgroup}
    ).sort(
        {"rank": 1}
    ).limit(100).toArray();


    let rank = {
        "myRank": {},
        "rankList": []
    }

    let myRank = -1;
    arr.map((u, index) => {
        rank.rankList.push({
            player: ((u.data) as any).player || {},
            roles: ((u.data) as any).roles || {},
            rank: (index + 1),
            //兼容前端
            valArr: [(index + 1)]
        });

        if (u.uid == uid) {
            myRank = rank.rankList.length;
            rank.myRank = {
                player: ((u.data) as any).player || {},
                roles: ((u.data) as any).roles || {},
                rank: (index + 1),
                //兼容前端
                valArr: [(index + 1)]
            };
        }
    })

    return rank;


}
