import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqShopBuy, ResShopBuy } from "../../../shared/protocols/event/kaifukuanghuan/PtlShopBuy";
import { PublicShared } from '../../../shared/public/public';

export default async function (call: ApiCall<ReqShopBuy, ResShopBuy>) {
    let conf = G.gc.kaifukuanghuan.shop[call.req.index];
    let buyNum = call.req.buyNum || 1;

    if (!conf) return call.error(globalThis.lng.pata_getprize_1);
    if (call.conn.gud.vip < conf.vip) return call.error(globalThis.lng.event_kfkh_4);
    if (PublicShared.getOpenServerDay(call.conn.gud.cTime) < conf.day) return call.error(globalThis.lng.event_kfkh_5);

    let data = await G.mongodb.cEvent('kaifukuanghuan').findOne({ uid: call.uid, type: 'kaifukuanghuan' });
    let useBuyNum = data.buyShop[call.req.index] || 0;

    if (buyNum > conf.buyNum - useBuyNum) return call.error(globalThis.lng.event_kfkh_6);

    let needs = conf.need.map(need => { return { ...need, n: need.n * buyNum }; });
    await PlayerFun.checkNeedIsMeet(call, needs);
    await PlayerFun.cutNeed(call, needs);

    let prizes = conf.prize.map(prize => { return { ...prize, n: prize.n * buyNum }; });
    await PlayerFun.sendPrize(call, prizes);

    G.mongodb.cEvent('kaifukuanghuan').updateOne(
        { uid: call.uid, type: 'kaifukuanghuan' },
        { $inc: G.mongodb.createTreeObj({ key: 'buyShop', k: `${call.req.index}`, val: buyNum }) }
    );

    call.succ({
        prize: prizes
    });
}