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

/******* 存在数据库里的数据 *******/
interface NewHeroGiftRewardInDb {
    index: number;     // 下标
    reward: string;    // 奖励 type&id&count
    countMax: number;  // 最多抽出次数
}

interface NewHeroGiftDataInDb {
    startTaskTime: string; // 开始计算任务积分的时间 hh:mm:ss
    rewards: NewHeroGiftRewardInDb[];  // 奖励
    consumePoint: number;   // 每转一次消耗的点数
}

/******* 返回给客户端的数据 *******/
class NewHeroGiftReward {
    index: number;     // 下标
    reward: string;    // 奖励 type&id&count
    countMax: number;  // 最多抽出次数
    buyCount: number = 0;  // 转出的次数

    constructor(data: NewHeroGiftRewardInDb) {
        this.index = data.index;
        this.reward = data.reward;
        this.countMax = data.countMax;
    }

    addBuyCount() {
        this.buyCount++;
    }
}

export class NewHeroGiftData extends ActivityBase {
    consumePoint: number;   // 每转一次消耗的点数
    rewards: NewHeroGiftReward[] = [];               // 奖励
    startTaskTime: number;  // 开始计算任务积分的时间 时间戳

    totalPoint: number = 0;    // 已获得的点数
    consumeTotalPoint: number = 0; // 总消耗的点数

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

    public initData(data: string) {
        let dataObj: NewHeroGiftDataInDb = JSON.parse(data);
        this.consumePoint = dataObj.consumePoint;
        let arr = dataObj.rewards||[];
        for (let obj of arr) {
            this.rewards.push(new NewHeroGiftReward(obj))
        }
        this.startTaskTime = moment(moment(this.beginTime).format(`YYYY-MM-DD ${dataObj.startTaskTime}`)).valueOf();
    }

    public findItem(index: number) {
        return this.rewards.find(obj => { return obj && obj.index === index });
    }

    //解析玩家购买记录
    public setPlayerRecords(data: ActivityNewHeroGiftModelType) {
        if (!data) {
            return;
        }
        this.totalPoint = data.totalPoint||0;
        let records = data.records||[];
        for (let obj of records) {
            let item = this.findItem(obj.index);
            if(item) item.addBuyCount();
            this.consumeTotalPoint += obj.point;
        }
    }

    public canRecordTaskPoint() {
        return Date.now() >= this.startTaskTime && Date.now() <= this.endTime
    }
}