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.etime)) * 10;
    payNum = payNum - (db.round || 0) * R.sort((a, b) => b.total - a.total)(_hdinfo.data.tasks)[0].total
    if (payNum < conf.total) return call.error('', {code: -3});

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

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

    await checkNextRound(call, db, _hdinfo)

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

export async function checkNextRound(call: ApiCall, event, _hdinfo) {
    if ((event?.recIndex?.length || 0) < _hdinfo.data.tasks.length) return event
    let payNum = (await PayFun.getPayDaysAllPayNum(call.uid, _hdinfo.stime, _hdinfo.etime)) * 10
    payNum = payNum - (event?.round || 0) * R.sort((a, b) => b.total - a.total)(_hdinfo.data.tasks)[0].total
    if (payNum < 0) return event

    let _dbType: `leijichongzhi${number}` = `leijichongzhi${call.req.hdid}`
    return (await G.mongodb.cEvent(_dbType).findOneAndUpdate(
        {uid: call.uid, type: _dbType},
        {$set: {recIndex: []}, $inc: {round: 1}}, {returnDocument: 'after'}
    )).value;
}