import { ApiCall } from "tsrpc";
import { FightFun } from '../../public/fight';
import { PlayerFun } from '../../public/player';
import { ReqFight, ResFight } from "../../shared/protocols/meirishilian/PtlFight";
import { PlayerShared } from '../../shared/public/player';
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqFight, ResFight>) {
    let conf = G.gc.meirishilian[call.req.type]?.[call.req.difficulty];
    if (!conf) return call.error('', { code: -1 });

    let db = await G.mongodb.cPlayerInfo('meirishilian').findOne({ uid: call.uid, type: 'meirishilian' });
    let useNum = db?.data?.numInfo?.[call.req.type]?.['0']?.useFightNum || 0;
    let buyNum = db?.data?.numInfo?.[call.req.type]?.['0']?.buyFightNum || 0;
    if (useNum >= buyNum + (PlayerShared.getMingDaoBuff(call.conn.gud, 'wzsj_free') || 0) + G.gc.meirishilian_com.fightNum) return call.error('', { code: -2 });

    let res: ResFight = {};
    if (db?.data?.recordWin?.[call.req.type]?.[call.req.difficulty]) {
        res.prize = conf.prize;
    } else {
        let result = res.result = await FightFun.fightNpc(call, conf.npcId, 'meirishilian');
        if (result.winSide == 0) res.prize = conf.prize;
    }
    res.prize && await PlayerFun.sendPrize(call, res.prize);
    res.prize && await G.mongodb.cPlayerInfo('meirishilian').updateOne(
        { uid: call.uid, type: 'meirishilian' },
        { $inc: G.mongodb.createTreeObj({ key: `data.numInfo.${call.req.type}.0.useFightNum`, val: 1 }, { key: `data.recordWin.${call.req.type}.${call.req.difficulty}`, val: 1 }) },
        { upsert: true }
    );

    HongDianChange.sendChangeKey(call.uid, ['wzcjhd', 'taskhd', 'huodonghd'])

    call.succ(res);
}