import {ApiCall} from "tsrpc";
import {PayFun} from '../../../public/pay';
import {ReqOpen, ResOpen} from "../../../shared/protocols/event/yuedujijin/PtlOpen";
import {player} from '../../../shared/protocols/user/type';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let type = call.req.type as `${number}jijin`;
    if (!G.gc.pay[type]) return call.errorCode(-1);

    await checkNewRound(call, type)

    let db = await G.mongodb.cEvent(type).findOne({uid: call.uid, type: type});

    let recLength = db?.rec?.length - (db?.round || 0) * 30
    let rec = recLength ? (db?.rec?.slice(-recLength) || []) : []

    call.succ({
        rec: rec,
        days: db?.days - (db?.round || 0) * 30 || 0,
        round: db?.round
    });
}

export async function addDay(player: player) {
    for (let v of G.gc.yuedujijin) {
        if ((await PayFun.getPayLog(player.uid, v.payId)).length > 0) {
            let id = v.payId as `${number}jijin`;
            G.mongodb.cEvent(id).updateOne(
                {uid: player.uid, type: id},
                {$inc: {days: 1}},
                {upsert: true}
            );
        }
    }
}

export async function checkNewRound(call, type) {
    let db = await G.mongodb.cEvent(type).findOne({uid: call.uid, type: type});
    let recLength = db?.rec?.length - (db?.round || 0) * 30
    if (recLength==30) {
        await G.mongodb.cEvent(type).updateOne({uid: call.uid, type: type}, {
            $set: {
                days: Math.ceil(db?.rec?.length / 30) * 30 - 1,
                round: Math.ceil(db?.rec?.length / 30)
            }
        }, {upsert: true});

        PayFun.delPayLog(call.uid, {payId: type, val: []});
    }
}