import { ApiCall } from "tsrpc";
import { ReqUpLoad, ResUpLoad } from "../../cross/protocols/clsl/PtlUpLoad";
import { Rank } from '../../public/rank/rank';
import { PublicShared } from "../../shared/public/public";
import { RankClslCross } from "../../public/rank/rank_clsl";

export default async function (call: ApiCall<ReqUpLoad, ResUpLoad>) {
    let { allStar, uid, ...ops } = call.req;

    let a = (await G.mongodb.collection('clslCrossUser').findOneAndUpdate(
        { uid: uid },
        {
            $inc: { allStar: allStar || 0 },
            $set: ops
        },
        { upsert: true, returnDocument: "after" }
    )).value;
    
    // 周四 并且没有分组 更新玩家分组
    if ((PublicShared.getWeek(G.time) || 7) >= 4 && !a.group) {
        // 查询分组数据
        let week = PublicShared.getToWeek();
        let group = await G.mongodb.collection('clslCrossGroup').findOne({ week: week });
        for (let groupid in group.groups) {
            let groupinfo = group.groups[groupid];
            if (a.info.player.cTime >= groupinfo.st && a.info.player.cTime < groupinfo.et) {
                a.group = groupid;
                G.mongodb.collection('clslCrossUser').updateOne({ uid: uid }, { $set: { group: a.group } });
                break;
            }
        }
    }

    if (a.group) { // 分完组之后就可以更新排行榜了
        if (allStar != undefined && ops.info) {
            let rank;
            if (Rank.list[`clslCross_${a.group}`]) {
                rank = Rank.list[`clslCross_${a.group}`]
            }
            else {
                rank = new RankClslCross(a.group)
            }
            rank.addNew({
                player: a.info.player,
                valArr: [a.allStar, a.info.player.power]
            });
        }
    }
}