import {ApiCall} from "tsrpc";
import {ReqExchange, ResExchange} from "../../../shared/protocols/event/yuandan/PtlExchange";
import {HuoDongFun} from "../../../public/huodongfun";
import {PlayerFun} from "../../../public/player";
import {HongDianChange} from "../../hongdian/fun";

export default async function (call: ApiCall<ReqExchange, ResExchange>) {
    // 礼包不存在
    let _hd = (await HuoDongFun.gethdList(call, 14))[0]
    let gift = _hd?.data?.duihuan?.find(i => 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?.exchange?.[call.req.id]
    if (rec && rec >= gift?.buyNum) return call.errorCode(-2)

    await PlayerFun.checkNeedIsMeet(call, gift.need);
    await PlayerFun.cutNeed(call, gift.need)
    await PlayerFun.sendPrize(call, gift.prize);

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

    call.succ({})

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