import { OptionalId, WithId } from 'mongodb';
import { ApiCall } from "tsrpc";
import { CollectionPlayerInfo } from '../../module/collection_palyerInfo';
import { joinFightData } from '../../shared/fightControl/fightType';
import { ReqOpen, ResOpen } from "../../shared/protocols/conglinshoulie/PtlOpen";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let db = await clslDb().findOne({ uid: call.uid, type: 'clsl' });
    let { _id, uid, type, ...ops } = db || {} as WithId<OptionalId<CollectionPlayerInfo<"clsl">>>;

    // 刷新 挑战次数、购买挑战次数、胜利次数任务
    if (!db || ops?.refreshTime < PublicShared.getToDayZeroTime()) {
        let change: Partial<typeof ops> = {
            refreshTime: G.time,
            useFightNum: 0,
            recWinPrize: [],
            fightWinNum: 0,
            buyFightNum: 0
        };

        // 隔周刷新星级
        if (ops?.refreshTime < PublicShared.getToWeekMondayZeroTime()) {
            change.allStar = 0;
            change.danPrize = [];
            change.curMaxStar = 0;
        }

        Object.assign(ops, change);

        clslDb().updateOne({ uid: call.uid, type: 'clsl' }, { $set: change }, { upsert: true });

        call.conn.getDefaultFightData().then(v => {
            G.clientCross.callApi('clsl/UpLoad', { uid: call.uid, info: v });
        });
    }

    call.succ({
        week: PublicShared.getWeek(G.time) || 7,
        allStar: ops?.allStar || 0,
        danPrize: ops?.danPrize || [],
        curMaxStar: ops?.curMaxStar || 0,
        buyFightNum: ops?.buyFightNum || 0,
        useFightNum: ops?.useFightNum || 0,
        fightWinNum: ops?.fightWinNum || 0,
        recWinPrize: ops?.recWinPrize || []
    });
}

export function clslDb() {
    return G.mongodb.cPlayerInfo('clsl');
}

export async function addStar(call: ApiCall, star: number, info?: joinFightData, update?: any) {
    update = update || {};

    if (update.$inc) {
        update.$inc["allStar"] = star
    } else {
        update["$inc"] = { allStar: star }
    }

    clslDb().updateOne({ uid: call.uid, type: 'clsl' }, update, { upsert: true });
    G.clientCross.callApi('clsl/UpLoad', { uid: call.uid, allStar: star, info: info || await call.conn.getDefaultFightData() });
}