import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqRec, ResRec } from "../../../shared/protocols/event/yibaichou/PtlRec";
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqRec, ResRec>) {
    let type = call.req.type;
    let index = call.req.index;

    let conf = G.gc.yibaichou[type + 'Prize'][index] as _gcType['yibaichou']['loginPrize'][0];
    if (!conf) return call.error('', { code: -1 });

    let finish = type == 'login' ? call.conn.gud.loginDays : call.conn.gud.onlineTime;
    if (finish < conf.total) return call.error('', { code: -2 });

    let db = await G.mongodb.cEvent('yibaichou').findOne({ uid: call.uid, type: 'yibaichou' });
    let recArr: number[] = db?.[type + 'Rec'] || [];
    if (recArr.includes(index)) return call.error('', { code: -3 });

    await PlayerFun.sendPrize(call, conf.prize);

    recArr.push(index);
    G.mongodb.cEvent('yibaichou').updateOne(
        { uid: call.uid, type: 'yibaichou' },
        { $set: G.mongodb.createTreeObj({ key: type + 'Rec', val: recArr }) },
        { upsert: true }
    );

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

    HongDianChange.sendChangeKey(call.uid, ['yibaichouhd'])

    call.succ({
        prize: conf.prize
    });
}