import { PublicShared } from '../../shared/public/public';
import { EmailFun } from '../email';
import { JJCFun } from '../jjc';
import { Scheduler, schedulerType } from './scheduler';


export class SchedulerJJC extends Scheduler {
    id: schedulerType = 'jjc';
    name = '竞技场发奖';
    time = G.gc.jjc_com.sendPrizeTime[1];
    type: 'day' | 'week' = 'day';

    async read() {
        await this.ctorStartTime();
        this.isReady = false;
    }
    async start() {
        Object.values(G.gc.jjc_ph).forEach(async (conf) => {
            // let players = rankList.slice(conf.ph[0] - 1, conf.ph[1]);
            let players = await JJCFun.getRankListUid(conf.ph[0] - 1, conf.ph[1]);

            players.forEach((uid, index) => {
                this.sendEmail(uid, conf.ph[0] + index, getRankPrize(conf.ph[0] + index, conf));
            });
        });

        let weekZeroTime = PublicShared.getToWeekMondayZeroTime();
        if (G.time > weekZeroTime + 4 * 24 * 3600 && G.time < weekZeroTime + 5 * 24 * 3600) {//竞技场前三名获得争霸赛参赛资格
            // ### globalDebug JJCFun 获取前20名用户，且不是npc
            let tops = await JJCFun.getRankList(0, 20)
            tops = tops.filter(l => !l.player.isNpc)
            G.clientCross?.callApi('hbzb/zbs/SendJjcTop', { tops });
        }

        await this.record();
    }
    sendEmail(uid: string, rank: number, prize: atn[]) {

        if (uid.indexOf('npc_') != -1) return;

        EmailFun.addEmail({
            uid: uid,
            type: 'system',
            title: G.gc.jjc_com.email.titel,
            content: G.gc.jjc_com.email.content,
            prize: prize,
            contentInsertArr: [rank]
        });
    }
}

function getRankPrize(rank: number, conf?: typeof G.gc.jjc_ph['']) {
    if (!conf) {
        conf = Object.values(G.gc.jjc_ph).filter(v => rank >= v.ph[0] && rank <= v.ph[1])[0];
    }
    if (conf) {
        return [...conf.prize, { a: 'item', t: '11', n: typeof conf.rongyuprize == 'number' ? conf.rongyuprize : PublicShared.eval(conf.rongyuprize, { a: rank }) }];
    } else {
        return [];
    }
}