import { ApiCall } from "tsrpc";
import { PlayerFun } from "../../../public/player";
import { ReqBuy, ResBuy } from "../../../shared/protocols/event/yangchengmubiao/PtlBuy";
import { HongDianChange } from "../../hongdian/fun";
import { YangChengMuBiaofun } from "./fun";

export default async function (call: ApiCall<ReqBuy, ResBuy>) {
    let initCon = await YangChengMuBiaofun.getCon(call)
    let conf = initCon[call.req.hdid].data.gift[call.req.index];
    if (!conf || conf.payId) return call.errorCode(-1);

    let _mydata = await YangChengMuBiaofun.getMyData(call, call.req.hdid)
    let buyNum = _mydata.record?.[call.req.index] || 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 selectPrize = conf.prize
    // 设置数据和发奖
    await YangChengMuBiaofun.setMyData(call.uid, call.req.hdid, { $inc: G.mongodb.createTreeObj({ key: `record.${call.req.index}`, val: 1 }) })
    await PlayerFun.sendPrize(call, selectPrize);

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

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