import { ApiCall } from "tsrpc";
import { ReqDecompose, ResDecompose } from "../../shared/protocols/weixiuchang/PtlDecompose";
import { weixiuchangType } from "../../shared/protocols/weixiuchang/type";
import { FunWeiXiuChang } from "../../public/weixiuchang";
import { PlayerFun } from "../../public/player";
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";


/**
 * 分解零部件
 * @param exchange true: 分解，false: 预览
 */
export default async function (call: ApiCall<ReqDecompose, ResDecompose>) {
    // 获取参数
    let exchange = call.req.exchange || false; // false为预览。
    // 避免深拷贝造成变量污染
    let conf = JSON.parse(JSON.stringify(G.gc.weixiuchang_zz))
    let confItem = JSON.parse(JSON.stringify(G.gc.weixiuchang_item))
    // 获取用户数据
    let data:weixiuchangType = await FunWeiXiuChang.getFindOne(call)
    // 计算配置内需消耗的道具类别与拥有数量, 计算可兑换的蓝图
    let needArr:atn[] = [];
    let prizeArr:atn[] = []
    let itemArr = []
    let itemStage = 0;
    for(let i in conf) {
        if(conf[i].stage >= data.stage || !data.stage) break;
        if(conf[i].stage == itemStage) continue;
        itemStage = conf[i].stage
        for(let k in conf[i].need) {
            // 验证是否已处理过该道具
            if(itemArr.indexOf(conf[i].need[k].t) != -1) continue; 
            itemArr.push(conf[i].need[k].t)
            // 查询道具数量
            let itemNum = await PlayerFun.getAtnNum(call, conf[i].need[k]);
            conf[i].need[k].n = itemNum
            if(conf[i].need[k].n > 0) {
                needArr.push(conf[i].need[k])
                // 计算兑换的蓝图数量
                let exchangeInfo = confItem[conf[i].need[k].t].fenjie
                exchangeInfo.forEach(x => {
                    x.n *= itemNum
                    prizeArr.push(x)
                })
            }
        }
    }
    if(prizeArr.length > 0) {
        // 合并蓝图奖励
        prizeArr = await PublicShared.mergePrize(prizeArr);
        if(exchange) {
            await PlayerFun.cutNeed(call, needArr); // 消耗的零件
            await PlayerFun.addItem(call, prizeArr); // 获取的蓝图
        }
        HongDianChange.sendChangeKey(call.uid, ['weixiuchang']);

        call.succ({prizeArr, needArr})
    } else {
        call.error(lng.weixiuchang_7); // 没有可分解的零件
    }
}