import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../public/player';
import { TanXianFun } from '../../public/tanxian';
import { ReqEvent, ResEvent } from "../../shared/protocols/tanxian/PtlEvent";
import { prizeType } from '../../shared/protocols/type';
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqEvent, ResEvent>) {
    let data = await TanXianFun.getData(call, false);
    if (!data?.eventTime || !G.gc.tanxian[call.conn.gud.mapId]) return call.errorCode(-1);

    let seconds = G.time - data.eventTime;
    if (seconds < G.gc.tanxian_com.eventCd) return call.errorCode(-2);
    let maxSeconds = 20 * 3600;
    if (seconds > maxSeconds) seconds = maxSeconds;

    let eventTime = G.time;
    let prizeData = getEventPrize( call.conn.gud.lv,seconds, call.conn.gud.mapId, call.conn.gud.wxcLv?.lv);

    await PlayerFun.sendPrize(call, prizeData.prize);
    TanXianFun.changeData(call, { eventTime: eventTime });
    call.succ({
        prize: prizeData.prize,
        iNum: prizeData.iNum,
        aNum: prizeData.aNum,
        eventTime: eventTime
    });
}

export function getEventPrize(plerLv: number, seconds: number, mapId: number, wxcLv = 1): {
    prize: prizeType[];
    iNum: number,
    aNum: number,
} {
    let prize: prizeType[] = [];
    let num = Math.floor(seconds / G.gc.tanxian_com.eventCd);
    let conf = G.gc.tanxian[mapId || 1];
    let cutNum = 0;
    let drop = [...conf.drop];
    // 根据等级查询饰品掉落组
    let shiwuConf = G.gc.tanxian_shiwu
    let shiwuDiaoluo = Object.values(shiwuConf).filter(v => v.level[0] <= plerLv && v.level[1] >= plerLv).map(v => v.guajidiaoluo)
    // 随机插入饰物
    if(shiwuDiaoluo.length > 0) {
        drop.push(shiwuDiaoluo.sort(() => 0.5 - Math.random()).shift())
    }
    if (G.gc.weixiuchang_zz[wxcLv || 1]) {
        wxcLv = wxcLv == 0 ? 1 : wxcLv
        drop.push(G.gc.weixiuchang_zz[wxcLv].drop);
    }

    for (let i = 0; i < num; i++) {
        let c = PublicShared.randomDropAny(G.gc.tanxian_com.event);
        if (c.type == 'item') {
            cutNum++;
            prize.push(...PublicShared.randomDropGroup(drop.random()));
        } else {
            prize.push({ a: "attr", t: 'jinbi', n: Math.floor(conf.base * conf.round.random()) });
        }
    }

    prize = PublicShared.mergePrize(prize);
    return {
        prize: prize,
        iNum: cutNum,
        aNum: num - cutNum
    };
}