import moment = require('moment');
import { ACTIVITY_TYPE } from '../../consts';
import { ActivityModelType } from '../../db/Activity';
import { ActivityMonthlyTicketModelType } from '../../db/ActivityMonthlyTicket';
import { deltaDays } from '../../pubUtils/util';
import { ActivityBase } from './activityField';

interface MonthlyTickerInDb {
    name: string;       // 月卡名字
    id: number;         // 序列
    productID: string;  // 商品id vip月卡商品ID
    price: number ;     // 价格
    days: number;       // 持续天数，永久卡的话这里填0
    baseReward: string; // 每天领取的奖励  "2&1&1"
    firstReward: string;// 首次购买获得的奖励  "2&1&1"
    imageName: string;  // 图片名
    rebate: number;     // 返利倍数
}

// 月卡数据
export class MonthlyTicketData extends ActivityBase {

    name: string = '';  // 名称
    id: number = 0;  // 序列
    productID: string = '';  // 商品id
    price: number = 0;  // 价格
    days: number = 0;   // 持续天数
    baseReward: string = '';   // 每天领取的奖励
    firstReward: string = '';  // 首次购买获得的奖励
    imageName: string = '';
    rebate: number = 0;  // 返利倍数
    isForever: boolean = false;  // 是否是永久卡

    cardEndTime: number = 0;  // 结束时间
    dayIndex: number = 0;     // 已经领取了几天
    isOpen: boolean = false;  // 是否开启中
    todayIndex: number = 0;   // 现在可以领取第几天的奖励

    constructor(activityData: ActivityModelType, createTime: number, serverTime: number) {
        super(activityData, createTime, serverTime)
        this.initData(activityData.data);
        this.isForever = activityData.type == ACTIVITY_TYPE.MONTHLY_TICKET_2;
    }

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

        this.id = dataObj.id;
        this.name = dataObj.name;
        this.productID = dataObj.productID;
        this.price = dataObj.price;
        if(dataObj.days) this.days = dataObj.days;
        this.baseReward = dataObj.baseReward;
        this.firstReward = dataObj.firstReward;
        this.imageName = dataObj.imageName;
        this.rebate = dataObj.rebate;
    }

    //解析玩家领取记录
    public setPlayerRecords(data: ActivityMonthlyTicketModelType) {
        if (!data) {//没有购买月卡
            return;
        }
        this.dayIndex = data.dayIndex;
        this.cardEndTime = data.isForever? this.endTime: moment(data.endTime).valueOf();
        if (data.isForever || moment(new Date).valueOf() < this.cardEndTime) {
            this.isOpen = true;
            this.todayIndex = deltaDays(data.createdAt, new Date) + 1;
            this.days = deltaDays(data.createdAt, new Date(this.cardEndTime));
        } else {
            this.todayIndex = 0;
        }
    }

}