import { ApiCall } from "tsrpc";
import { ReqFbOpen, ResFbOpen } from "../../shared/protocols/gonghui/PtlFbOpen";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqFbOpen, ResFbOpen>) {
    let res: ResFbOpen = { fightNum: 0, addNum: 0, rankList: [] };
    let conf = G.gc.shili_fb[call.req.fbId];
    let gh = await call.conn.gonghui;

    if (Number(call.req.fbId) > Number(gh.data.fuben.id)) return call.error(globalThis.lng.gonghui_14);
    if (!conf) return call.error(globalThis.lng.gonghui_15);
    if (call.req.fbId != gh.data.fuben.id) {
        let md = await G.mongodb.collection('gonghuiFb').findOne({ ghId: gh.data._id, fbId: call.req.fbId });
        let uids = Object.keys(md.rankList);
        let players = (await G.mongodb.find('user',{uid:{$in: uids}})) as any;
        res.rankList = players.map(p => {
            return {
                player: p,
                dps: md.rankList[p.uid]
            };
        });
    } else {
        let uids = Object.keys(gh.data.fuben.dps);
        let players = (await G.mongodb.find('user',{uid:{$in: uids}})) as any;
        res.rankList = players.map(p => {
            return {
                player: p,
                dps: gh.data.fuben.dps[p.uid]
            };
        });
    }

    let mdMy = (await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid }))?.fuben;
    if (!mdMy || PublicShared.getToDayZeroTime() > mdMy.refreshTime) {
        mdMy = {
            fightNum: G.gc.shili_com.fightNum,
            refreshTime: G.time
        };
        G.mongodb.collection('gonghuiUser').updateOne({ uid: call.uid }, { $set: { fuben: mdMy } }, { upsert: true });
    }
    call.succ({ ...res, fightNum: mdMy.fightNum, addNum: mdMy?.addNum||0 });
}