import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { ReqBuyNum, ResBuyNum } from "../../shared/protocols/slzd/PtlBuyNum";
import { prizeType } from '../../shared/protocols/type';
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqBuyNum, ResBuyNum>) {
    let num = Math.floor(call.req.num);
    if (num < 1) return call.error(globalThis.lng.kbzz_1);

    let dbData = await G.mongodb.collection('slzdUser').findOne({ uid: call.uid });
    let buyNum = dbData.data.buyFightNum;
    let maxNum = G.gc.slzd.maxFightNum;
    if (buyNum + num > maxNum) return call.error(globalThis.lng.slzd_2);

    let need: prizeType[] = [];
    for (let n = 1; n <= num; n++) {
        let cn = buyNum + n;
        let conf = G.gc.slzd.buyFightNumNeed.find(c => cn >= c.nums[0] && cn <= c.nums[1]);
        need.push(...conf.need);
    }
    need = PublicShared.mergePrize(need);

    await PlayerFun.checkNeedIsMeet(call, need);
    await PlayerFun.cutNeed(call, need);

    G.mongodb.collection('slzdUser').updateOne(
        { uid: call.uid },
        {
            $inc: { 'data.buyFightNum': num, 'data.fightNum': num }
        }
    );

    HongDianChange.sendChangeKey(call.uid, ['slzdhd'])

    call.succ({});
}