import {ApiCall} from "tsrpc";
import {ReqReceive, ResReceive} from "../../../shared/protocols/event/zhoumolibao/PtlReceive";
import {HuoDongFun} from "../../../public/huodongfun";
import {PlayerFun} from "../../../public/player";
import {HongDianChange} from "../../hongdian/fun";

export default async function (call: ApiCall<ReqReceive, ResReceive>) {
    // 查询活动是否有当前领奖的免费选项
    let _hd = (await HuoDongFun.gethdList(call, 9))[0]
    let gift = _hd?.data?.gift?.find(i => i.free && i.id == call.req.id)
    if (!gift) return call.errorCode(-1)

    // 取奖励列表，判断是否有可领取奖励
    let data = await G.mongodb.cEvent('zhoumolibao').findOne({uid: call.uid, type: 'zhoumolibao'})
    let rec = data?.record?.[call.req.id]
    if (rec && rec >= gift?.buyNum) return call.errorCode(-2)

    await PlayerFun.sendPrize(call, gift.prize);

    await G.mongodb.cEvent('zhoumolibao').updateOne({uid: call.uid, type: 'zhoumolibao'}, {
        $inc: {[`record.${gift.id}`]: 1},
    }, {upsert: true})

    call.succ({})

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