import { ApiCall } from "tsrpc";
import { playerInfoType } from '../../module/collection_palyerInfo';
import { FightFun } from '../../public/fight';
import { ReqOpen, ResOpen } from "../../shared/protocols/kbzz/PtlOpen";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let second = G.time - PublicShared.getToWeekMondayZeroTime();

    if (second >= G.gc.kbzz.time.apply[0] && second < G.gc.kbzz.time.apply[1]) {
        applyTime(call);
    } else if (second >= G.gc.kbzz.time.applyEnd[0] && second < G.gc.kbzz.time.applyEnd[1]) {
        applyEndTime(call);
    } else {
        eventCycleTime(call);
    }
}

async function applyTime(call: ApiCall<ReqOpen, ResOpen>, type: 'apply' | 'event' = 'apply') {
    let state = await G.mongodb.cPlayerInfo('kbzzApply').findOne({ uid: call.uid, type: 'kbzzApply' });
    let resCall = await G.clientCross.callApi('kbzz/State', { type: type });

    call.succ({
        apply: state?.apply || false,
        autoApply: state?.autoApply || false,
        state: resCall.res
    });
}

async function applyEndTime(call: ApiCall<ReqOpen, ResOpen>) {
    applyTime(call, 'event');
}

async function eventCycleTime(call: ApiCall<ReqOpen, ResOpen>) {
    let state = await G.mongodb.cPlayerInfo('kbzzApply').findOne({ uid: call.uid, type: 'kbzzApply' });
    if (state?.apply != true) return call.error('', { code: -1, message: globalThis.lng.kbzz_3 });

    let isOpen = (await G.clientCross.callApi('kbzz/State', { type: 'event' })).res;
    console.log(isOpen)
    if (!isOpen.succ) return call.error('', { code: -2, message: globalThis.lng.kbzz_4 });

    let dbData = await kbzzUserDb().findOne({ uid: call.uid, type: 'kbzzUser' });
    let data: playerInfoType['kbzzUser'];

    if (!dbData) {
        let res = (await G.clientCross.callApi('kbzz/GetUser', { uid: call.uid })).res;
        data = {
            ...res,
            enemy: [],
            score: G.gc.kbzz.playerScore,
            fightNum: G.gc.kbzz.fightNum,
            toDayScore: 0,
            buyFightNum: 0,
            refreshTime: G.time,
            recScorePrize: []
        };
        kbzzUserDb().updateOne({ uid: call.uid, type: 'kbzzUser' }, { $set: { ...data } }, { upsert: true });
    } else {
        data = dbData;
        let zeroTime = PublicShared.getToDayZeroTime();
        if (zeroTime > data.refreshTime) {
            let addFightNum = Math.ceil((zeroTime - PublicShared.getToDayZeroTime(data.refreshTime)) / (3600 * 24)) * G.gc.kbzz.recoverFightNum;
            data.fightNum = data.fightNum + addFightNum > G.gc.kbzz.maxFightNum ? G.gc.kbzz.maxFightNum : data.fightNum + addFightNum;
            data.toDayScore = 0;
            data.buyFightNum = 0;
            data.recScorePrize = [];
            kbzzUserDb().updateOne({ uid: call.uid, type: 'kbzzUser' }, {
                $set: {
                    refreshTime: G.time,
                    fightNum: data.fightNum,
                    toDayScore: 0,
                    buyFightNum: 0,
                    recScorePrize: []
                }
            }, { upsert: true });
        }
    }

    call.succ(data);
}

export async function apply(uid: string) {
    G.mongodb.cPlayerInfo('kbzzApply').updateOne({ uid: uid, type: 'kbzzApply' }, { $set: { apply: true, applyTime: G.time } }, { upsert: true });

    let info = await FightFun.getPlayerFightData(uid);
    G.clientCross.callApi('kbzz/Apply', { info: info });
}

export const kbzzUserDb = () => {
    return G.mongodb.cPlayerInfo('kbzzUser');
};