import { ApiCall } from "tsrpc";
import { PeijianFun } from '../../public/peijian';
import { PlayerFun } from '../../public/player';
import { ReqJingLian, ResJingLian } from "../../shared/protocols/peijian/PtlJingLian";

export default async function (call: ApiCall<ReqJingLian, ResJingLian>) {

    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.peijiancom.jinglianColour.includes(conf.colour)) return call.errorCode(-2);

    let jlConf = G.gc.peijian_jl[peijian.jinglian + 1];
    if (!jlConf) return call.errorCode(-3);
    if (peijian.lv < jlConf.needLv) return call.errorCode(-4);

    await PlayerFun.checkNeedIsMeet(call, jlConf.need);

    if (jlConf.peijianNum) {
        let t = Object.values(G.gc.peijian).find(p => p.jjid.toString() == peijian.peijianId);
        if (t) {
            let filters = Object.values(await G.redis.get('peijian', call.uid)).filter(p => p.peijianId == t.id.toString() && !p.wearId && p.lv <= 1);
            if (filters.length < jlConf.peijianNum) return call.errorCode(-5);
            await PlayerFun.cutPeijian(call, filters.slice(0, jlConf.peijianNum).map(p => p._id));
        } else {
            return call.errorCode(-6);
        }
    }

    await PlayerFun.cutNeed(call, jlConf.need);
    await PeijianFun.changeAttr(call, peijian, { jinglian: peijian.jinglian + 1 });

    call.succ({});
}