import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqRecAll, ResRecAll } from "../../../shared/protocols/event/yibaichou/PtlRecAll";
import { prizeType } from '../../../shared/protocols/type';

export default async function (call: ApiCall<ReqRecAll, ResRecAll>) {

    let db = await G.mongodb.cEvent('yibaichou').findOne({ uid: call.uid, type: 'yibaichou' });
    let prize: prizeType[] = [];
    let loginRec = db?.loginRec || [];
    let onlineRec = db?.onlineRec || [];

    G.gc.yibaichou.loginPrize.forEach((t, index) => {
        if (call.conn.gud.loginDays >= t.total && !loginRec.includes(index)) {
            prize.push(...t.prize);
            loginRec.push(index);
        }
    });

    G.gc.yibaichou.onlinePrize.forEach((t, index) => {
        if (call.conn.gud.onlineTime >= t.total && !onlineRec.includes(index)) {
            prize.push(...t.prize);
            onlineRec.push(index);
        }
    });

    if (prize.length > 0) {
        prize = await PlayerFun.sendPrize(call, prize);
        G.mongodb.cEvent('yibaichou').updateOne(
            { uid: call.uid, type: 'yibaichou' },
            { $set: { loginRec: loginRec, onlineRec: onlineRec } },
            { upsert: true }
        );
    }

    if (loginRec?.length >= G.gc.yibaichou.loginPrize.length) {
        G.mongodb.collection('syncBtns').updateOne({ uid: call.uid }, { $set: { 'yibaichou.active': false } }, { upsert: true });
    }

    call.succ({
        prize: prize,
        change: {
            loginRec: loginRec,
            onlineRec: onlineRec
        }
    });
}