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

export default async function (call: ApiCall<ReqWear, ResWear>) {

    if (!G.gc.peijiancom.gridCond[call.req.pos]) return call.errorCode(-1);

    let hero = await HeroFun.getHero(call, call.req.h_id);
    if (!hero) return call.errorCode(-2);
    if (call.conn.gud.lv < G.gc.peijiancom.gridCond['1'].lv) return call.errorCode(-3);
    if (Object.values(hero.peijian || {}).includes(call.req.p_id)) return call.errorCode(-4);

    let peijian = await PeijianFun.getPeijian(call, call.req.p_id);
    if (!peijian || peijian.wearId || G.gc.peijian[peijian.peijianId].isExp) return call.errorCode(-5);

    let wears = hero.peijian || {};
    let wearsData = Object.values(wears).filter(pos => !!wears[pos] && pos != call.req.pos).map(s => PeijianShared.fmt(s));
    let unlock = call.conn.gud.peijianUnlock || {};

    //是否解锁
    if (call.req.pos != '1' && G.gc.peijiancom.gridCond[call.req.pos].lv > call.conn.gud.lv && unlock[call.req.pos] == undefined) return call.errorCode(-6);

    //是否存在同类型buff配件
    if (wearsData.map(p => G.gc.peijian[p.peijianId].buff[0]).includes(G.gc.peijian[peijian.peijianId].buff[0])) return call.errorCode(-7);

    //如果该位置穿戴着其他配件 那么卸下
    if (wears[call.req.pos]) {
        await PeijianFun.changeAttr(call, PeijianShared.fmt(wears[call.req.pos]), { wearId: '' }, false);
    }

    await PeijianFun.changeAttr(call, peijian, { wearId: call.req.h_id }, false);

    wears[call.req.pos] = PeijianShared.fmt(peijian);

    await HeroFun.changeHeroAttr(call, hero, { peijian: wears });

    call.succ({});
}