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/xinshoulibao/PtlOpen";
import { PublicShared } from '../../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    // 后端加不加没多重要
    // let [isOpen, tips] = PublicShared.getOpenCond(call, "xinshoulibao")
    // if (!isOpen) return call.error('', { code: -1, message: tips });

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

    if (!db) {
        update = {
            $set: { index: 0, sTime: PublicShared.getToDayZeroTime(G.time) }
        };
    } else {
        if (db.sTime + G.gc.xinshoulibao[db.index].time < G.time) {

            db.sTime = PublicShared.getToDayZeroTime(G.time);
            db.index = G.gc.xinshoulibao[db.index + 1] == undefined ? db.index : db.index + 1;

            update = {
                $set: { index: db.index, sTime: db.sTime }
            };

            if (db.index == G.gc.xinshoulibao.length - 1) {
                PayFun.delPayLog(call.uid, ...G.gc.xinshoulibao[db.index].pays.map(p => { return { payId: p.payId, val: [] }; }));
            }
        }
    }

    update && G.mongodb.cEvent('xinshoulibao').updateOne({ uid: call.uid, type: 'xinshoulibao' }, update, { upsert: true });

    call.succ({
        index: db?.index || 0,
        sTime: db?.sTime || PublicShared.getToDayZeroTime(G.time)
    });
}