import {ApiCall} from "tsrpc";
import {ReqDZRec, ResDZRec} from "../../../shared/protocols/event/yuandan/PtlDZRec";
import {HuoDongFun} from "../../../public/huodongfun";
import {PlayerFun} from "../../../public/player";
import {HongDianChange} from "../../hongdian/fun";

export default async function (call: ApiCall<ReqDZRec, ResDZRec>) {
    // 查询活动是否有当前领奖的免费选项
    let _hd = (await HuoDongFun.gethdList(call, 14))[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(`yuandan${_hd.hdid}`).findOne({uid: call.uid, type: `yuandan${_hd.hdid}`})
    let rec = data?.gift?.[call.req.id]
    if (rec && rec >= gift.buynum) return call.errorCode(-2)

    // 奖励不符合，严格判断
    let dlzList = R.flatten(gift.dlz.map(i => R.values(i)))
    call.req.dlz.map(i => {
        let item = dlzList.find(v => i.a == v.a && i.t == v.t && i.n == v.n)
        if (!item) call.errorCode(-4)
    })

    let prize = [...gift.prize, ...call.req.dlz]

    await PlayerFun.sendPrize(call, prize);

    await G.mongodb.cEvent(`yuandan${_hd.hdid}`).updateOne({uid: call.uid, type: `yuandan${_hd.hdid}`}, {
        $set: {[`gift.${gift.id}`]: prize},
    }, {upsert: true})

    call.succ({[gift.id]: prize})

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