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

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

    let payLog = await PayFun.getPayLog(call.uid, gift.payId)
    payLog = payLog?.filter(i => i.time >= _hd.stime && i.time <= _hd.etime) || []
    if (!payLog || !payLog.length) return call.errorCode(-2)


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

    await PlayerFun.sendPrize(call, gift[call.req.recId]);

    await G.mongodb.cEvent('pobinglibao').updateOne({uid: call.uid, type: 'pobinglibao'}, {
        $push: {[`record.${gift.id}`]: call.req.recId},
    }, {upsert: true})

    call.succ({})

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