import { ApiCall } from "tsrpc";
import { ReqExchange, ResExchange } from "../../shared/protocols/weixiuchang/PtlExchange";
import { weixiuchangType } from "../../shared/protocols/weixiuchang/type";
import { FunWeiXiuChang } from "../../public/weixiuchang";
import { PlayerFun } from "../../public/player";
import { HongDianChange } from "../hongdian/fun";

// 蓝图兑换零件
export default async function (call: ApiCall<ReqExchange, ResExchange>) {
    // 获取参数
    let num = call.req.num || 0;
    let index = call.req.index;
    // 验证参数
    if(num <= 0) return call.error(lng.weixiuchang_5); // 未提供足够的蓝图
    if(!(index >= 0 && index < 5)) return call.error(lng.weixiuchang_6); // 零件错误
    // 获取用户数据
    let data:weixiuchangType = await FunWeiXiuChang.getFindOne(call);
    // 获取相关配置
    let conf = JSON.parse(JSON.stringify(G.gc.weixiuchang_zz))
    let needConf = conf[data.star].need;
    let exchangeConf = conf[data.star].exchange;
    // 计算消耗蓝图数量
    let exchangeInfo:atn = exchangeConf[index];
    exchangeInfo.n *= num;
    let needArr:atn[] = [exchangeInfo];
    // 计算获取的零件
    let itemInfo:atn = needConf[index];
    itemInfo.n = num;
    let prizeArr:atn[] = [itemInfo];
    // 验证背包蓝图是否足够
    await PlayerFun.checkNeedIsMeet(call, needArr);
    // 道具写入数据库
    await PlayerFun.cutNeed(call, needArr);
    await PlayerFun.addItem(call, prizeArr);
    HongDianChange.sendChangeKey(call.uid, ['weixiuchang']);
    call.succ({ prizeArr, needArr });
}