import moment = require('moment');
import { RANK_TYPE } from '../../consts';
import { ActivityModelType } from '../../db/Activity';
import { ActivityBase } from './activityField';

interface TimeLimitRewardInDb {
    rank: number;      // 第几名
    rewards: string;   // type&id&count
    guildRewards: string; // 军团整体奖励
}

interface TimeLimitInDb {
    rankType: number;      // 排行榜类型 
    hid: number;           // 如果有单个武将排行，这里写武将id
    rankEndDay: number;   // 开始时间之后几天停止计入活动
    rankEndTime: string;  // hh:mm:ss，几点几分几秒正式计入活动
    sendMailTime: number;  // rankEndTime 后几秒发送邮件奖励
    rankRewards: TimeLimitRewardInDb[];        // 不同排名的奖励
    tabName: string;       // 排行榜标签名
}


export class TimeLimitRankReward {
    rank: number
    rewards: string;
    guildRewards: string;
    
    constructor(data: TimeLimitRewardInDb) {
        this.rank = data.rank;
        this.rewards = data.rewards;
        this.guildRewards = data.guildRewards;
    }
}

// 新云转盘活动数据
export class TimeLimitRankData extends ActivityBase {
    rankType: number;      // 排行榜类型 
    hid: number;           // 如果有单个武将排行，这里写武将id
    rankEndTime: number;   // 排行榜统计结束时间。13位时间戳，之后会在后台加时间筛选，在此之前先找wo
    sendMailTime: number;  // 发送奖励时间。13位时间戳
    rankRewards: TimeLimitRankReward[] = [];        // 不同排名的奖励
    tabName: string;       // 标签名
    
    // 是否可以记录
    public canRecord() {
        return this.beginTime <= Date.now() && this.rankEndTime >= Date.now();
    }

    public getRewardByRank(rank: number) {
        let result: TimeLimitRankReward;
        for(let reward of this.rankRewards) {
            result = reward;
            if(reward.rank >= rank) break;
        }
        return result;
    }

    public needSnapshot() {
        switch(this.rankType) {
            case RANK_TYPE.GUILD_FUND:
                return false;
            default:
                return true;
        }
    }

    public initData(data: string) {
        let dataObj: TimeLimitInDb = JSON.parse(data);
        this.rankType = dataObj.rankType;
        this.hid = dataObj.hid;
        this.rankEndTime = new Date(moment(this.beginTime).add(dataObj.rankEndDay - 1, 'd').format(`YYYY-MM-DD ${dataObj.rankEndTime}`)).getTime() ;
        this.sendMailTime = this.rankEndTime + dataObj.sendMailTime * 1000;
        for(let rank of dataObj.rankRewards) {
            this.rankRewards.push(new TimeLimitRankReward(rank));
        }
        this.tabName = dataObj.tabName;
    }

    public getShowResult() {
        return {
            ...this.getBaseKeys(),
            rankType: this.rankType,
            rankEndTime: this.rankEndTime,
            tabName: this.tabName,
        }
    }

    constructor(activityData: ActivityModelType, createTime: number, serverTime: number) {
        super(activityData, createTime, serverTime);
        this.initData(activityData.data)
    }
}