import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { ReqBuyGift, ResBuyGift } from "../../shared/protocols/chongzhi/PtlBuyGift";

export default async function (call: ApiCall<ReqBuyGift, ResBuyGift>) {

    if (call.req.vip > call.conn.gud.vip) return call.error(globalThis.lng.chongzhi_1);
    if (!G.gc.chongzhi.tequan[call.req.vip] || !G.gc.chongzhi.tequan[call.req.vip].gift) return call.error(globalThis.lng.chongzhi_2);

    let data = await G.mongodb.cPlayerInfo('chongzhi').findOne({ uid: call.uid, type: 'chongzhi' });
    let buyNum = data?.giftBy?.[call.req.vip];
    let need = G.gc.chongzhi.tequan[call.req.vip].gift.need.map(v => { return { ...v, n: v.n * G.gc.chongzhi.tequan[call.req.vip].gift.sale / 10 }; });
    if (buyNum >= G.gc.chongzhi.tequan[call.req.vip].gift.buyNum) return call.error(globalThis.lng.chongzhi_3);

    await PlayerFun.checkNeedIsMeet(call, need);
    await PlayerFun.cutNeed(call, need);
    await PlayerFun.sendPrize(call, G.gc.chongzhi.tequan[call.req.vip].gift.prize);

    G.mongodb.cPlayerInfo('chongzhi').updateOne(
        { uid: call.uid, type: 'chongzhi' },
        { $inc: G.mongodb.createTreeObj({ key: 'giftBy', k: call.req.vip.toString(), val: 1 }) },
        { upsert: true }
    );

    call.succ({
        prize: G.gc.chongzhi.tequan[call.req.vip].gift.prize
    });
}