import {ApiCall} from "tsrpc";
import {Rank} from '../../../public/rank/rank';
import {ReqOpen, ResOpen} from "../../../shared/protocols/hbzb/jfs/PtlOpen";
import {PublicShared} from '../../../shared/public/public';
import {getHbzbData, getMyRank, getToper200RankUid, updateHbzbCrossUser} from "./fun";

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    //查看本地数据库里，刷出来的玩家数据
    let dbData = await getHbzbData(call.uid);
    let data: typeof dbData.data = dbData?.data || {} as any;

    //如果没有，则同步到跨服
    await updateHbzbCrossUser(await call.conn.getDefaultFightData(), dbData == null);

    if (!data.refreshTime || data.refreshTime < PublicShared.getToDayZeroTime()) {
        data.winNum = 0;
        data.buyFightNum = 0;
        data.useFightNum = 0;
        data.refreshTime = G.time;
        data.winRecPrize = [];
        data.useRefreshNum = 0;

        if (!data.enemy) {
            //积分赛时的排行榜，是本服积分排序
            data.jifen = 0;
            //但是刷出来的对手，是跨服的玩家
            let callRes = await G.clientCross.callApi('hbzb/jfs/GetEnemy', {uid: call.uid, auto: true});
            if (!callRes.isSucc) {
                //todo 健壮性处理
                return call.errorCode(-4)
            }
            if (callRes.res?.enemy?.length)
                data.enemy = callRes.res.enemy.map(e => {
                    return {...e, result: null};
                });
        }

        G.mongodb.cPlayerInfo('hbzb').updateOne(
            {uid: call.uid, type: 'hbzb'},
            {$set: {data: data}},
            {upsert: true}
        );
    }

    call.succ({
        ...data,
        enemy: data.enemy || [],
        rank: await getMyRank(call.uid)
    });
}

export function checkIsOpen() {
    let weekZeroTime = PublicShared.getToWeekMondayZeroTime();
    return G.time >= weekZeroTime + G.gc.hbzb.jfsOpenTime[0] && G.time <= weekZeroTime + G.gc.hbzb.jfsOpenTime[1];
}