import { ApiCall } from "tsrpc";
import { GHManage } from '../../public/gonghui/manage';
import { PlayerFun } from '../../public/player';
import { ReqJx, ResJx } from "../../shared/protocols/gonghui/PtlJx";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqJx, ResJx>) {
    const conf = G.gc.shili_com.juanxian[call.req.index];

    if (!conf) return call.error(globalThis.lng.gonghui_20);

    const data = await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid });
    const jx = data?.jx || { refreshTime: G.time, record: {} };

    let num = conf.maxNum;
    if (conf.vipAddNum.length > 0) {
        if (conf.vipAddNum[call.conn.gud.vip] != undefined) num += conf.vipAddNum[call.conn.gud.vip];
        else num += conf.vipAddNum.last();
    }
    if (jx.record[call.req.index] >= num) return call.error(globalThis.lng.gonghui_21);

    await PlayerFun.checkNeedIsMeet(call, conf.need);
    await PlayerFun.cutNeed(call, conf.need);
    await PlayerFun.sendPrize(call, conf.prize);
    await (await GHManage.getGH(call.conn.gud.ghId)).juanxian(call.req.index, call.uid);

    G.mongodb.collection('gonghuiUser').updateOne({ uid: call.uid }, { $inc: G.mongodb.createTreeObj({ key: 'jx', k: `record.${call.req.index}`, val: 1 }) });
    HongDianChange.sendChangeKey(call.uid, ['gonghuihd', 'taskhd', 'huodonghd'])
    call.succ({
        change: {},
        prize: conf.prize
    });
}