import { ApiCall } from "tsrpc";
import { HeroFun } from '../../public/hero';
import { ShiwuFun } from '../../public/shiwu';
import { ReqWear, ResWear } from "../../shared/protocols/shiwu/PtlWear";

export default async function (call: ApiCall<ReqWear, ResWear>) {
    if (!['1', '2'].includes(call.req.pos)) return call.error(globalThis.lng.shiwu_6);

    let hero = await HeroFun.getHero(call, call.req.heroId);
    if (!hero) return call.error(globalThis.lng.shiwu_7);
    if (hero.lv < G.gc.herocom.equipOpenLv) return call.error(`英雄${G.gc.herocom.equipOpenLv}开启`);

    let shiwu = await ShiwuFun.getShiwu(call, call.req.shiwuId);
    if (!shiwu) return call.error(globalThis.lng.shiwu_3);
    if (G.gc.shiwu[shiwu.shiwuId].lv > call.conn.gud.lv) return call.error(globalThis.lng.shiwu_8);

    let wearShiwu = hero.shiwu || {};
    if (Object.values(wearShiwu).filter(sw => sw._id == shiwu._id).length > 0) return call.error(globalThis.lng.shiwu_9);

    let oldShiwu = wearShiwu[call.req.pos];
    if (oldShiwu) {
        await ShiwuFun.changeShiwuAttr(call, oldShiwu, { wearId: '' }, false);
    }

    wearShiwu[call.req.pos] = ShiwuFun.fmtHeroShiwu(shiwu);

    await HeroFun.changeHeroAttr(call, hero, { shiwu: wearShiwu });
    await ShiwuFun.changeShiwuAttr(call, shiwu, { wearId: hero._id });

    call.succ({});
}