import {ApiCall} from "tsrpc";
import {HuoDongFun} from "../../../public/huodongfun";
import {PayFun} from '../../../public/pay';
import {ReqOpen, ResOpen} from "../../../shared/protocols/event/leijichongzhi/PtlOpen";
import {PublicShared} from '../../../shared/public/public';
import {checkNextRound} from "./ApiRec";

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    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 db = await G.mongodb.cEvent(_dbType).findOne({uid: call.uid, type: _dbType});
    let sTime = db?.sTime || PublicShared.getToDayZeroTime(G.time);

    if (!db) {
        await G.mongodb.cEvent(_dbType).updateOne(
            {uid: call.uid, type: _dbType},
            {$set: {sTime: sTime, recIndex: [], round: 0}},
            {upsert: true}
        );
    }
    db = await checkNextRound(call, db, _hdinfo)

    let payNum = (await PayFun.getPayDaysAllPayNum(call.uid, _hdinfo.stime, _hdinfo.rtime)) * 10
    payNum = payNum - (db?.round || 0) * R.sort((a, b) => b.total - a.total)(_hdinfo.data.tasks)[0].total

    call.succ({
        sTime: sTime,
        recIndex: db?.recIndex || [],
        payNum: payNum,
        hdinfo: _hdinfo,
        round: db?.round || 0
    });
}