import { ApiCall } from "tsrpc";
import { HuoDongFun } from "../../../public/huodongfun";
import { PlayerFun } from '../../../public/player';
import { ReqGet, ResGet } from "../../../shared/protocols/event/diaoluoduihuan/PtlGet";
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqGet, ResGet>) {
    let num = call.req.nums || 1;
    if (num < 1) return call.errorCode(-1);

    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 conf = _hdinfo.data.event[call.req.type];
    if (!conf[call.req.index] || conf[call.req.index].payId) return call.errorCode(-1);

    let db = await G.mongodb.cEvent(`diaoluoduihuan${call.req.hdid}`).findOne({ uid: call.uid, type: `diaoluoduihuan${call.req.hdid}` });
    let recordNum = db?.record?.[call.req.type]?.[call.req.index] || 0;
    if (recordNum + num > conf[call.req.index].num) return call.errorCode(-2);

    if (conf[call.req.index].need) {
        let need = conf[call.req.index].need.map(item => (
            { ...item, n: item.n * num }
        ));

        await PlayerFun.checkNeedIsMeet(call, need);
        await PlayerFun.cutNeed(call, need);
    }

    let prize = conf[call.req.index].prize.map(item => (
        { ...item, n: item.n * num }
    ));

    await PlayerFun.sendPrize(call, prize);

    G.mongodb.cEvent(`diaoluoduihuan${call.req.hdid}`).updateOne(
        { uid: call.uid, type: `diaoluoduihuan${call.req.hdid}` },
        { $inc: G.mongodb.createTreeObj({ key: `record.${call.req.type}.${call.req.index}`, val: num }) },
        { upsert: true }
    );
    HongDianChange.sendChangeKey(call.uid, ['huodonghd'])
    
    call.succ({
        prize: prize
    });
}