import { ApiCall } from "tsrpc";
import { HuoDongFun } from "../../../public/huodongfun";
import { PayFun } from '../../../public/pay';
import { PlayerFun } from '../../../public/player';
import { ReqRec, ResRec } from "../../../shared/protocols/event/leijichongzhi/PtlRec";
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 _dbType: `leijichongzhi${number}` = `leijichongzhi${call.req.hdid}`

    let conf = _hdinfo.data.tasks[call.req.index];
    if (!conf) return call.error('', { code: -1 });

    let db = await G.mongodb.cEvent(_dbType).findOne({ uid: call.uid, type: _dbType });
    if (db.recIndex.includes(call.req.index)) return call.error('', { code: -2 });

    let payNum = (await PayFun.getPayDaysAllPayNum(call.uid, _hdinfo.stime, _hdinfo.rtime)) * 10;
    if (payNum < conf.total) return call.error('', { code: -3 });

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

    G.mongodb.cEvent(_dbType).updateOne(
        { uid: call.uid, type: _dbType },
        { $push: { recIndex: call.req.index } }
    );

    HongDianChange.sendChangeKey(call.uid, ['huodonghd'])
    call.succ({
        prize: conf.prize
    });
}