import { ApiCall } from "tsrpc";
import { Wjjl } from '../../module/collection_wjjl';
import { EquipFun } from '../../public/equip';
import { HeroFun } from '../../public/hero';
import { PlayerFun } from '../../public/player';
import { ReqOneKeyLvUp, ResOneKeyLvUp } from "../../shared/protocols/equip/PtlOneKeyLvUp";
import { ServiceType } from '../../shared/protocols/serviceProto';
import { EquipShared } from '../../shared/public/equip';
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";
import kfjsFun from "../../public/kaifujingsai";

export default async function (call: ApiCall<ReqOneKeyLvUp, ResOneKeyLvUp, ServiceType>) {
    let hero = await HeroFun.getHero(call, call.req.heroId);

    if (!hero) return call.errorCode(-4);
    if (hero.lv < G.gc.herocom.equipOpenLv) return call.errorCode(0);
    if (Object.values(hero.equip || {}).filter(v => v != '').length < 1) return call.errorCode(-1);
    // let res = EquipShared.getQuickLvUpNeed(hero.equip, call.conn.gud.lv)
    // let {posLvUp, allNeed, log} = res
    let allNeed:atn[] = [];
    let posLvUp = {};
    // 获取装备数量
    let _equip = {}
    Object.keys(hero.equip).forEach( x => {
        if(hero.equip[x]) _equip[x] = EquipShared.getFmtEquipLvUp(x, hero.equip)
    })
    for (let i = 1; i <= 10 * Object.keys(_equip).length; i++) {
        let meet: boolean[] = [];
        // 排序，取等级最低的装备升级
        let _sortPos = Object.keys(_equip).sort((a, b) => _equip[a] - _equip[b])
        const pos = _sortPos[0]
        // const pos = _sortPos[index];
        if (!hero.equip[pos]) continue;
        let equipLv = _equip[pos]
        if (equipLv + 1 > call.conn.gud.lv * 2) continue;
        let need:atn[] = EquipShared.getEquipLvUpNeed({ lv: equipLv + 1 });
        let countNeed = PublicShared.mergePrize(allNeed.concat(need));
        if ((await PlayerFun.checkNeedIsMeet(call, countNeed, false)).isOk == false) {
            continue;
        }
        meet.push(true);
        allNeed = allNeed.concat(need);
        if (!posLvUp[pos]) posLvUp[pos] = 0;
        posLvUp[pos]++;
        _equip[pos]++;
        if (!meet.includes(true)) break;
    }
    if (allNeed.length < 1) return call.errorCode(-104);

    await PlayerFun.cutNeed(call, allNeed);

    let log = {};
    for (let pos in posLvUp) {
        let equip = EquipShared.fmtEquip(hero.equip[pos]);
        let _lv = equip.lv + posLvUp[pos];
        await EquipFun.changeEquipAttr(call, equip, { lv: _lv });
        hero.equip[pos] = EquipShared.fmtEquip(equip);

        Wjjl.setVal(call.uid, 'equip_qh_lv', _lv);

        log[pos] = _lv;
    }

    await HeroFun.changeHeroAttr(call, hero, { equip: hero.equip });
    HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd']);

    call.succ({ posLvUp: posLvUp, log: log, allNeed});

    kfjsFun.setEquipLvCount(call)
}