import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { TanXianFun } from '../../public/tanxian';
import { TeQuanFun } from "../../public/tequan";
import { ReqFastGuaJi, ResFastGuaJi } from "../../shared/protocols/tanxian/PtlFastGuaJi";
import { TanXianShared } from '../../shared/public/tanxian';
import { event_dldh_addPrize } from '../event/diaoluoduihuan/ApiOpen';
import { HongDianChange } from "../hongdian/fun";
import { getEventPrize } from './ApiEvent';

export default async function (call: ApiCall<ReqFastGuaJi, ResFastGuaJi>) {

    const data = await TanXianFun.getData(call);
    const maxNum = await TanXianFun.getFastGuaJiNum(call);
    if (data.useFastGuaJiNum >= maxNum) return call.error(globalThis.lng.tanxian_1);
    // 特权免费次数
    let tqFree = await TeQuanFun.getTxFreeNum(call)
    let freeNum = G.gc.tanxian_com.fastGuaJiFreeNum + tqFree

    // let notFree = data.useFastGuaJiNum >= freeNum && ((data?.zztqfreeNum || 0) >= tqFree && tqFree) && (data?.useFreeGuaJiNum || 0) <= freeNum 
    let notFree = (data?.useFreeGuaJiNum || 0) >= freeNum 
    if (notFree) {
        let num = G.gc.tanxian_com.fastGuaJiNeed[data.useFastGuaJiNum - freeNum ] || 0;
        let need = [{ a: 'attr', t: 'rmbmoney', n: num ? num : G.gc.tanxian_com.fastGuaJiNeed[G.gc.tanxian_com.fastGuaJiNeed.length - 1] }];
        await PlayerFun.checkNeedIsMeet(call, need);
        await PlayerFun.cutNeed(call, need);
    }
    let prize = TanXianShared.getGuaJiPrize(G.gc.tanxian_com.fastGuaJiTime, call.conn.gud.mapId, false, {
        shoucangpin: call.conn.gud.shoucangping
    });

    let eventPrize = getEventPrize(call.conn.gud.lv, G.gc.tanxian_com.fastGuaJiTime, call.conn.gud.mapId, call.conn.gud.wxcLv?.lv);
    let _p = [].concat(prize.prize, prize.dlz, eventPrize.prize);
    // 过滤物品数量为0的道具。
	_p = _p.filter(x => x.n > 0)
    // await event_dldh_addPrize(_p, call, G.gc.tanxian_com.fastGuaJiTime);
    await PlayerFun.sendPrize(call, _p);

    let setData = { useFastGuaJiNum: data.useFastGuaJiNum + 1, useFreeGuaJiNum: (data?.useFreeGuaJiNum || 0) + (notFree ? 0 : 1)}
    if ((data?.zztqfreeNum || 0) < tqFree && tqFree) setData["zztqfreeNum"] = tqFree
    TanXianFun.changeData(call, setData);

    // (await call.conn.gonghui)?.addExp(20, call.uid);

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

    call.succ({
        prize: _p,
        iNum: eventPrize.iNum,
        aNum: eventPrize.aNum,
        useFastGuaJiNum: data.useFastGuaJiNum + 1
    });
}