import moment = require('moment');
import { FIRST_GIFT_STATE } from '../../consts';
import { ActivityModelType } from '../../db/Activity';
import { ActivityFirstGiftModelType } from '../../db/ActivityFirstGift';
import { deltaDays } from '../../pubUtils/util';
import { ActivityBase } from './activityField';

// 首充礼包的数据
export class FirstGiftItem {
    index: number;          // 第几天，从1开始
    name: string;            //名称
    reward: string;           //奖励
    goldCount: number;        // 显示用的可获得元宝

    isReceive: boolean = false;          //是否领取过奖励

    constructor(data: any) {
        this.name = data.name;
        this.index = data.index;
        this.reward = data.reward;
        this.goldCount = data.goldCount;
        this.isReceive = false;
    }
}

// 30天任务活动数据
export class FirstGiftData extends ActivityBase {
    state: number = FIRST_GIFT_STATE.CLOSED;//活动状态
    list: Array<FirstGiftItem> = [];//奖励

    //全部领取完成
    public isComplete() {
        for (let i = 0; i < this.list.length; i++) {
            if (!this.list[i].isReceive) {
                return false
            }
        }
        return true;
    }

    //奖励内容
    public findFirstGiftItem(index: number): FirstGiftItem {
        let listIndex = this.list.findIndex(obj => { return obj && obj.index == index });
        if (listIndex != -1) {
            return this.list[listIndex];
        }
        return null;
    }

    //可以领取的奖励
    public canReceiveItems(): FirstGiftItem[] {
        return this.list.filter(obj => { return obj && !obj.isReceive && obj.index <= this.todayIndex });
    }

    //解析玩家任务领取记录
    public setPlayerRecords(data: ActivityFirstGiftModelType) {
        this.todayIndex = 0;
        if (!data) {
            return;
        }
        this.todayIndex = deltaDays(moment(data.createdAt).startOf('d').toDate(), new Date) + 1;
        this.state = FIRST_GIFT_STATE.OPEN

        let daysNum = data.days ? data.days : [];
        for (let obj of this.list) {
            if (daysNum.indexOf(obj.index) !== -1) {
                obj.isReceive = true;
            }
        }
    }

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

        let arr = dataObj.data;
        for (let obj of arr) {
            this.list.push(new FirstGiftItem(obj))
        }
    }

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