import {PublicShared} from '../../shared/public/public';
import {EmailFun} from '../email';
import {RankClslCross} from '../rank/rank_clsl';
import {Scheduler, schedulerType} from './scheduler';

/**
 * 丛林猎手赛季重置
 */
export class SchedulerClslLocalCtor extends Scheduler {
    id: schedulerType = 'clsl_cross_ctor';

    time = 0;
    name = '丛林猎手赛季重置';
    type: 'day' | 'week' = 'week';

    async read() {
        await this.ctorStartTime();
        this.isReady = false;
    }

    async start() {
        let week = PublicShared.getToWeek(
            PublicShared.getToWeekMondayZeroTime(G.time - 3600)
        );

        // 修改clslCrossUser表中的uid为del_uid_week 并且 设置ttltime为当前时间
        await G.mongodb.collection('clslCrossUser').updateMany(
            {
                ttltime: {$exists: false}
            }, {$rename: {"uid": `del_uid_${week}`}, $set: {"ttltime": new Date()}}
        );

        // 获取分组信息 重置排行榜
        let groups = await G.mongodb.collection('clslCrossGroup').findOne({week});
        Object.keys(groups.groups).forEach((group) => {
            // 清理排行数据
            new RankClslCross(group).clear();
        })

        await this.record();
    }
}

/**
 * 丛林猎手赛季划分
 * 达到王者段位的所有玩家 按照创号时间从早到晚排序 每100个玩家划分一个区间
 */
export class SchedulerClslCrossCtor extends Scheduler {
    id: schedulerType = 'clsl_cross_group';

    num: number = 2;

    type: 'day' | 'week' = 'week';
    time = G.gc.clsl_com.divideTime;
    name = '丛林猎手赛季区间划分 周四00:00';

    star = Object.values(G.gc.clsl_dan).slice(-1)[0].allStar;

    async read() {
        await this.ctorStartTime();
        this.isReady = false;
    }

    async start() {
        let week = PublicShared.getToWeek();
        let users = await G.mongodb.collection('clslCrossUser').find({
            ttltime: {$exists: false}
        }, {
            projection: {
                "uid": 1,
                "allStar": 1,
                "info.player.cTime": 1
            }
        }).toArray();

        // 筛选出所有王者分段 按照建号时间排序
        let wzusers = users.filter(u => u.allStar >= this.star).sort((a, b) => a.info.player.cTime - b.info.player.cTime);

        // 每100个玩家划分一个区间
        let groups: { [group: string]: { st: number, et: number, users: string[] } } = {};
        let group_num = wzusers.length / this.num;

        // 非王者玩家
        let remaining_users = users.filter(u => u.allStar < this.star);
        if (group_num >= 1) {
            let tt = parseInt(group_num + '')
            for (let i = 1; i <= tt; i++) {
                groups['group' + i] = {
                    et: wzusers[i * this.num - 1].info.player.cTime,
                    st: wzusers[(i - 1) * this.num].info.player.cTime,
                    users: wzusers.slice((i - 1) * this.num, i * this.num).map(u => u.uid),
                }
                if (i == 1) {
                    groups['group1'].st = 0
                }
                if (i == tt) {
                    groups['group' + i].et = G.time + 7 * 14 * 3600;
                    groups['group' + i].users = wzusers.slice((i - 1) * this.num).map(u => u.uid);
                }
            }
            ;
        } else {
            groups['group0'] = {
                st: 0,
                et: G.time + 7 * 14 * 3600,
                users: wzusers.map(u => u.uid),
            }
        }

        // 剩余玩家
        for (let i = 0; i < remaining_users.length; i++) {
            for (let group in groups) {
                if (remaining_users[i].info.player.cTime >= groups[group].st && remaining_users[i].info.player.cTime <= groups[group].et) {
                    groups[group].users.push(remaining_users[i].uid);
                }
            }
        }

        // 更新玩家分组id
        for (let group in groups) {
            await G.mongodb.collection('clslCrossUser').updateMany({uid: {$in: groups[group].users}}, {$set: {group: group}});
        }

        // 记录分组
        await G.mongodb.collection("clslCrossGroup").updateOne({week: week}, {$set: {groups: groups}}, {upsert: true});

        // 初始化丛林猎手排行榜
        G.mongodb.collection('clslCrossUser').find({
            allStar: {$gte: this.star}, ttltime: {$exists: false}
        }).toArray().then(users => {
            users.forEach(u => {
                new RankClslCross(u.group).addNew({
                    valArr: [u.allStar, u.info.player.power],
                    player: u.info.player,
                    roles: u.info.roles,
                })
            })
        })

        await this.record();
    }
}


/**
 * 丛林猎手赛季发奖
 */
export class SchedulerClslPrize extends Scheduler {
    id: schedulerType = 'clsl_prize';

    name = '丛林猎手赛季发奖';
    type: 'day' | 'week' = 'week';
    time = G.gc.clsl_com.prizeTime;
    star = Object.values(G.gc.clsl_dan).slice(-1)[0].allStar;

    async read() {
        await this.ctorStartTime();
        this.isReady = false;
    }

    async start() {
        // 排名奖励
        let group2users: { [group: string]: string[] } = {};
        (await G.mongodb.collection('clslCrossUser').find({allStar: {$gte: this.star}}).toArray()).forEach(u => {
            if (u.group in group2users) {
                group2users[u.group].push(u.uid);
            } else {
                group2users[u.group] = [u.uid];
            }
        });

        Object.values(group2users).forEach((uids, index) => {
            G.gc.clsl_com.rankPrize.forEach((conf) => {
                let players = uids.slice(conf.rank[0] - 1, conf.rank[1]);
                players.forEach((uid, index) => {
                    EmailFun.addEmail({
                        uid: uid,
                        type: 'system',
                        title: G.gc.clsl_com.email_rank.title,
                        content: G.gc.clsl_com.email_rank.content,
                        prize: conf.prize,
                        contentInsertArr: [conf.rank[0] + index]
                    }, true);
                });
            });
        })

        await this.record();
    }
}