import { ApiCall } from "tsrpc";
import { HeroFun } from '../../public/hero';
import { PeijianFun } from '../../public/peijian';
import { PlayerFun } from '../../public/player';
import { PeiJian } from '../../shared/protocols/peijian/PtlGetList';
import { ReqOneKeyLvUp, ResOneKeyLvUp } from "../../shared/protocols/peijian/PtlOneKeyLvUp";
import { prizeType } from '../../shared/protocols/type';
import { PeijianShared } from '../../shared/public/peijian';
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqOneKeyLvUp, ResOneKeyLvUp>) {

    let hero = await HeroFun.getHero(call, call.req.heroId);
    if (!hero) return call.errorCode(-1);

    if (!hero.peijian) return call.errorCode(-2);

    let posObj: k_v<Omit<PeiJian, "wearId">> = {};
    let need: prizeType[] = [];

    Object.keys(hero.peijian).forEach( x => {
        if(hero.peijian[x]) posObj[x] = PeijianShared.fmt(hero.peijian[x])
    })
    let addObj = Object.fromEntries(Object.keys(posObj).map(p => [ p, { lv: 0, can: true, peijianId: posObj[p].peijianId }]));
    let _sjNum = 0    // 任务计数，升级用
    for (let addLv = 1; addLv <= 20 * Object.keys(posObj).length; addLv++) {
        if (Object.values(addObj).filter(a => a.can == false).length == Object.keys(posObj).length) break;
        // 排序获取级最低的装备
        let _sortPos = Object.keys(posObj).sort((a, b) => posObj[a].lv - posObj[b].lv)
        let pos = _sortPos[0]
        let peijian = posObj[pos]
        if (!addObj[pos].can) continue;
        let nextLv = peijian.lv + 1;
        // 下一级需要的资源
        let lvConf = G.gc.peijian_lv[G.gc.peijian[peijian.peijianId].colour][nextLv];

        if (!lvConf || (await PlayerFun.checkNeedIsMeet(call, PublicShared.mergePrize([].concat(need, lvConf.need)), false)).isOk == false) {
            addObj[pos].can = false;
            continue;
        }
        need.push(...lvConf.need);
        addObj[pos].lv++;
        _sjNum++
        posObj[pos].lv++
    }

    if (need.length < 1) return call.errorCode(-2);

    await PlayerFun.cutNeed(call, need);

    for (let [pos, obj] of Object.entries(addObj)) {
        if (!obj.lv) continue;
        let pj = posObj[pos];
        await PeijianFun.changeAttr(call, pj, { lv: pj.lv }, false);
    }

    await HeroFun.changeHeroAttr(call, hero, { peijian: Object.fromEntries(Object.keys(posObj).map(pos => [pos, PeijianShared.fmt(posObj[pos])])) });
    let posLvUp = Object.keys(addObj).map(x => addObj[x].lv)
    let allNeed =  PublicShared.mergePrize(need)
    call.succ({ sjnum: _sjNum, posLvUp, allNeed});
}