import moment = require('moment');
import { random } from 'underscore';
import { ActivityModelType } from '../../db/Activity';
import { ActivityRechargeMoneyModelType } from '../../db/ActivityRechargeMoney';
import { ActivityBase } from './activityField';

// 充值记录
export class RechargeMoneyItem {
    _id: string;      //mongodb 
    id: number;       //商品id
    name: string;      //商品名称
    reward: string;   //奖励

    rewardTime: Date; //领奖时间

    constructor(data: any) {
        this.id = data.id;
        this.name = data.name;
        this.reward = data.reward;
        this.rewardTime = null;
    }
}

// 累计充值数据
export class RechargeMoneyData extends ActivityBase {
    list: Array<RechargeMoneyItem> = [];//记录
    days: number = 0;
    price: number = 0;

    totalCount: number = 0;//一共可领取次数
    receiveCount: number = 0;//已经领取次数

    recordArray: ActivityRechargeMoneyModelType[] = [];

    //当前回合最后一个
    public isLast() {
        let items = this.list.filter(obj => { return obj && !obj.rewardTime });
        return items.length === 1;
    }

    public randomReward(): RechargeMoneyItem {
        let items = this.list.filter(obj => { return obj && (!obj.rewardTime || obj.rewardTime == undefined) })
        if (items.length == 0) {
            return null;
        }
        let index = random(items.length - 1);
        return items[index];
    }

    //解析玩家购买记录
    public setPlayerRecords(data: ActivityRechargeMoneyModelType[]) {
        this.todayIndex = 0;
        if (!data) {
            return;
        }
        this.recordArray = data.filter(obj => {
            return obj.RMB >= this.price;
        }).sort((a, b) => {
            return moment(a.beginTime).valueOf() - moment(b.beginTime).valueOf()
        })

        this.totalCount = this.recordArray.length;
        this.receiveCount = 0;
        for (let item of this.list) {
            let index = this.recordArray.findIndex(obj => { return obj.index === item.id })
            if (index != -1) {
                this.receiveCount++;
                item.rewardTime = this.recordArray[index].rewardTime;
            }
        }
    }

    public initData(data: string) {
        let dataObj = JSON.parse(data);
        this.days = dataObj.days;
        this.price = dataObj.price;

        let arr = dataObj.data;
        for (let obj of arr) {
            this.list.push(new RechargeMoneyItem(obj))
        }
        this.list = this.list.sort((a, b) => {
            return a.id - b.id
        })
    }

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