import { ApiCall } from "tsrpc";
import { ReqOpen, ResOpen } from "../../shared/protocols/meirishilian/PtlOpen";
import { PublicShared } from '../../shared/public/public';

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

    let db = await G.mongodb.cPlayerInfo('meirishilian').findOne({ uid: call.uid, type: 'meirishilian' });
    let data = db?.data || {
        refreshTime: G.time,
        recordWin: Object.fromEntries(Object.keys(G.gc.meirishilian).map(t => [t, {}])),
        useFightNum: 0,
        buyFightNum: 0,
        numInfo: Object.fromEntries(Object.keys(G.gc.meirishilian).map(t => [t, {"0": { buyFightNum: 0, useFightNum: 0 }}]))
    };
    if (!db || db.data.refreshTime < PublicShared.getToDayZeroTime()) {
        data.useFightNum = 0;
        data.buyFightNum = 0;
        data.numInfo = Object.fromEntries(Object.keys(G.gc.meirishilian).map(t => [t, {"0": { buyFightNum: 0, useFightNum: 0 }}]))

        G.mongodb.cPlayerInfo('meirishilian').updateOne(
            { uid: call.uid, type: 'meirishilian' },
            { $set: { "data.refreshTime": G.time, 'data.useFightNum': 0, 'data.buyFightNum': 0, 'data.numInfo': data.numInfo } },
            { upsert: true }
        );
    }

    if (!data.recordWin) {
        data.recordWin = Object.fromEntries(Object.keys(G.gc.meirishilian).map(t => [t, {}]));
    }

    if (!data.numInfo) {
        data.numInfo = Object.fromEntries(Object.keys(G.gc.meirishilian).map(t => [t, {}]));
    }

    call.succ(data);
}