import { ApiCall } from "tsrpc";
import { DxltFun } from '../../public/dxlt';
import { PlayerFun } from '../../public/player';
import { ResOpen } from '../../shared/protocols/dixialeitai/PtlOpen';
import { ReqUseItem, ResUseItem } from "../../shared/protocols/dixialeitai/PtlUseItem";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqUseItem, ResUseItem>) {
    let args = call.req;
    let change: Partial<ResOpen> = {};
    let data = await DxltFun.getData(call);
    let item = data.item;
    let conf = G.gc.dxlt_com.fightPrize.item[args.id];
    let prize: atn[] = [];

    if (!item[args.id]) return call.error(globalThis.lng.dixialeitai_11);
    if (args.id == '1' && !data.heros[args.pos]) return call.error(globalThis.lng.dixialeitai_5);
    if (args.id == '2' && data.killBoss >= G.gc.dxlt_com.dayFightLayer) return call.error(globalThis.lng.dixialeitai_2);
    if (args.id == '2' && G.gc.dxlt_layer[data.curLayer].type != 1) return call.error(globalThis.lng.dixialeitai_12);
    if (args.id == '2' && data.over) return call.error(globalThis.lng.dixialeitai_12);

    item[args.id]--;
    switch (args.id) {
        case '1':
            data.heros[args.pos].attr.hp += data.heros[args.pos].attr.maxHp * conf.val;
            if (data.heros[args.pos].attr.hp > data.heros[args.pos].attr.maxHp) data.heros[args.pos].attr.hp = data.heros[args.pos].attr.maxHp;
            change.heros = data.heros;
            break;
        case '2':
            DxltFun.saodan(data, 1);
            change.over = true;
            change.buff = data.buff;

            if (data.saodang.mibaoNum) {
                change.mibao += data.saodang.mibaoNum;
            }

            if (G.gc.dxlt_layer[data.curLayer].isBoss) {
                change.killBoss = (data.killBoss || 0) + 1;
            }

            prize.push(...G.gc.dxlt_layer[data.curLayer].price);

            if (data.saodang.prize) {
                prize.push(...data.saodang.prize);
            }

            if (data.saodang.shop) {
                DxltFun.changeShop(data, change);
            }

            DxltFun.passLayerChange(data, change);
            break;
        case '3':
            DxltFun.changeShop(data, change);
            break;
    }
    change.item = data.item;

    prize.length > 0 && await PlayerFun.sendPrize(call, prize);
    await DxltFun.changeData(call, change);

    HongDianChange.sendChangeKey(call.uid, ['dxlthd']);

    call.succ({
        change: change,
        fightPrize: data.saodang || {},
        prize: prize
    });
}