import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqLottery, ResLottery } from "../../../shared/protocols/event/niudanji/PtlLottery";
import { PublicShared } from '../../../shared/public/public';
import { pay2num } from './ApiOpen';
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqLottery, ResLottery>) {
    let hasNum = pay2num(call.conn.gud);
    if (hasNum < 1) return call.error('', { code: -1 });

    let db = await G.mongodb.cEvent('niudanji').findOne({ uid: call.uid, type: 'niudanji' });
    let useNum = db?.useNum || 0;

    if (useNum >= hasNum) return call.error('', { code: -1 });

    let random = (useNum != 0 && useNum % G.gc.niudanji.num2lottery == 0) ? G.gc.niudanji.lottery[0] : PublicShared.randomDropAny(G.gc.niudanji.lottery);
    let prize = random.prize.random();

    if (random.pmd) {
        G.mongodb.collection('any').updateOne({ type: 'niudanlog' }, { $push: { data: { $each: [{ name: call.conn.gud.name, item: prize }], $slice: -30 } } }, { upsert: true });
    }

    await PlayerFun.sendPrize(call, [prize]);

    G.mongodb.cEvent('niudanji').updateOne(
        { uid: call.uid, type: 'niudanji' },
        { $inc: { useNum: 1 } },
        { upsert: true }
    );
    HongDianChange.sendChangeKey(call.uid, ['heishihd'])
    call.succ({
        prize: [prize]
    });
}