import {ApiCall} from "tsrpc";
import {ReqZLRec, ResZLRec} from "../../../shared/protocols/event/yuandan/PtlZLRec";
import {HuoDongFun} from "../../../public/huodongfun";
import {PlayerFun} from "../../../public/player";
import {HongDianChange} from "../../hongdian/fun";
import {Yuandanfun} from "./fun";
import {PublicShared} from "../../../shared/public/public";

export default async function (call: ApiCall<ReqZLRec, ResZLRec>) {
    let _hd = await Yuandanfun.getCon(call)
    if (!_hd) return call.errorCode(-1)

    // 查询是否存在当前传入id的礼品
    let gift = _hd?.data?.qiandao?.[call.req.id]
    if (!gift) return call.errorCode(-2)

    // 奖励已领取
    let data = await G.mongodb.cEvent(`yuandan${_hd.hdid}`).findOne({uid: call.uid, type: `yuandan${_hd.hdid}`})
    let rec = data?.qiandao?.[call.req.id]
    if (rec) return call.errorCode(-3)

    if (data && data.qiandaoTime && PublicShared.chkSameDate(data.qiandaoTime, G.time)) {
        return call.errorCode(-4)
    }

    // 奖励不符合，严格判断
    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(-5)
    })

    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: {[`qiandao.${call.req.id}`]: prize, qiandaoTime: G.time},
    }, {upsert: true})

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

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