import { SHOP_REFRESH_TYPE } from '../../consts';
import { ActivityModelType } from '../../db/Activity';
import { ActivityRefreshShopModelType, GoodsInfo } from '../../db/ActivityRefreshShop';
import { getZeroPoint, getZeroPointOfTime } from '../../pubUtils/timeUtil';
import { ActivityBase } from './activityField';

interface RefreshShopDataInDb {
    shopType: number;
    name: string;
    data: RefreshShopPageInDb[];
}

interface RefreshShopPageInDb {
    pageIndex: number;
    viewcount: number;
    name: string;
    items: RefreshShopItemInDb[]
}

interface RefreshShopItemInDb {
    id: number;
    name: string;
    price: number;
    productID: string;
    reward: string;
    countMax: number;
    discount: number;
    imageName: string;
    consume: string;
    weight: number;
    refreshType: number;
    levelLimitMin: number;
    levelLimitMax: number;
}

// 每个商品的内容
export class RefreshShopItem {
    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;        //折扣
    pageIndex: number;      // 第几页
    levelLimitMin: number;   //玩家最低等级 0:不限制
    levelLimitMax: number;   //玩家最高等级 0:不限制
    weight: number;           //随机权重
    refreshType: SHOP_REFRESH_TYPE = SHOP_REFRESH_TYPE.FOREVER;

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

    constructor(data: RefreshShopItemInDb, pageIndex: number) {
        this.pageIndex = pageIndex;
        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.levelLimitMin = data.levelLimitMin ? data.levelLimitMin : 0;
        this.levelLimitMax = data.levelLimitMax ? data.levelLimitMax : 0;
        this.weight = data.weight ? data.weight : 0;
        if(data.refreshType) this.refreshType = data.refreshType;
    }

    setBuyRecords(data: ActivityRefreshShopModelType) {
        if(!data) return;
        let refZeroPoint = getZeroPoint(this.refreshType);
        let records = data.records ? data.records : [];
        let buyRecords = records.filter(obj => { 
            let curRefTime = getZeroPointOfTime(obj.time, this.refreshType);
            // console.log(curRefTime, refZeroPoint)
            return obj && obj.id === this.id && obj.pageIndex == this.pageIndex && curRefTime == refZeroPoint 
        });
        this.buyCount = buyRecords.length;
    }
}


// 每个商品的内容
export class RefreshShopPage {
    pageIndex: number;      // 第几页
    name: string;           //名字
    viewCount: number;       //随机可购买的商品个数
    items: Array<RefreshShopItem> = [];//商品列表
    constructor(data: RefreshShopPageInDb) {
        this.pageIndex = data.pageIndex;
        this.name = data.name;
        for (let item of data.items) {
            this.items.push(new RefreshShopItem(item, data.pageIndex))
        }
        this.viewCount = data.viewcount ? data.viewcount : this.items.length;
    }
}

// 商店数据
export class RefreshShopData extends ActivityBase {
    shopType: number = 0;//商店类型，用于客户端显示使用
    name: string = '';//活动名称
    list: Array<RefreshShopPage> = [];//商品列表

    //随机出商店可购买的商品数据
    public randomGoodsItems(playerLevel: number) {
        let goods: GoodsInfo[] = [];
        for (let pageData of this.list) {
            let pageIndex = pageData.pageIndex;
            let randomCount = pageData.viewCount;
            pageData.items = pageData.items.filter(obj => { return (obj.levelLimitMin == 0 && obj.levelLimitMax == 0) || (obj.levelLimitMin <= playerLevel && obj.levelLimitMax >= playerLevel) });

            if (pageData.items.length > randomCount) {
                pageData.items = this.randomGoods(pageData.items, randomCount);
            }
            for (let item of pageData.items) {
                goods.push({
                    pageIndex: pageIndex,
                    id: item.id
                })
            }
        }
        return goods;
    }

    //根据权重随机物品
    public randomGoods(allGoodsArray: RefreshShopItem[], maxNum: number) {
        let maxCount = 100;//防止策划数值填错...出现过这个情况
        let goodsArray = [];
        while ((goodsArray.length < maxNum) && (allGoodsArray.length > 0) && (maxCount >= 0)) {
            let totalWeight = allGoodsArray.reduce((pre, cur) => {
                return pre + cur.weight || 1;
            }, 0);
            let random = Math.floor(totalWeight * Math.random());
            for (let index = 0; index < allGoodsArray.length; index++) {
                random -= allGoodsArray[index].weight;
                if (random < 0) {
                    let rmObj = allGoodsArray.splice(index, 1)
                    goodsArray.push(rmObj[0]);
                    break;
                }
            }
            maxCount--;
        }
        return goodsArray;
    }

    public findItemByProductID(productID: string): RefreshShopItem {
        for (let pageData of this.list) {
            let index = pageData.items.findIndex(obj => { return obj && obj.productID === productID });
            if (index != -1) {
                return pageData.items[index]
            }
        }
        return null;
    }

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

    //解析玩家购买记录
    public setPlayerRecords(data: ActivityRefreshShopModelType) {
        if (!data) {
            return;
        }
        for (let pageData of this.list) {
            for (let item of pageData.items) {
                item.setBuyRecords(data);
            }
        }

        let goods = data.goods ? data.goods : [];
        for (let pageData of this.list) {
            pageData.items = pageData.items.filter(item => {
                let index = goods.findIndex(obj => { return obj.pageIndex == pageData.pageIndex && obj.id == item.id });
                return (index != -1);
            })
        }

    }


    public initData(data: string) {
        // this.nextRefreshTime = this.endTime;
        let dataObj: RefreshShopDataInDb = JSON.parse(data);
        this.shopType = dataObj.shopType;
        this.name = dataObj.name;
        let arr = dataObj.data;
        for (let obj of arr) {
            this.list.push(new RefreshShopPage(obj))
        }
    }

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