import {ApiCall} from "tsrpc";
import {FightFun} from '../../public/fight';
import {PlayerFun} from "../../public/player";
import {formatNpcData} from '../../shared/fightControl/fightFun';
import {ReqChallenge, ResChallenge} from "../../shared/protocols/ganbutexun/PtlChallenge";

export default async function (call: ApiCall<ReqChallenge, ResChallenge>) {
    let heroid = call.req.id;
    let conf = G.gc.ganbutexun[heroid];
    // 判断开启条件
    // 判断关卡进度 TODO
    let isUnlock = Object.entries(conf.cond).every(v => call.conn.gud[v[0]] >= v[1]);
    if (!isUnlock) {
        return call.error('', {code: -1});
    }
    let need = [conf.need];
    await PlayerFun.checkNeedIsMeet(call, need);
    // 战斗 TODO

    let prize = [];
    let addnum = 0;
    let fightNum = (await G.mongodb.collection('gbtx').findOne({uid: call.uid}))?.fightNum?.[call.req.id] || 0;
    fightNum + 1;

    let lv = fightNum % 6 + fightNum;
    let npc = formatNpcData(conf.battle, null, lv);
    const result = FightFun.fight([await call.conn.getDefaultFightData(), npc]);
    const isWin = result.winSide == 0;

    if (isWin) {
        addnum = G.gc.common.gbtxcom.gbtxadd;

        let data = await G.redis.get('gbtx', call.uid, 'luck');
        let prizeArr = JSON.parse(JSON.stringify(conf.prize));
        let obj = {};
        obj['luck.' + call.req.id] = addnum;
        data[call.req.id] = data[call.req.id] || 0;
        prize = (data[call.req.id] > 0 && data[call.req.id] % 6 == 5) ? prizeArr.map((item) => {
            item.n *= 2;
            return item;
        }) : prizeArr;
        data[call.req.id] += addnum;
        G.redis.set('gbtx', call.uid, 'luck', data);

        await PlayerFun.cutNeed(call, need);
        await PlayerFun.addItem(call, prize);

        G.mongodb.collection('gbtx').updateOne(
            {uid: call.uid},
            {
                $inc: obj
            },
            {
                upsert: true
            }
        );
    }

    G.mongodb.collection('gbtx').updateOne(
        {uid: call.uid},
        {
            $inc: G.mongodb.createTreeObj({key: `fightNum.${call.req.id}`, val: 1})
        },
        {
            upsert: true
        }
    );
    return call.succ({
        addluck: addnum,
        prize: prize,
        fightobj: result
    });
}