import { ApiCall } from "tsrpc";
import { ActionLog } from '../../public/actionLog/actionLog';
import { PlayerFun } from '../../public/player';
import { ReqTaskReceive, ResTaskReceive } from "../../shared/protocols/gonghui/PtlTaskReceive";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqTaskReceive, ResTaskReceive>) {
    let prize: atn[];
    let gh = await call.conn.gonghui;
    let data = await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid });

    if (call.req.type == 'gh') {


        if (!G.gc.shili_com.ghTask[call.req.index]) return call.error(globalThis.lng.gonghui_15);
        if (G.gc.shili_com.ghTask[call.req.index].total > gh.data.task.finised) return call.error(globalThis.lng.gonghui_26);
        if (data.task.ghRec.includes(call.req.index)) return call.error(globalThis.lng.gonghui_27);

        prize = G.gc.shili_com.ghTask[call.req.index].prize;

        G.mongodb.collection('gonghuiUser').updateOne({ uid: call.uid }, { $push: { 'task.ghRec': call.req.index } });
    } else {

        if (!G.gc.shili_com.task[call.req.index]) return call.error(globalThis.lng.gonghui_15);
        if (G.gc.shili_com.task[call.req.index].total > await ActionLog.getDayLog(call.uid, G.gc.shili_com.task[call.req.index].taskId)) return call.error(globalThis.lng.gonghui_26);
        if (data.task.myRec.includes(call.req.index)) return call.error(globalThis.lng.gonghui_27);

        prize = G.gc.shili_com.task[call.req.index].prize;

        G.mongodb.collection('gonghuiUser').updateOne({ uid: call.uid }, { $push: { 'task.myRec': call.req.index } });

        gh.data.task.finised++;
        gh.updateDb({ $inc: { 'task.finised': 1 } });

        G.gc.shili_com.task[call.req.index].addExp && gh.addExp(G.gc.shili_com.task[call.req.index].addExp, call.uid);
    }

    await PlayerFun.sendPrize(call, prize);
    HongDianChange.sendChangeKey(call.uid, ['gonghuihd']);
    call.succ({
        prize: prize
    });
}