import { ApiCall } from "tsrpc";
import { PlayerFun } from "../../public/player";
import { ReqRenownBuy, ResRenownBuy } from "../../shared/protocols/user/PtlRenownBuy";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqRenownBuy, ResRenownBuy>) {

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

    let _mydata = {
        // 礼包相关数据
        record: {},
        // 领取时间
        tequan: {
            istq: 0,
            recTime: 0
        }
    }

    _mydata = await G.mongodb.collection('playerInfo', 'juewei').findOne({ uid: call.conn.uid, type: 'juewei' }) || _mydata;
    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
    // 设置数据和发奖
    G.mongodb.collection('playerInfo', 'juewei').updateOne({ uid: call.conn.uid, type: 'juewei' }, { $inc: G.mongodb.createTreeObj({ key: `record.${call.req.index}`, val: 1 }) });
    await PlayerFun.sendPrize(call, selectPrize);

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

    call.succ({
        prize: selectPrize,
        mydata: _mydata
    });
}