import { ApiCall } from "tsrpc";
import { PeijianFun } from '../../public/peijian';
import { PlayerFun } from '../../public/player';
import { ReqReset, ResReset } from "../../shared/protocols/peijian/PtlReset";

export default async function (call: ApiCall<ReqReset, ResReset>) {

    let peijians = (await PeijianFun.getPeijian(call, call.req.p_ids)).filter(peijian => !peijian.wearId && (peijian.lv > 1 || G.gc.peijian[peijian.peijianId].colour == 5) && !G.gc.peijian[peijian.peijianId].isExp);
    if (peijians.length < call.req.p_ids.length) return call.errorCode(-1);

    let need = G.gc.peijiancom.resetNeed.map(atn => { return { ...atn, n: atn.n * peijians.length }; });
    await PlayerFun.checkNeedIsMeet(call, need);
    await PlayerFun.cutNeed(call, need);

    let prize: atn[] = [];
    let allConfs = Object.values(G.gc.peijian);
    for (let peijian of peijians) {
        let conf = G.gc.peijian[peijian.peijianId];

        if (peijian.lv > 1) {
            let needs = Object.values(G.gc.peijian_lv[conf.colour]).filter(c => c.lv <= peijian.lv).map(c => c.need).reduce((a, b) => a.concat(b));
            prize.push(...needs);
        }

        if (conf.colour == 5) {
            let jjConf = allConfs.find(c => c.jjid.toString() == peijian.peijianId);
            prize.push(...G.gc.peijiancom.jinjieNeed);

            if (peijian.jinglian > 0) {
                prize.push(...Object.values(G.gc.peijian_jl).filter(c => c.lv <= peijian.jinglian).map(c => [].concat(c.need, { a: 'peijian', t: jjConf.id, n: c.peijianNum })).reduce((a, b) => a.concat(b)));
            }

            await PeijianFun.changeAttr(call, peijian, { lv: 1, jinglian: 0, peijianId: jjConf.id.toString() });
        } else {
            await PeijianFun.changeAttr(call, peijian, { lv: 1, jinglian: 0 });
        }
    }

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

    call.succ({ prize: prize });
}