import { getToper200RankUid } from '../../api_s2c/hbzb/jfs/fun';
import { getZbsRankList, zbsGroup } from '../../api_s2c/hbzb/zbs/fun';
import {ChatFun} from '../chat';
import {EmailFun} from '../email';
import {Rank} from '../rank/rank';
import {Scheduler, schedulerType} from './scheduler';

/**
 * 这个定时器在本服上执行
 * 用于在积分赛结束时，给本服的玩家，按积分排序后发奖 
 */
export class Scheduler_hbzb_jfs_local_prize extends Scheduler {
    id: schedulerType = 'hbzb_jfs_prize';
    //G.gc.hbzb.jfsOpenTime[1]，按需求，这个时间应该是周五晚上22点的秒数
    time = G.gc.hbzb.jfsOpenTime[1];
    name = '黑帮争霸积分赛邮件发奖(周五22:00)';
    type: 'day' | 'week' = 'week';

    async read() {
        await this.ctorStartTime();
        this.isReady = false;
    }
    async start() {
        let rankListUid = await getToper200RankUid();
        this.sendEmail(rankListUid);
        await this.record();
    }

    sendEmail(uids: string[]) {
        let rankConf = G.gc.hbzb.jfsLocalRankPrize;
        let email = G.gc.hbzb.jfsLocalEmail;
        rankConf.forEach(conf => {
            //根据配置slice出对应的uid
            let uidSlice = uids.slice(conf.ph[0] - 1, conf.ph[1]);
            uidSlice.forEach((uid, index) => {
                EmailFun.addEmail({
                    uid: uid,
                    type: 'system',
                    title: email.titel,
                    content: email.content,
                    prize: conf.prize,
                    contentInsertArr: [conf.ph[0] + index]
                });
            });
        });
    }
}

/**
 * 这个定时器在跨服上执行
 * 用于将hbzb_user_cross表里的zbsgroup，jifen，rank清空，便于01:00时，各个区向跨服上传数据
 */
export class Scheduler_hbzb_zbs_cross_clear extends Scheduler {
    id: schedulerType = 'hbzb_zbs_clear';
    //周六凌晨0点时，计算数据
    time = 5*24*3600;
    name = '黑帮争霸争霸赛清理数据(周六00:00)';
    type: 'day' | 'week' = 'week';

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

    async start() {
        await G.mongodb.collection('hbzb_user_cross').updateMany({}, {$set: {
            jifen:-999999,
            rank:-999999,
            zbsgroup:""
        }})
        await this.record();
    }
}

/**
 * 这个定时器在本服里执行，用于将积分赛前100名的积分数据上传到跨服里
 */
export class Scheduler_hbzb_zbs_local_ready extends Scheduler {
    id: schedulerType = 'hbzb_zbs_ready';
    //周六凌晨1点时，计算数据
    time = 5*24*3600+3600;
    name = '黑帮争霸争霸赛上传数据(周六01:00)';
    type: 'day' | 'week' = 'week';

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

    async start() {
        let arr = await G.mongodb.collection("playerInfo").find(
            { "type": "hbzb", "data.jifen":{$gt:0} },
        ).sort(
            { "data.jifen": -1 }
        ).project({
            uid:1,
            "data.jifen":1
        }).limit(100).toArray();

        arr.map(async u=>{
            console.log('hbzb_user_cross update=>',u.uid,u.data.jifen);
            G.crossmongodb.collection("hbzb_user_cross").updateMany({uid: u.uid}, {$set: {jifen: u.data.jifen}})
        })

        await this.record();
    }
}

/**
 * 这个定时器在跨服上执行
 * 用于每300个玩家进行分组，并初始化rank排名
 */
export class Scheduler_hbzb_zbs_cross_group extends Scheduler {
    id: schedulerType = 'hbzb_zbs_group';
    time = 5*24*3600+ 3*3600;
    name = '黑帮争霸争霸赛分组(周六03:00)';
    type: 'day' | 'week' = 'week';

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

