import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqTaskBox, ResTaskBox } from "../../../shared/protocols/event/kaifukuanghuan/PtlTaskBox";
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqTaskBox, ResTaskBox>) {

    let conf = G.gc.kaifukuanghuan.taskBoxPrize[call.req.index];

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

    let data = await G.mongodb.cEvent('kaifukuanghuan').findOne({ uid: call.uid, type: 'kaifukuanghuan' });

    if (data.receiveBox.includes(call.req.index)) return call.error(globalThis.lng.event_jijin_3);

    let finished = Object.values(data.receiveTask).map(fs => fs.length).reduce((a, b) => a + b);

    if (finished < conf.total) return call.error(globalThis.lng.event_jijin_1);

    G.mongodb.cEvent('kaifukuanghuan').updateOne(
        { uid: call.uid, type: 'kaifukuanghuan' },
        { $push: { receiveBox: call.req.index } }
    );
    await PlayerFun.sendPrize(call, conf.prize);

    HongDianChange.sendChangeKey(call.uid, ['kaifukuanghuanhd'])

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