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

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 kbzzUserDb().findOne({ uid: call.uid, type: 'kbzzUser' });
    let buyNum = dbData.buyFightNum;
    let maxNum = G.gc.kbzz.buyFightNum[call.conn.gud.vip] || G.gc.hbzb.jfsBuyFightNum.slice(-1)[0];
    if (buyNum + num > maxNum) return call.error(globalThis.lng.kbzz_2);

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

    await kbzzUserDb().updateOne(
        { uid: call.uid, type: 'kbzzUser' },
        { $inc: { buyFightNum: num, fightNum: num } }
    );

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

    call.succ({});
}