import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { TanXianFun } from '../../public/tanxian';
import { ReqReceive, ResReceive } from "../../shared/protocols/tanxian/PtlReceive";
import { PublicShared } from '../../shared/public/public';

// 一键领取通关奖励
export default async function (call: ApiCall<ReqReceive, ResReceive>) {
    // 玩家数据 receivePrize 记录玩家领取进度
    const data = await TanXianFun.getData(call, false);
    let { receiveLastId, receivePrizeConfId } = TanXianFun.getLastMapId(data.receivePrizeConfId)// 获取当前的领取进度
    // 配置表
    const conf = G.gc.tanxian_tgjl;
    // 当前通关进度
    let currentMapId = call.conn.gud.mapId || 0
    let lastMapId = ~~receiveLastId > 0 ? conf[receiveLastId].mapId : 0
    // 计算领取奖励
    let prizeArr = []
    for(let key = ~~receiveLastId + 1; key <= Object.keys(conf).length; key++) {
        // 验证
        if(conf[key].mapId > currentMapId || !currentMapId) break;
        if(conf[key].id < ~~receiveLastId || receivePrizeConfId.indexOf(String(key)) != -1 ) continue;
        if(conf[key].mapId < lastMapId || data.receivePrize.indexOf(String(conf[key].mapId)) != -1 ) continue;
        prizeArr.push(...conf[key].prize); // 插入领取奖励
        data.receivePrize.push(String(conf[key].mapId)); // 插入领取mapId记录
        receivePrizeConfId.push(String(key)); // 插入领取id记录
        receiveLastId = String(key);
    }
    prizeArr = await PublicShared.mergePrize(prizeArr); // 合并奖励
    await PlayerFun.sendPrize(call, prizeArr); // 发送奖励
    await TanXianFun.changeData(call, { receivePrize: data.receivePrize, receivePrizeConfId}); // 修改领取记录
    if(prizeArr.length > 0) {
        call.succ({
            prize: prizeArr,
            receiveLastId: receiveLastId
        });
    } else {
        call.error(lng.tanxian_7)
    }
}