import { UpdateFilter } from 'mongodb';
import { ApiCall } from "tsrpc";
import { CollectionEvent } from '../../../module/collection_event';
import { PayFun } from '../../../public/pay';
import { ReqOpen, ResOpen } from "../../../shared/protocols/event/qirichongzhi/PtlOpen";
import { PublicShared } from '../../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {

    let db = await G.mongodb.cEvent('qirichongzhi').findOne({ uid: call.uid, type: 'qirichongzhi' });
    let update: UpdateFilter<CollectionEvent<'qirichongzhi'>>;
    let sTime = PublicShared.getToDayZeroTime(G.time);

    if (!db) {
        update = {
            $set: { round: 0, sTime: sTime, recIndexs: [] }
        };
    } else {
        if (db.sTime + G.gc.qirichongzhi[db.round].time < G.time) {

            db.sTime = sTime;
            db.round = G.gc.qirichongzhi[db.round + 1] == undefined ? db.round : db.round + 1;
            db.recIndexs = [];

            update = {
                $set: { index: db.round, sTime: db.sTime, recIndex: [] }
            };
        } else {
            sTime = db.sTime;
        }
    }

    update && G.mongodb.cEvent('qirichongzhi').updateOne({ uid: call.uid, type: 'qirichongzhi' }, update, { upsert: true });
    let round = db?.round || 0;

    call.succ({
        round: round,
        sTime: sTime,
        recIndexs: db?.recIndexs || [],
        finished: await PayFun.getPayDaysAllPayNum(call.uid, sTime, sTime + G.gc.qirichongzhi[round].time)
    });
}