import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { ReqBuy, ResBuy } from "../../shared/protocols/meirishilian/PtlBuy";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqBuy, ResBuy>) {
    let db = await G.mongodb.cPlayerInfo('meirishilian').findOne({ uid: call.uid, type: 'meirishilian' });
    let buyNum = db?.data?.numInfo?.[call.req.type]?.['0']?.buyFightNum || 0;

    let addNum = call.req.num;
    if (buyNum + addNum > G.gc.meirishilian_com.fightBuyNum) return call.error('', { code: -1 });
    
    let need = [];
    for (let i = 0; i < addNum; i++) {
        need.push(G.gc.meirishilian_com.fightBuyNumNeed[buyNum]);
        buyNum++;
    }
    await PlayerFun.checkNeedIsMeet(call, need);

    await PlayerFun.cutNeed(call, need);

    await G.mongodb.cPlayerInfo('meirishilian').updateOne(
        { uid: call.uid, type: 'meirishilian' },
        { $inc: G.mongodb.createTreeObj({ key: `data.numInfo.${call.req.type}.0.buyFightNum`, val: addNum }) },
        { upsert: true }
    );

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

    call.succ({});
}