import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { ReqDeal, ResDeal } from "../../shared/protocols/peijiancangku/PtlDeal";
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqDeal, ResDeal>) {
    let db = await G.mongodb.cPlayerInfo('peijiancangku').findOne({ uid: call.uid, type: 'peijiancangku' });
    let index = db?.index || 0;

    let need: atn[] = [];
    let indexs: number[] = [];
    for (let n = 0; n < call.req.num; n++) {

        let isMeet = await PlayerFun.checkNeedIsMeet(call, [].concat(need, G.gc.peijiancangku.warehouse[index].need), false);
        if (!isMeet.isOk) {
            if (indexs.length == 1) return call.error('', { code: -104, atn: isMeet.atn });
            else break;
        }
        indexs.push(index);
        need.push(...G.gc.peijiancangku.warehouse[index].need);

        let next = G.gc.peijiancangku.warehouse[index + 1];
        if (next) {
            let isRandom = PublicShared.randomNum(1, 100) <= next.p;
            if (isRandom) {
                index = index + 1;
            } else {
                index = 0;
            }
        } else {
            index = 0;
        }
    }

    await PlayerFun.cutNeed(call, need);

    let prize = indexs.map(i => {
        let conf = G.gc.peijiancangku.warehouse[i];
        let drop = PublicShared.randomDropAny(conf.drop);
        return drop.dlz.map(dlz => PublicShared.randomDropGroup(dlz)).reduce((a, b) => a.concat(b));
    }).reduce((a, b) => a.concat(b));

    let sendPrize = prize.map(p => {
        if (p.a == 'peijian' && G.gc.peijian[p.t].conversion.length > 0) return G.gc.peijian[p.t].conversion[0];
        return p;
    });

    await PlayerFun.sendPrize(call, sendPrize);

    G.mongodb.cPlayerInfo('peijiancangku').updateOne(
        { uid: call.uid, type: 'peijiancangku' },
        { $set: { index: index } },
        { upsert: true }
    );

    HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd'])

    call.succ({ prize: prize, index: index, indexs: indexs });
}