import {ApiCall} from "tsrpc";
import {EquipFun} from '../../public/equip';
import {HeroFun} from '../../public/hero';
import {ReqOneKeyWear, ResOneKeyWear} from "../../shared/protocols/equip/PtlOneKeyWear";
import {ServiceType} from '../../shared/protocols/serviceProto';
import {EquipShared} from '../../shared/public/equip';
import kfjsFun from "../../public/kaifujingsai";

export default async function (call: ApiCall<ReqOneKeyWear, ResOneKeyWear, ServiceType>) {
    let hero = await HeroFun.getHero(call, call.req.heroId);

    if (!hero) return call.error(globalThis.lng.equip_3);
    if (hero.lv < G.gc.herocom.equipOpenLv) return call.errorCode(-1)

    let wearNum = 0;
    let wearData = hero.equip || {};
    let equipList = await EquipFun.getAllEquips(call);
    let allEquip = Object.values(equipList);
    let heroIds = Object.values(call.conn.gud.heroPos).filter(i => !!i)


    for (let pos = 1; pos < 5; pos++) {
        let posEquip = wearData[pos] || '';
        let curEquip = EquipShared.fmtEquip(posEquip);
        let curEquipConf = G.gc.equip[curEquip.equipId];
        let wearEquip = allEquip.filter(e => {
            let conf = G.gc.equip[e.equipId];
            if (!posEquip) {
                return (!e.wearaId || !heroIds.includes(e.wearaId)) && conf.type == pos;
            } else {
                return (!e.wearaId || !heroIds.includes(e.wearaId)) && conf.type == pos && (
                    conf.colour > curEquipConf.colour
                    || (conf.colour >= curEquipConf.colour && e.star > curEquip.star)
                    || (conf.colour >= curEquipConf.colour && e.star >= curEquip.star && e.lv > curEquip.lv));
            }
        }).sort((a, b) => {
            if (G.gc.equip[a.equipId].colour != G.gc.equip[b.equipId].colour) {
                return G.gc.equip[b.equipId].colour - G.gc.equip[a.equipId].colour;
            } else if (a.lv != b.lv) {
                return b.lv - a.lv;
            } else {
                return b.star - a.star;
            }
        })[0];
        if (!wearEquip) continue;
        if (posEquip) {
            await EquipFun.changeEquipAttr(call, equipList[G.formatRedisKey(EquipShared.fmtEquip(posEquip)._id)], {wearaId: ''}, false);
        }
        await EquipFun.changeEquipAttr(call, wearEquip, {wearaId: hero._id});
        wearNum++;
        wearData[pos] = EquipShared.fmtEquip(wearEquip);
    }

    if (wearNum == 0) {
        return call.errorCode(-2)
    }

    await HeroFun.changeHeroAttr(call, hero, {equip: wearData});
    call.succ({});

    kfjsFun.setEquipLvCount(call)

}