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 {ReqLvUp, ResLvUp} from "../../shared/protocols/equip/PtlLvUp";
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<ReqLvUp, ResLvUp, ServiceType>) {
    let equip = await EquipFun.getEquip(call, call.req.equipId);

    if (!equip) return call.error(globalThis.lng.equip_1);
    if (equip.lv >= call.conn.gud.lv * 2) return call.error(globalThis.lng.equip_2);

    let addLv = 0;
    let allNeed: atn[] = [];

    for (let i = 1; i <= call.req.upLv; i++) {
        if (equip.lv + i > call.conn.gud.lv * 2) break;
        let need = EquipShared.getEquipLvUpNeed({lv: equip.lv + i});
        let isMeet = await PlayerFun.checkNeedIsMeet(call, PublicShared.mergePrize(allNeed.concat(need)), false);
        if (!isMeet.isOk) {
            if (addLv == 0) {
                return call.error('', {code: -104, atn: isMeet.atn});
            } else {
                break;
            }
        }
        addLv++;
        allNeed = allNeed.concat(need);
    }

    await PlayerFun.cutNeed(call, allNeed);
    await EquipFun.changeEquipAttr(call, equip, {lv: equip.lv + addLv});

    Wjjl.setVal(call.uid, 'equip_qh_lv', equip.lv);

    if (equip.wearaId) {
        let hero = await HeroFun.getHero(call, equip.wearaId);
        if (hero) {
            let wearData = hero.equip || {};
            wearData[G.gc.equip[equip.equipId].type] = EquipShared.fmtEquip(equip);
            await HeroFun.changeHeroAttr(call, hero, {equip: wearData});
        }
    }

    HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd']);
    call.succ({lv: equip.lv, addlv: addLv});

    kfjsFun.setEquipLvCount(call)
}