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

export default async function (call: ApiCall<ReqBuyNum, ResBuyNum>) {
    if (!checkIsOpen()) return call.error(globalThis.lng.hbzb_7);
    let num = Math.floor(call.req.num);
    if (num < 1) return call.error(globalThis.lng.gongyu_4);
    let dbData = await G.mongodb.cPlayerInfo('hbzb').findOne({ uid: call.uid, type: 'hbzb' });
    let buyNum = dbData.data.buyFightNum;
    let maxNum = G.gc.hbzb.jfsBuyFightNum[call.conn.gud.vip] || G.gc.hbzb.jfsBuyFightNum.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.jfsBuyFightNumNeed.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('hbzb').updateOne(
        { uid: call.uid, type: 'hbzb' },
        { $set: { 'data.buyFightNum': buyNum + num } }
    );
    HongDianChange.sendChangeKey(call.uid, ['hbzbhd'])
    call.succ({});
}