import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqTaskPrize, ResTaskPrize } from "../../../shared/protocols/event/kaifukuanghuan/PtlTaskPrize";
import { PublicShared } from '../../../shared/public/public';
import { HongDianChange } from "../../hongdian/fun";
import { getTaskVal } from './ApiOpen';

export default async function (call: ApiCall<ReqTaskPrize, ResTaskPrize>) {

    let conf: _gcType['kaifukuanghuan']['task']['1'][0] = G.gc.kaifukuanghuan.task[call.req.day]?.[call.req.index];

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

    let day = PublicShared.getOpenServerDay(call.conn.gud.cTime);

    if (call.req.day > day) return call.error(globalThis.lng.event_kfkh_7);

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

    if (data.receiveTask[call.req.day].includes(call.req.index)) return call.error(globalThis.lng.event_jijin_3);

    let finished = (await getTaskVal(call.conn.gud, [conf.taskType]))[conf.taskType] || 0;

    if (conf.taskType == 'jjc_rank') {
        if (finished > conf.total) return call.error(globalThis.lng.event_kfkh_8);
    } else {
        if (finished < conf.total) return call.error(globalThis.lng.event_kfkh_8);
    }

    G.mongodb.cEvent('kaifukuanghuan').updateOne(
        { uid: call.uid, type: 'kaifukuanghuan' },
        { $push: G.mongodb.createTreeObj({ key: `receiveTask.${call.req.day}`, val: call.req.index }) }
    );
    await PlayerFun.sendPrize(call, conf.prize);

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

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