import { ApiCall } from "tsrpc";
import { HuoDongFun } from "../../../public/huodongfun";
import { PlayerFun } from '../../../public/player';
import { ReqBuy, ResBuy } from "../../../shared/protocols/event/zixuanlibao/PtlBuy";

export default async function (call: ApiCall<ReqBuy, ResBuy>) {
    let _hdinfo = await HuoDongFun.getHdidInfo(call, call.req.hdid)
    if (!_hdinfo || Object.keys(_hdinfo).length <= 0) {
        // 无此活动
        return call.error('', { code: -1, message: globalThis.lng.huodong_open_1 })
    }

    let _dbType: `zixuanlibao${number}` = `zixuanlibao${call.req.hdid}`

    let conf = _hdinfo.data.gift[call.req.index];
    if (!conf || conf.payId) return call.errorCode(-1);

    let data = await G.mongodb.cEvent(_dbType).findOne({uid: call.uid, type: _dbType})
    let rec = data?.rec?.[call.req.index]
    if (rec) return call.errorCode(-3)

    // 奖励不符合，严格判断
    let dlzList = R.flatten(conf.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 event = (await G.mongodb.cEvent(_dbType).findOne({ uid: call.uid, type: _dbType }));

    let buyNum = R.values(event?.rec)?.length || 0

    if (buyNum >= conf.buyNum) return call.errorCode(-3);

    if (conf.need.length > 0) {
        await PlayerFun.checkNeedIsMeet(call, conf.need);
        await PlayerFun.cutNeed(call, conf.need);
    }

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

    await PlayerFun.sendPrize(call, prize);

    await G.mongodb.cEvent(_dbType).updateOne({uid: call.uid, type: _dbType}, {
        $set: {[`rec.${call.req.index}`]: prize},
    }, {upsert: true})

    call.succ({
        prize: prize
    });
}