import { ApiCall } from "tsrpc";
import { HuoDongFun } from "../../../public/huodongfun";
import { PlayerFun } from '../../../public/player';
import { ReqRec, ResRec } from "../../../shared/protocols/event/chuanshuozhilu/PtlRec";
import { prizeType } from '../../../shared/protocols/type';
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqRec, ResRec>) {
    let _hdinfo = await HuoDongFun.getHdidInfo(call, call.req.hdid)
    if (!_hdinfo || Object.keys(_hdinfo).length <= 0) {
        // 无此活动
        return call.error('', { code: -1, message: globalThis.lng.huodong_open_1 })
    }

    let curTask = _hdinfo.data
    if (call.req.type == 'task' && !curTask.task[call.req.index]) return call.errorCode(0);

    let prize: prizeType[] = [];

    let _dbType: `chuanshuozhilu${number}` = `chuanshuozhilu${call.req.hdid}`

    let db = await G.mongodb.cEvent(_dbType).findOne({ uid: call.uid, type: _dbType });
    let info: Partial<typeof db.info['']> = db?.info?.[curTask.hid] || {};
    let rec = info.rec || [];

    if (call.req.type == 'box') {
        if (info.box) return call.errorCode(-1);
        if (rec.length < curTask.box.total) return call.errorCode(-2);

        prize.push(...curTask.box.prize);

        G.mongodb.cEvent(_dbType).updateOne(
            { uid: call.uid, type: _dbType },
            { $set: G.mongodb.createTreeObj({ key: `info.${curTask.hid}.box`, val: true }) },
            { upsert: true }
        );
    } else {
        let conf = curTask.task[call.req.index];
        let finish = info[conf.type] || 0;
        if (finish < conf.total) return call.errorCode(-3);
        if (rec.includes(call.req.index)) return call.errorCode(-4);

        G.mongodb.cEvent(_dbType).updateOne(
            { uid: call.uid, type: _dbType },
            { $push: G.mongodb.createTreeObj({ key: `info.${curTask.hid}.rec`, val: call.req.index }) },
            { upsert: true }
        );

        prize.push(...conf.prize);
    }

    await PlayerFun.sendPrize(call, prize);
    HongDianChange.sendChangeKey(call.uid, ['huodonghd'])

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