import { ApiCall } from "tsrpc";
import { CollectionShiwu } from '../../module/collection_shiwu';
import { HeroFun } from '../../public/hero';
import { PlayerFun } from '../../public/player';
import { ShiwuFun } from '../../public/shiwu';
import { ReqLvUp, ResLvUp } from "../../shared/protocols/shiwu/PtlLvUp";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqLvUp, ResLvUp>) {
    let _id = call.req._id;
    let _ids = call.req._ids;

    if (_ids.length > 5 || _ids.length == 0) return call.errorCode(0);
    if (_ids.intersection([_id]).length > 0) return call.errorCode(-1);

    let shiwu = await ShiwuFun.getShiwu(call, _id);
    if (!checkIsSpeed(shiwu) || !shiwu.wearId) return call.errorCode(-2);
    if (!checkIsCanUp(shiwu)) return call.errorCode(-3);

    let hero = await HeroFun.getHero(call, shiwu.wearId);
    let next = getNextShiwu(shiwu);
    if (hero.lv < next.lv) return call.errorCode(-6);


    let shiwus = await ShiwuFun.getShiwu(call, _ids);
    if (shiwus.length != _ids.length) return call.errorCode(-4);
    if (shiwus.filter(s => !!s.wearId || s.shiwuId != shiwu.shiwuId).length > 0) return call.errorCode(-5);

    let isSucc = PublicShared.randomNum(1, 100) <= _ids.length * 20;
    if (isSucc) {
        shiwu.shiwuId = next.id.toString();
        shiwu.jichu = ShiwuFun.randomJichu(shiwu);
        ShiwuFun.randomFujiaAll(shiwu);
        await ShiwuFun.changeShiwuAttr(call, shiwu, { shiwuId: shiwu.shiwuId, jichu: shiwu.jichu, fujia: shiwu.fujia });
    }

    await PlayerFun.cutShiwu(call, _ids);

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

function checkIsSpeed(shiwu: CollectionShiwu) {
    let conf = G.gc.shiwu[shiwu.shiwuId];
    return Object.keys(conf.buff)[0] == 'speed';
}

function checkIsCanUp(shiwu: CollectionShiwu) {
    let ss = Object.values(G.gc.shiwu).filter(s => Object.keys(s.buff)[0] == 'speed').sort((a, b) => a.lv - b.lv);
    return ss.findIndex(s => s.id.toString() == shiwu.shiwuId) != ss.length - 1;
}

function getNextShiwu(shiwu: CollectionShiwu) {
    let ss = Object.values(G.gc.shiwu).filter(s => Object.keys(s.buff)[0] == 'speed').sort((a, b) => a.lv - b.lv);
    let index = ss.findIndex(s => s.id.toString() == shiwu.shiwuId);
    return ss[index + 1];
}