import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqDuihuan, ResDuihuan } from "../../../shared/protocols/event/xianshizhaomu/PtlDuihuan";
import { xszmdb } from './ApiOpen';

export default async function (call: ApiCall<ReqDuihuan, ResDuihuan>) {
    let conf = G.gc.xianshizhaomu.duihuan[call.req.index];
    if (!conf || call.req.num <= 0) return call.error('', { code: -1 });

    let db = await xszmdb().findOne({ uid: call.uid, type: 'xianshizhaomu' });
    if ((db?.recordDuihuan?.[call.req.index] || 0) + call.req.num > conf.num) return call.error('', { code: -2 });

    let need = conf.need.map(need => { return { ...need, n: need.n * call.req.num }; });
    let prize = conf.prize.map(prize => { return { ...prize, n: prize.n * call.req.num }; });

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

    xszmdb().updateOne(
        { uid: call.uid, type: 'xianshizhaomu' },
        { $inc: G.mongodb.createTreeObj({ key: `recordDuihuan.${call.req.index}`, val: call.req.num }) },
        { upsert: true }
    );

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