import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqGet, ResGet } from "../../../shared/protocols/event/jierihuodong/PtlGet";

export default async function (call: ApiCall<ReqGet, ResGet>) {
    let req = call.req;
    let db = await G.mongodb.cEvent('jierihuodong').findOne({ uid: call.uid, type: 'jierihuodong' });

    let conf = req.type == 'duihuan' ? G.gc.jierihuodong.duihuan : G.gc.jierihuodong.libao;
    if (!conf[req.index]) return call.error('', { code: -1 });

    let record = req.type == 'duihuan' ? (db?.recordDuihuan || {}) : (db?.recordLibao || {});
    if (record[req.index] + req.num > conf[req.index].num) return call.error('', { code: -2 });

    let need = conf[req.index].need.map(_n => {
        return { ..._n, n: _n.n * req.num };
    });

    let prize = conf[req.index].prize.map(_p => {
        return { ..._p, n: _p.n * req.num };
    });

    await PlayerFun.checkNeedIsMeet(call, need);
    await PlayerFun.cutNeed(call, need);
    await PlayerFun.sendPrize(call, prize);

    G.mongodb.cEvent('jierihuodong').updateOne(
        { uid: call.uid, type: 'jierihuodong' },
        { $inc: G.mongodb.createTreeObj({ key: req.type == 'duihuan' ? `recordDuihuan.${req.index}` : `recordLibao.${req.index}`, val: req.num }) }
    );

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