import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqRecPrize, ResRecPrize } from "../../../shared/protocols/event/zhanling/PtlRecPrize";
import { PublicShared } from '../../../shared/public/public';
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqRecPrize, ResRecPrize>) {
    if (call.req.recIndexs.length < 1) return call.error(globalThis.lng.pata_getprize_1);

    let conf = G.gc.zhanling.prize;
    let isErr = conf.map((c, i) => i).intersection(call.req.recIndexs).length != call.req.recIndexs.length;

    if (isErr) return call.error(globalThis.lng.pata_getprize_1);

    let data = await G.mongodb.cEvent('zhanling').findOne({ uid: call.uid, type: 'zhanling' });
    let rec = data.rec;
    let val = data.lv;
    let isPay = data.isPay;
    let prize: atn[] = [];

    for (let index of call.req.recIndexs) {
        if (val < conf[index].lv) return call.error(globalThis.lng.event_jijin_1);

        let hasPt = conf[index].pt.length > 0;
        let hasTq = conf[index].tq.length > 0;
        let getPt = !hasPt || rec[index]?.pt == true;
        let getTq = !hasTq || rec[index]?.tq == true;

        if (getPt && !getTq && !isPay) return call.error(globalThis.lng.event_jijin_2);
        if (getPt && getTq) return call.error(globalThis.lng.event_jijin_3);

        if (!rec[index]) rec[index] = { pt: false, tq: false };

        if (hasPt && !getPt) {
            prize.push(...conf[index].pt);
            rec[index].pt = true;
        }

        if (hasTq && !getTq && isPay) {
            prize.push(...conf[index].tq);
            rec[index].tq = true;
        }
    }

    prize = PublicShared.mergePrize(prize);
    await PlayerFun.sendPrize(call, prize);

    G.mongodb.cEvent('zhanling').updateOne(
        { uid: call.uid, type: 'zhanling' },
        { $set: { rec: rec } }
    );

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

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