import {ApiCall} from "tsrpc";
import {ReqDMRec, ResDMRec} from "../../../shared/protocols/event/yuandan/PtlDMRec";
import {HuoDongFun} from "../../../public/huodongfun";
import {PlayerFun} from "../../../public/player";
import {HongDianChange} from "../../hongdian/fun";
import {PublicShared} from "../../../shared/public/public";

export default async function (call: ApiCall<ReqDMRec, ResDMRec>) {
    // 查询活动是否存在
    let _hd = (await HuoDongFun.gethdList(call, 14))[0]
    if (!_hd) return call.errorCode(-1)

    // 扣除免费次数或相应货币
    let data = await G.mongodb.cEvent(`yuandan${_hd.hdid}`).findOne({uid: call.uid, type: `yuandan${_hd.hdid}`})
    let rec = data?.gameNum

    if (rec && rec >= _hd.data?.gamefree) {
        await PlayerFun.checkNeedIsMeet(call, _hd.data.gameneed);
        await PlayerFun.cutNeed(call, _hd.data.gameneed);
    }

    let prize = []
    if (call.req.id) {
        prize = PublicShared.randomDropGroup('1', 1, {'1': _hd.data.game});
        await PlayerFun.sendPrize(call, prize);
    }

    await G.mongodb.cEvent(`yuandan${_hd.hdid}`).updateOne({uid: call.uid, type: `yuandan${_hd.hdid}`}, {
        $inc: {[`gameNum`]: 1},
    }, {upsert: true})

    call.succ({prize})

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