import { ActivityModelType } from '../../db/Activity';
import { ActivityShopModelType } from '../../db/ActivityShop';
import { ActivityBase } from './activityField';

// 每个商品的内容
export class ShopItem {
    id: number;             // 商品id，不能重复
    reward: string;         //任务奖励，格式:1&3&1(类型&id&数量) 类型定义:1.英雄，2.物品
    countMax: number = 0;   //可购买的最大次数，0表示不限制
    name: string;           //名字
    price: number;           //价格
    productID: string;           //商品id
    consume: string;           //消耗
    imageName: string;
    discount: number;        //折扣

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

    constructor(data: any) {
        this.id = data.id;
        this.reward = data.reward;
        this.countMax = data.countMax;
        this.name = data.name;
        this.price = data.price;
        this.productID = data.productID;
        this.imageName = data.imageName;
        this.discount = data.discount ? data.discount : 0;
        this.consume = data.consume ? data.consume : '';
        this.buyCount = 0;
    }
}

// 商店数据
export class LimitShopData extends ActivityBase {
    name: string = '';//活动名称
    list: Array<ShopItem> = [];//商品列表
    // nextRefreshTime: number;//下次刷新时间
    // roundIndex: number = 1;//周期数从1开始

    public findItemByProductID(productID: string) {
        let index = this.list.findIndex(obj => { return obj && obj.productID === productID });
        return (index != -1) ? this.list[index] : null
    }

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

    //全部领取完成
    public isComplete() {
        for (let item of this.list) {
            if (item.countMax == 0 ||
                (item.countMax > 0 && item.buyCount < item.countMax)) {
                return false
            }
        }
        return true;
    }

    //解析玩家购买记录
    public setPlayerRecords(data: ActivityShopModelType) {
        if (!data) {
            return;
        }
        let records = data.records ? data.records : [];
        for (let item of this.list) {
            let buyRecords = records.filter(obj => { return obj && obj.id === item.id });
            item.buyCount = buyRecords.length;
        }
    }


    public initData(data: string) {
        // this.nextRefreshTime = this.endTime;
        let dataObj = JSON.parse(data);
        this.name = dataObj.name;

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

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