import { ApiCall } from "tsrpc";
import { ActionLog } from '../../../public/actionLog/actionLog';
import { PlayerFun } from '../../../public/player';
import { ReqRec, ResRec } from "../../../shared/protocols/event/jierihuodong/PtlRec";
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqRec, ResRec>) {
    let req = call.req;
    let db = await G.mongodb.cEvent('jierihuodong').findOne({ uid: call.uid, type: 'jierihuodong' });

    let conf = req.type == 'login' ? G.gc.jierihuodong.denglufuli : G.gc.jierihuodong.huodongrenwu;
    if (!conf[req.index]) return call.error('', { code: -1 });

    let recIndex = req.type == 'login' ? (db?.recLogin || []) : (db?.recTask || []);
    if (recIndex.includes(req.index)) return call.error('', { code: -2 });

    let finish = req.type == 'login' ? call.conn.gud.loginDays : await ActionLog.getDayLog(call.uid, conf[req.index].taskId);
    if (finish < conf[req.index].total) return call.error('', { code: -3 });

    await PlayerFun.sendPrize(call, conf[req.index].prize);

    G.mongodb.cEvent('jierihuodong').updateOne(
        { uid: call.uid, type: 'jierihuodong' },
        { $push: req.type == 'login' ? { recLogin: req.index } : { recTask: req.index } }
    );

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

    call.succ({
        prize: conf[req.index].prize
    });
}