import { ApiCall } from "tsrpc";
import { HeroFun } from '../../public/hero';
import { PlayerFun } from '../../public/player';
import { ReqWeaponUp, ResWeaponUp } from "../../shared/protocols/hero/PtlWeaponUp";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqWeaponUp, ResWeaponUp>) {
    let hero = await HeroFun.getHero(call, call.req.id)

    let heroConf = G.gc.hero[hero?.heroId];

    if (!hero) return call.error(globalThis.lng.hero_1);
    if (!heroConf.zhuanshu) return call.error(globalThis.lng.hero_16);
    if (hero.lv < G.gc.herocom.zswqOpenLv) return call.error(`英雄达到${G.gc.herocom.zswqOpenLv}级开启`);

    let weapon = Object.assign({}, hero.weapon || { jieji: 0, star: 0, starProbability: 0 });
    let weaponConf = G.gc.zhuanshu[heroConf.zhuanshu];

    if (call.req.type == 'jieji') {
        if (!weaponConf[weapon.jieji + 1]) return call.error(globalThis.lng.hero_17);
        if (weapon.star < Object.values(weaponConf[weapon.jieji]).slice(-1)[0].star) return call.error(globalThis.lng.hero_18);

        let need = weaponConf[weapon.jieji + 1][0].need;
        await PlayerFun.checkNeedIsMeet(call, need);

        weapon.jieji += 1;
        weapon.star = 0;
        await PlayerFun.cutNeed(call, need);
        await HeroFun.changeHeroAttr(call, hero, {
            weapon: weapon
        });

        call.succ({});
    } else if (call.req.type == 'star') {
        if (!weaponConf[weapon.jieji][weapon.star + 1]) return call.error(globalThis.lng.hero_19);

        let need = weaponConf[weapon.jieji][weapon.star + 1].need;
        await PlayerFun.checkNeedIsMeet(call, need);

        await PlayerFun.cutNeed(call, need);

        let starFail: boolean;
        let randomNum = PublicShared.randomNum(1, 100);
        let vipAdd = 0;
        if (G.gc.herocom.zswqVip[call.conn.gud.vip] == undefined) vipAdd += G.gc.herocom.zswqVip.last();
        else vipAdd += G.gc.herocom.zswqVip[call.conn.gud.vip];
        let probability = (weapon.starProbability + vipAdd + weaponConf[weapon.jieji][weapon.star + 1].probability) * 100;
        if (randomNum <= probability) {
            weapon.star += 1;
            weapon.starProbability = 0;
            starFail = false;
        } else {
            weapon.starProbability += 0.01;
            starFail = true;
        }
        await HeroFun.changeHeroAttr(call, hero, {
            weapon: weapon
        });

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