import { ApiCall } from "tsrpc";
import { ReqUpLv, ResUpLv } from "../../shared/protocols/weixiuchang/PtlUpLv";
import { weixiuchangType } from "../../shared/protocols/weixiuchang/type";
import { FunWeiXiuChang } from "../../public/weixiuchang";
import { PlayerFun } from "../../public/player";
import { HongDianChange } from "../hongdian/fun";

/**
 * 零件升级
 * @param index 指定零件索引0-4，不传升级全部
 */
export default async function (call: ApiCall<ReqUpLv, ResUpLv>) {
    // 获取参数
    let index = call.req.index;
    let conf = JSON.parse(JSON.stringify(G.gc.weixiuchang_zz)); // 避免深拷贝造成变量污染
    // 查询个人数据
    let data:weixiuchangType = await FunWeiXiuChang.getFindOne(call);
    let needConf = conf[data.star].need; // 获取相关星级的need配置
    // 零件升级
    let needArr:atn[] = []
    for(let i = 0; i < needConf.length; i++) {
        if(index !== undefined && index != i) continue 
        if(data.schedule[i] >= needConf[i].n) continue;
        let item = await PlayerFun.getAtnNum(call, needConf[i]); // 拥有指定物品数量
        if(!item) continue;
        let needItemNum:number = (needConf[i].n - data.schedule[i]) >= item ? item : needConf[i].n - data.schedule[i];
        let need:atn = {
            a: needConf[i].a,
            t: needConf[i].t,
            n: needItemNum
        };
        needArr.push(need); // 总消耗插入
        data.schedule[i] += needItemNum; // data数据变更
    }
    if(needArr.length > 0) {
        await PlayerFun.cutNeed(call, needArr); // 执行消耗
        await FunWeiXiuChang.updateOne(call, data); // 修改数据库
        HongDianChange.sendChangeKey(call.uid, ['weixiuchang']);
        call.succ({ schedule: data.schedule, star: data.star, needArr })
    } else {
        // 没有任何消耗，未升星
        call.error(lng.weixiuchang_3)
    }
}