    async start() {
        await zbsGroup();
        await this.record();
    }
}

/**
 * 在本服上执行
 * 用于从跨服获取排名数据，并判断哪些玩家在本服，对这些玩家进行发奖
 */
export class Scheduler_hbzb_zbs_local_prize extends Scheduler {
    id: schedulerType = 'hbzb_zbs_prize';
   
    time = G.gc.hbzb.zbsOpenTime[1];
    name = '黑帮争霸争霸赛结算(周日22:00)';
    type: 'day' | 'week' = 'week';

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

    async start() {
        let zbsgroups = await G.crossmongodb.collection("hbzb_user_cross").distinct("zbsgroup", { zbsgroup: { $ne: "" } });
        zbsgroups.map(async group =>{
            let rank = await getZbsRankList(null,group);
            let uids = rank.rankList.map(r => r.player.uid);
            this.sendEmail(uids);
        });
        // console.log(zbsgroups);

        // let crossRank = (await G.clientCross.callApi('hbzb/zbs/GetRankList', {})).res.rankList;
        // this.sendEmail(crossRank.map(rank => {
        //     return {uid: rank.player.uid, valArr: [...rank.valArr]};
        // }));

        // crossRank.length > 0 && ChatFun.newMsg({
        //     type: 'cross',
        //     msg: G.gc.pmd.hbzb_pmd,
        //     time: G.time,
        //     sender: 'system',
        //     otherData: {
        //         pmd: true,
        //         args: crossRank.slice(0, 3).map(v => `${v.player.name}【${v.player.serverName}】`)
        //     }
        // });

        // for (let i = 0; i < 3; i++) {
        //     let r = crossRank[i];
        //     if (r) {
        //         ChatFun.newMsg({
        //             type: 'cross',
        //             msg: G.gc.pmd['hbzb_pmd' + (i + 1)],
        //             time: G.time,
        //             sender: 'system',
        //             otherData: {
        //                 pmd: true,
        //                 args: [`${r.player.name}【${r.player.serverName}】`]
        //             }
        //         });

        //     }
        // }

        await this.record();
    }

    sendEmail(uids: string[]) {
        let rankConf = G.gc.hbzb.zbsRankPrize;
        let email = G.gc.hbzb.zbsEmail;
        rankConf.forEach(conf => {
            let _uids = uids.slice(conf.ph[0] - 1, conf.ph[1]);
            _uids.forEach((uid, index) => {
                EmailFun.addEmail({
                    uid: uid,
                    type: 'system',
                    title: email.titel,
                    content: email.content,
                    prize: conf.prize,
                    contentInsertArr: [conf.ph[0] + index]
                });
            });
        });
    }
}



export class Scheduler_hbzb_local_reset extends Scheduler {
    id: schedulerType = 'hbzb_local_reset';
    time = G.gc.hbzb.jfsOpenTime[0];
    name = '黑帮争霸本服重置(周一0:00)';
    type: 'day' | 'week' = 'week';

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

    async start() {
        //删除data.enemy字段
        G.mongodb.cPlayerInfo('hbzb').updateMany({type: 'hbzb'}, {$unset: {"data.enemy": 1},$set: {"data.jifen": 0}});
        await this.record();
    }
}

// export class Scheduler_hbzb_corss_reset extends Scheduler {
//     id: schedulerType = 'hbzb_cross_reset';
//     time = G.gc.hbzb.zbsOpenTime[1] + 300;
//     name = '黑帮争霸跨服重置';
//     type: 'day' | 'week' = 'week';

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

//     async start() {
//         // await G.mongodb.collection('hbzb_user_cross').updateMany({}, {$set: {jifen: 1000}});
//         // Rank.list.hbzbCross.loadAllPlayer();
//         // Rank.list.hbzbCross.clear();
//         // Rank.list.hbzbZbsCross.clear();
//         await this.record();
//     }
// }