import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqBuyNum, ResBuyNum } from "../../../shared/protocols/hbzb/zbs/PtlBuyNum";
import { prizeType } from '../../../shared/protocols/type';
import { PublicShared } from '../../../shared/public/public';

export default async function (call: ApiCall<ReqBuyNum, ResBuyNum>) {
    let num = Math.floor(call.req.num);
    if (num < 1) return call.error(globalThis.lng.gongyu_4);
    let dbData = await G.mongodb.cPlayerInfo('hbzbZbs').findOne({ uid: call.uid, type: 'hbzbZbs' });
    let buyNum = dbData?.data?.buyFightNum || 0;
    let maxNum = G.gc.hbzb.zbsBuyFightNum[call.conn.gud.vip] || G.gc.hbzb.zbsBuyFightNum.slice(-1)[0];

    if (buyNum + num > maxNum) return call.error(globalThis.lng.hbzb_8);


    let need: prizeType[] = [];
    for (let n = 1; n <= num; n++) {
        let cn = buyNum + n;
        let conf = G.gc.hbzb.zbsBuyFightNumNeed.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);

    await G.mongodb.cPlayerInfo('hbzbZbs').updateOne(
        { uid: call.uid, type: 'hbzbZbs' },
        { $set: { 'data.buyFightNum': buyNum + num } },
        { upsert: true }
    );
    call.succ({});
}