import { ActivityModelType } from '../../db/Activity';
import { ActivityDailyGiftsModelType } from '../../db/ActivityDailyGifts';
import { parseResStr } from '../../pubUtils/util';
import { ConsumeResParam } from '../activityField/consumeField';
import { ActivityBase } from './activityField';


// 每日礼包配置数据
export class DailyGiftItem {
    dayIndex: number;       // 第几天,从1开始
    cellIndex: number;      // 当天第几行，从1开始
    name: string;           // 名称
    consume: string;        // 购买的资源数据; 格式:type:id:count, type:ACTIVITY_RESOURCES_TYPE;RMB时id无效
    reward: string;         // 任务奖励，格式:1&3&1(类型&id&数量) 类型定义:1.英雄，2.物品
    maxCount: number = 1;   //最大可购买次数
    discount: number = 0;// 商品显示的折扣

    buyCount: number = 0;   //购买次数

    constructor(data: any) {
        this.dayIndex = data.dayIndex;
        this.cellIndex = data.cellIndex;
        this.name = data.name;
        this.consume = data.consume;
        this.reward = data.reward;
        this.maxCount = data.maxCount;
        this.discount = data.discount;
        this.buyCount = 0;
    }

    //消耗的资源
    public consumeRes(): ConsumeResParam {
        let consumeArray = parseResStr(this.consume);
        return consumeArray[0];
    }

    public canBuy(): boolean {
        return this.buyCount < this.maxCount;
    }

}


// 今日挑战活动数据
export class DailyGiftsData extends ActivityBase {
    list: Array<DailyGiftItem> = [];

    public findDailyGiftsItem(dayIndex: number, cellIndex: number) {
        let index = this.list.findIndex(obj => { return obj && obj.dayIndex == dayIndex && obj.cellIndex == cellIndex })
        return (index != -1) ? this.list[index] : null;
    }

    //解析玩家购买记录
    public setPlayerRecords(data: ActivityDailyGiftsModelType[]) {
        for (let obj of this.list) {
            let index = data.findIndex(record => { return obj.dayIndex == record.dayIndex && obj.cellIndex == record.cellIndex })
            if (index != -1) {
                obj.buyCount = data[index].buyCount ? data[index].buyCount : 0;
            } else {
                obj.buyCount = 0;
            }
        }
    }

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

        let arr = dataObj;

        for (let obj of arr) {
            this.list.push(new DailyGiftItem(obj))
        }
    }

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