import { ApiCall } from "tsrpc";
import { PeijianFun } from '../../public/peijian';
import { PlayerFun } from '../../public/player';
import { ReqLvUp, ResLvUp } from "../../shared/protocols/peijian/PtlLvUp";
import { prizeType } from '../../shared/protocols/type';
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqLvUp, ResLvUp>) {

    let peijian = await PeijianFun.getPeijian(call, call.req.p_id);
    if (!peijian) return call.errorCode(-1);

    let conf = G.gc.peijian[peijian.peijianId];
    if (!G.gc.peijian_lv[conf.colour][peijian.lv + 1] || conf.isExp) return call.errorCode(-2);

    let addLv = 0;
    let need: prizeType[] = [];
    for (let lv = 1; lv <= call.req.num; lv++) {
        let lvConf = G.gc.peijian_lv[conf.colour][peijian.lv + lv];
        if (!lvConf) break;

        let isMeet = await PlayerFun.checkNeedIsMeet(call, PublicShared.mergePrize(need.concat(lvConf.need)), false);
        if (!isMeet.isOk) {
            if (lv == 1) {
                return call.error('', { code: -104, atn: isMeet.atn });
            } else {
                break;
            }
        }

        addLv++;
        need = need.concat(lvConf.need);
    }

    await PlayerFun.cutNeed(call, need);
    await PeijianFun.changeAttr(call, peijian, { lv: peijian.lv + addLv });

    call.succ({});
}