import { ApiCall } from "tsrpc";
import { ChatFun } from '../../public/chat';
import { PeijianFun } from '../../public/peijian';
import { PlayerFun } from '../../public/player';
import { ReqJinJie, ResJinJie } from "../../shared/protocols/peijian/PtlJinJie";

export default async function (call: ApiCall<ReqJinJie, ResJinJie>) {

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

    let conf = G.gc.peijian[peijian.peijianId];
    if (!conf.jjid) return call.errorCode(-2);

    if (peijian.lv < G.gc.peijiancom.jinjieLv) return call.errorCode(-3);

    await PlayerFun.checkNeedIsMeet(call, G.gc.peijiancom.jinjieNeed);
    await PlayerFun.cutNeed(call, G.gc.peijiancom.jinjieNeed);

    let newLv = 2;
    let useExp = Object.values(G.gc.peijian_lv[conf.colour]).filter(c => c.lv <= peijian.lv).map(c => c.need[0].n).reduce((a, b) => a + b);
    let countExp = 0;
    let newLvConfs = Object.values(G.gc.peijian_lv[G.gc.peijian[conf.jjid].colour]);

    for (let c of newLvConfs) {
        countExp += c.need[0].n;
        if (useExp < countExp) break;
        if (G.gc.peijian_lv[G.gc.peijian[conf.jjid].colour][newLv + 1]) newLv++;
    }

    await PeijianFun.changeAttr(call, peijian, { peijianId: conf.jjid.toString(), lv: newLv });

    ChatFun.newMsg({
        type: 'local',
        msg: G.gc.pmd.jinjie_peijian,
        time: G.time,
        sender: 'system',
        otherData: {
            pmd: true,
            args: [call.conn.gud.name, conf.name]
        }
    });

    call.succ({});
}