import {ApiCall} from "tsrpc";
import {eventType} from '../../../module/collection_event';
import {PlayerFun} from '../../../public/player';
import {ZhanLingTasks} from '../../../public/zhanling';
import {ReqRecTask, ResRecTask} from "../../../shared/protocols/event/zhanling/PtlRecTask";
import {HongDianChange} from "../../hongdian/fun";

export default async function (call: ApiCall<ReqRecTask, ResRecTask>) {
    let conf = G.gc.zhanling.task[call.req.index];

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

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

    if (data.taskRec.includes(call.req.index)) return call.error(globalThis.lng.event_kfkh_12);

    let taskVal = await ZhanLingTasks.getLog(call.uid, {type: conf.type as any, key: conf.taskId});

    if (taskVal < conf.total) return call.error(globalThis.lng.event_kfkh_13);

    conf.prize && await PlayerFun.sendPrize(call, conf.prize);

    G.mongodb.cEvent('zhanling').updateOne(
        {uid: call.uid, type: 'zhanling'},
        {$push: {taskRec: call.req.index}}
    );

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

    call.succ({
        prize: conf.prize || [],
        change: await addExp(call.uid, conf.exp, data)
    });
}

export async function addExp(uid: string, exp: number, data?: eventType['zhanling']) {
    if (!data) data = await G.mongodb.cEvent('zhanling').findOne({uid: uid, type: 'zhanling'});
    let change: ResRecTask['change'] = {};

    change.exp = (data?.exp || 0) + exp;

    let lv = data?.lv || 1
    while (G.gc.zhanling.lv[lv + 1] < change.exp) {
        lv += 1
    }
    if (lv > (data?.lv || 1)) {
        change.lv = lv
    }
    await G.mongodb.cEvent('zhanling').updateOne(
        {uid: uid, type: 'zhanling'},
        {$set: change}
    );

    return change;
}