import {Scheduler, schedulerType} from './scheduler';
import {PublicShared} from "../../shared/public/public";
import {Wjjl} from "../../module/collection_wjjl";
import {ZhanLingTasks} from "../zhanling";
import {setGud} from '../gud';
import {HuoDongFun} from "../huodongfun";
import {EmailFun} from "../email";
import {sortRankList} from "../../api_s2c/event/xiaofeijingsai/ApiOpen";

/**
 * 消费竞赛发奖定时器
 * 每天0点5分检测活动结束
 */
export class Scheduler_xfjs_Local_Ctor extends Scheduler {
    id: schedulerType = 'xiaofeijingsai_local_ctor';
    time = 300;
    name = '消费竞赛发奖定时器';
    type: 'day' | 'week' = 'day';

    // todo 测试
    // get nextTime() {
    //     return G.time + 30;
    // }

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

    async start() {
        let _hd = (await G.mongodb.collection('hdinfo').find({
            htype: 11,
            ttype: 0,
            etime: {$lt: G.time, $gt: 99999999},
            $or: [{isSendPrize: {$exists: false}}, {isSendPrize: false}],
        }).sort({etime: -1}).limit(1).toArray())[0]

        if (!_hd) return

        let limit = _hd.data?.rank?.slice(-1)?.[0]?.rank?.slice(-1)?.[0] || 100

        let rmbuse = await G.crossmongodb.collection('rmbuse').find({type: `xfjs_${_hd.hdid}`}).sort({change: 1}).limit(limit).toArray()

        let list: any = rmbuse.map(i => ({...i, total: R.negate(i.change)}))

        let rankList = sortRankList(_hd.data.rank, list)

        let userList = await G.crossmongodb.collection('huodong_user').find({uid: {$in: rankList.map(i => i._id).filter(i => i != 'system')}}).toArray()

        rankList = rankList.map(i => ({...i, player: userList.find(v => v.uid == i.uid) || {}}))

        R.forEach(i => {
            let users = R.slice(i.rank[0] - 1, i.rank[1])(rankList).filter(i => i._id != 'system')
            users.map(v => {
                if (G.config.serverId != v.player?.sid) return;
                EmailFun.addEmail({
                    uid: v._id,
                    type: 'system',
                    title: _hd.data.mailTitle,
                    content: _hd.data.mailDes,
                    prize: i.prize,
                    contentInsertArr: [v.rank + 1]
                });
            })
        })(_hd.data.rank)

        await G.mongodb.collection('hdinfo').findOneAndUpdate({hdid: _hd.hdid}, {$set: {isSendPrize: true}})
    }
}
