import { PublicShared } from '../../shared/public/public';
import { EmailFun } from '../email';
import { QjzzdFun } from '../qjzzd';
import { Rank } from '../rank/rank';
import { Scheduler, schedulerType } from './scheduler';


export class SchedulerQjzzd extends Scheduler {
    id: schedulerType = 'qjzzd';
    name = '清剿真主党';
    time = G.gc.qjzzd.time[1] + 60;
    // time = G.time - this.zeroTime + 1 * 60 - 3 * 24 * 60 * 60;  // todo 测试
    // get nextTime() {
    //     return G.time + 1 * 60;
    // }

    type: 'day' | 'week' = 'day';
    async read() {
        let data = await this.db.findOne({ type: this.id });

        if (!data) {
            this.db.updateOne({ type: this.id }, { $set: { lastRunTime: G.time, boss: await QjzzdFun.getBoosId(0) } }, { upsert: true });
        }

        if (PublicShared.getOpenServerDay() < G.gc.eventOpen.qjzzd.day) {
            this.startTime = PublicShared.getToDayZeroTime(G.openTime) + G.gc.eventOpen.qjzzd.day * 24 * 3600;
        } else {
            await this.ctorStartTime();
        }
        this.isReady = false;
    }
    async start() {
        if (!await QjzzdFun.chkSetBoosId()) {
            console.log("真主党跑光了 今天无法清缴")
            this.startTime = this.nextTime;
            this.isStart = false;
            return
        }
        let rankList:any = await Rank.list['qjzzd'].getRankListAll()
        rankList = rankList.map(rank => { return { uid: rank.player.uid, valArr: [...rank.valArr] }; });

        // G.gc.qjzzd.rankPrize
        let _rankPrize = await QjzzdFun.getphPrize()
        _rankPrize.forEach(conf => {
            let players = rankList.slice(conf.ph[0] - 1, conf.ph[1]);
            players.forEach((p, index) => {
                EmailFun.addEmail({
                    uid: p.uid,
                    type: 'system',
                    title: G.gc.qjzzd.email.titel,
                    content: G.gc.qjzzd.email.content,
                    prize: conf.prize,
                    contentInsertArr: [conf.ph[0] + index, ...p.valArr]
                });
            });
        });

        Rank.list.qjzzd.clear();

        let nextBoss: string;
        nextBoss = await QjzzdFun.getBoosId();

        // let data = await G.mongodb.collection('scheduler').findOne({ type: this.id });

        // if (!data) {
        //     nextBoss = G.gc.qjzzd.boss[0];
        // } else {

        //     let index = G.gc.qjzzd.boss.findIndex(id => id == data.boss);
        //     if (index == -1 || index == G.gc.qjzzd.boss.length - 1) {
        //         nextBoss = G.gc.qjzzd.boss[0];
        //     } else {
        //         nextBoss = G.gc.qjzzd.boss[index + 1];
        //     }
        // }
        // lastRunTime仅储存最大值，问题记录: 本地多人启动服务时，有调用此定时器的情况下，时间会混乱。
        await this.db.updateOne({ type: this.id }, { $set: { boss: nextBoss }, $max: { lastRunTime: G.time } }, { upsert: true });
        this.startTime = this.nextTime;
        this.isStart = false;
    }
}