import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { Rank } from '../../../public/rank/rank';
import { ReqLottery, ResLottery } from "../../../shared/protocols/event/xianshizhaomu/PtlLottery";
import { prizeType } from '../../../shared/protocols/type';
import { PublicShared } from '../../../shared/public/public';
import { xszmdb } from './ApiOpen';

export default async function (call: ApiCall<ReqLottery, ResLottery>) {
    let drop: number[] = G.gc.xianshizhaomu[call.req.type + 'Drop'];
    let need: prizeType[] = G.gc.xianshizhaomu[call.req.type + 'Need'];

    await PlayerFun.checkNeedIsMeet(call, need);

    let prize = G.gc.xianshizhaomu[call.req.type + 'Prize'];
    let lotteryPrize: prizeType[] = [];
    let db = await xszmdb().findOne({ uid: call.uid, type: 'xianshizhaomu' });
    if (call.req.type == 'one' && db?.recordNum % G.gc.xianshizhaomu.oneReplace.num == 0) {
        drop = G.gc.xianshizhaomu.oneReplace.drop;
    }

    drop.sort(() => Math.random() - .5);
    for (let id of drop) {
        lotteryPrize.push(...PublicShared.randomDropGroup(id));
    }

    await PlayerFun.cutNeed(call, need);
    await PlayerFun.sendPrize(call, lotteryPrize.concat(prize));

    xszmdb().updateOne(
        { uid: call.uid, type: 'xianshizhaomu' },
        { $inc: { recordNum: drop.length, recordOneNum: drop.length > 1 ? 0 : 1 } },
        { upsert: true }
    );

    Rank.list.xszm.addNew({
        ...await call.conn.getDefaultFightData(),
        valArr: [(db?.recordNum || 0) + drop.length]
    });

    call.succ({
        prize: prize,
        lotteryPrize: lotteryPrize
    });
}