import { ApiCall } from "tsrpc";
import { Wjjl } from '../../module/collection_wjjl';
import { HeroFun } from '../../public/hero';
import { PlayerFun } from '../../public/player';
import { ReqHandle, ResHandle } from "../../shared/protocols/yongbingzhuzhan/PtlHandle";

export default async function (call: ApiCall<ReqHandle, ResHandle>) {
    let req = call.req;
    let gud = call.conn.gud;
    let helpHeros: typeof gud.helpHeros = JSON.parse(JSON.stringify(gud.helpHeros));

    if (req.state == 'shangzhen') {
        // 查询站位是否有英雄，判断上阵还是更换
        if (helpHeros.find(v => v.heroPosId == req.heroPosId)) helpHeros.removeOne(v => v.heroPosId == req.heroPosId)
        let openNum = G.gc.herocom.zhuzhan.filter((lv: any[]) => {
            if (lv.length > 2) {
                return gud[lv[0]] >= lv[1] || gud[lv[2]] >= lv[3];
            } else {
                return gud[lv[0]] >= lv[1];
            }
        }).length;
        if (helpHeros.length >= openNum) return call.error('', { code: -1 });
        if (Object.values(gud.heroPos).includes(req._id)) return call.error('', { code: -2 });

        let hero = await HeroFun.getHero(call, req._id);
        // let isUp = helpHeros.find(v => v._id == hero._id);
        // if (isUp) return call.error('', { code: -3 });
        // 上阵英雄数据
        let currentHlepHero = { _id: hero._id, jieji: hero.jieji, heroId: hero.heroId, heroPosId: req.heroPosId}
        helpHeros.push(currentHlepHero);
    } else if (req.state == 'xiexia') {
        if (!helpHeros.find(v => v._id == req._id)) return call.error('', { code: -4 });
        helpHeros.removeOne(v => v._id == req._id);
    }

    await Wjjl.setVal(call.uid, 'helpHeros', helpHeros.length);

    await PlayerFun.addAttr(call, { helpHeros: helpHeros });

    call.succ({});
}