import { pick, random } from 'underscore';
import { ActivityModelType } from '../../db/Activity';
import { ActivityTreasureHuntShopModelType } from '../../db/ActivityTreasureHuntShop';
import { ActivityTreasureHuntTaskModelType } from '../../db/ActivityTreasureHuntTask';
import { ActivityTreasureHuntTreasureShopModelType } from '../../db/ActivityTreasureHuntTreasureShop';
import { ActivityTreasureHuntFirstPageModelType } from '../../db/ActivityTreasureHuntFirstPage';
import { parseNumberList, splitString } from '../../pubUtils/util';
import { ActivityBase } from './activityField';
import { ActivityTreasureHuntChallengeModelTypeParam } from '../../db/ActivityTreasureHuntChallenge';
import { TREASURE_HUNT_DATA_TYPE } from '../../consts';

// 首页
interface TreasureHuntFirstPageInDb {
    index: TREASURE_HUNT_DATA_TYPE.FIRST_PAGE;
    name: string;      // 页签名
    reward: string;    // 奖励
    imageName: string; // 图片
}

// 商店
interface TreasureHuntShopItemConsumeInDb {
    count: number,     // 第几次
    consume: string,   // 消耗 type&id&count
    discount: number,  // 折扣
}

interface TreasureHuntShopItemInDb {
    cellIndex: number;     // 第几项
    name: string;          // 礼包名
    productID: string;     // 商品id
    price: number;         // 价格  
    countMax: number;      // 限购数量
    discount: number;      // 折扣
    reward: string;        // 奖励
    imageName: string;     // 图片
    data: TreasureHuntShopItemConsumeInDb[];  // 消耗
}

interface TreasureHuntShopInDb {
    index: TREASURE_HUNT_DATA_TYPE.SHOP;                // 2. 每日物资，即商店
    name: string;            // 页签名
    data: TreasureHuntShopItemInDb[];
}

// 任务
interface TreasureHuntTaskItemInDb {
    cellIndex: number;    // 第几项
    name: string;         // 任务名
    taskType: number;     // 任务类型
    taskParam: string;    // 任务参数
    condition: number;    // 条件
    reward: string;       // 奖励 type&id&count
    fragment: number;    // 前端显示 碎片数量
    skip: string;         // 前端用 跳转
}

interface TreasureHuntTaskInDb {
    index: TREASURE_HUNT_DATA_TYPE.TASK;                // 3. 任务
    name: string;            // 页签名
    reward: string;          // 奖励 type&id&count
    data: TreasureHuntTaskItemInDb[]; // 任务
}

// 关卡
interface TreasureHuntChallengeInDb {
    index: TREASURE_HUNT_DATA_TYPE.CHALLENGE;               // 4. 关卡
    name: string;            // 页签名
    consume: string;         // 消耗
    warid: string;           // 关卡
    fixReward: string;       // 奖励 type&id&count
    jackpotReward: string;   // 随机奖励
    imageName: string;       // 图标 
}

// 高级商店
interface TreasureHuntTreasureShopItemInDb {
    cellIndex: number;     // 第几项
    name: string;          // 礼包名
    reward: string;        // 奖励
    countMax: number;      // 限购数量
    imageName: string;     // 图片
    consume: string;      // 消耗
}
interface TreasureHuntTreasureShopInDb {
    index: TREASURE_HUNT_DATA_TYPE.TREASURE_SHOP;               // 4. 关卡
    name: string;            // 页签名
    data: TreasureHuntTreasureShopItemInDb[];         // 消耗
}
interface TreasureHuntInDb {
    data: (TreasureHuntFirstPageInDb|TreasureHuntShopInDb|TreasureHuntTaskInDb|TreasureHuntChallengeInDb|TreasureHuntTreasureShopInDb)[];
}


/************************************************************/
// 操作数据
// 进入活动首页的数据
export class TreasureHuntFirstPageData {
    index: number;         //下标
    name: string;          //页签名字
    reward: string;        //奖励
    imageName: string;

    isReceive: boolean = false;//是否领取

    constructor(data: TreasureHuntFirstPageInDb) {
        this.initData(data)
    }

    public initData(data: TreasureHuntFirstPageInDb) {
        this.name = data.name;
        this.index = data.index;
        this.reward = data.reward;
        this.imageName = data.imageName;
    }

    public setPlayerFirstPageRecord(record: ActivityTreasureHuntFirstPageModelType) {
        if (!record) return;
        this.isReceive = !!record.isReceive;
    }
}

//购买价格
export class ConsumeData {
    count: number;       // 第几次购买，1开始
    consume: string;            //消耗资源 "2&31002&400"
    discount: number;       // 折扣

    constructor(data: TreasureHuntShopItemConsumeInDb) {
        this.count = data.count;
        this.consume = data.consume;
        this.discount = data.discount;
    }
}

// 商品的数据
export class TreasureHuntShopItem {
    cellIndex: number;       // 第几个，从1开始
    name: string;            //名称
    price: number;          // 价格RMB 每次购买价格不变
    productID: string;      // 商品id
    reward: string;         //奖励
    countMax: number;      //最大购买次数
    discount: number;      //折扣
    imageName: string;
    consume: ConsumeData[] = [];    //每次购买价格不同

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

    constructor(data: TreasureHuntShopItemInDb) {
        this.cellIndex = data.cellIndex;
        this.name = data.name;
        this.price = data.price;
        this.productID = data.productID;
        this.reward = data.reward;
        this.countMax = data.countMax;
        this.discount = data.discount;
        this.imageName = data.imageName;
        for (let obj of data.data) {
            this.consume.push(new ConsumeData(obj))
        }
    }

    public getConsume(count: number) {
        let consumes: string[] = [];
        for(let cnt = 1; cnt <= count; cnt ++) {
            let index = this.consume.findIndex(obj => { return obj && obj.count === this.buyCount + cnt });
            if (index != -1) consumes.push(this.consume[index].consume);
        }
        return consumes;
    }

    public setBuyCount(record: ActivityTreasureHuntShopModelType) {
        if (!record) return;
        let buyRecords = record.records.filter(obj => { return obj.id === this.cellIndex });
        this.buyCount = buyRecords.length;
    }
}

// 商店数据
export class TreasureHuntShopData {
    index: number;                 //下标
    name: string;                  //页签名字
    list: TreasureHuntShopItem[] = [];//商品

    constructor(data: TreasureHuntShopInDb) {
        this.initData(data)
    }

    public initData(data: TreasureHuntShopInDb) {
        this.index = data.index;
        this.name = data.name;
        let arr = data.data;
        for (let obj of arr) {
            this.list.push(new TreasureHuntShopItem(obj))
        }
    }

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

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

    public setPlayerShopRecords(record: ActivityTreasureHuntShopModelType) {
        if (!record) {
            return;
        }
        for (let item of this.list) {
            item.setBuyCount(record);
        }
    }
}

/************************************************************/

// 寻宝备战的数据
export class TreasureHuntTaskItem {
    cellIndex: number;       // 第几个，从1开始
    name: string;            //名称
    taskType: number;          // 任务类型
    taskParam: string;      // 任务参数
    condition: number;      //任务条件数据
    reward: string;         //奖励
    fragment: number;      //碎片
    skip: string;

    taskParamArray: number[] = [];      // 任务参数
    totalCount: number = 0;          //任务统计
    isReceive: boolean = false;       //是否领取奖励

    constructor(data: TreasureHuntTaskItemInDb) {
        this.cellIndex = data.cellIndex;
        this.name = data.name;
        this.taskType = data.taskType;
        this.taskParam = data.taskParam;
        this.taskParamArray = parseNumberList(data.taskParam);
        this.condition = data.condition;
        this.reward = data.reward;
        this.fragment = data.fragment;
        this.skip = data.skip;
    }

    setPlayerRecord(record: ActivityTreasureHuntTaskModelType) {
        if(!record) return;
        this.totalCount = record.totalCount||0;
        this.isReceive = record.receiveRewardCount ? true : false;
    }

    public getShowResult() {
        return pick(this, ['cellIndex', 'name', 'taskType', 'condition', 'reward', 'fragment', 'skip', 'totalCount', 'isReceive'])
    }
}

// 寻宝备战数据
export class TreasureHuntTaskData {
    name: string;            //页签名字
    index: number;           //下标
    reward: string;          //奖励
    list: TreasureHuntTaskItem[] = [];//任务

    constructor(data: TreasureHuntTaskInDb) {
        this.initData(data)
    }

    public initData(data: TreasureHuntTaskInDb) {
        this.name = data.name;
        this.index = data.index;
        this.reward = data.reward;
        let arr = data.data||[];
        for (let obj of arr) {
            this.list.push(new TreasureHuntTaskItem(obj))
        }
    }

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

    public setPlayerTaskRecords(records: ActivityTreasureHuntTaskModelType[]) {
        for(let record of records) {
            let item = this.getItem(record.cellIndex);
            if(item) item.setPlayerRecord(record);
        }
    }

    public findItemByTaskType(type: number) {
        return this.list.filter(obj => { return obj && obj.taskType === type });
    }

    public getShowResult() {
        return {
            ...this, list: this.list.map(item => item.getShowResult())
        }
    }
}

/************************************************************/

// 寻宝大冒险的数据
export class TreasureHuntChallengeData {
    name: string;         // 页签名字
    index: number;        // 下标
    consume: string;      // 消耗
    warid: string;        // 随机的关卡号
    fixReward: string;    // 客户端显示奖励
    jackpotReward: string;// 客户端显示奖励
    imageName: string;

    resultWarId: number = 0;  // 玩家随机出的关卡id

    constructor(data: TreasureHuntChallengeInDb) {
        this.initData(data)
    }

    public initData(data: TreasureHuntChallengeInDb) {
        this.name = data.name;
        this.index = data.index;
        this.consume = data.consume;
        this.warid = data.warid;
        this.fixReward = data.fixReward;
        this.jackpotReward = data.jackpotReward;
        this.imageName = data.imageName;
    }

    public randomGK() {
        let gkArray = splitString(this.warid, '&');
        let index = random(gkArray.length - 1);
        return gkArray[index];
    }

    public setChallengeRecord(record: ActivityTreasureHuntChallengeModelTypeParam) {
        if(record) {
            this.resultWarId = record.warId;
        }
    }
}


/************************************************************/

//天子宝库
// 商品的数据
export class TreasureHuntTreasureShopItem {
    cellIndex: number;         // 第几个，从1开始
    name: string;              //名称
    reward: string;            //奖励
    countMax: number;           //最大购买次数
    imageName: string;
    consume: string;               //购买价格

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

    constructor(data: TreasureHuntTreasureShopItemInDb) {
        this.cellIndex = data.cellIndex;
        this.name = data.name;
        this.reward = data.reward;
        this.countMax = data.countMax;
        this.imageName = data.imageName;
        this.consume = data.consume;
    }

    setPlayerRecord(record: ActivityTreasureHuntTreasureShopModelType) {
        let buyRecords = record.records.filter(obj => { return obj.id === this.cellIndex });
        this.buyCount = buyRecords.length;
    }
}

// 天子宝库商店数据
export class TreasureHuntTreasureShopData {
    index: number;//下标
    name: string;//页签名字
    list: TreasureHuntTreasureShopItem[] = [];//商品

    constructor(data: TreasureHuntTreasureShopInDb) {
        this.initData(data)
    }

    public initData(data: TreasureHuntTreasureShopInDb) {
        this.index = data.index;
        this.name = data.name;
        let arr = data.data||[];
        for (let obj of arr) {
            this.list.push(new TreasureHuntTreasureShopItem(obj))
        }
    }

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

    public setPlayerTreasureShopRecords(record: ActivityTreasureHuntTreasureShopModelType) {
        if (!record) {
            return;
        }
        for (let item of this.list) {
            item.setPlayerRecord(record);
        }
    }

}

/************************************************************/

// 寻宝骑兵活动数据
export class TreasureHuntData extends ActivityBase {
    firstPage: TreasureHuntFirstPageData = null;//首页奖励
    shop: TreasureHuntShopData = null; //每日物资
    tasks: TreasureHuntTaskData = null; //寻宝备战
    challenge: TreasureHuntChallengeData = null;//寻宝大冒险
    treasureShop: TreasureHuntTreasureShopData = null; //天子宝库（商店）

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

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

        let arr = dataObj.data||[];
        arr.forEach(data => {
            switch(data.index) {
                case 1:
                    this.firstPage = new TreasureHuntFirstPageData(<TreasureHuntFirstPageInDb>data); break;
                case 2:
                    this.shop = new TreasureHuntShopData(<TreasureHuntShopInDb>data); break;
                case 3:
                    this.tasks = new TreasureHuntTaskData(<TreasureHuntTaskInDb>data); break;
                case 4:
                    this.challenge = new TreasureHuntChallengeData(<TreasureHuntChallengeInDb>data); break;
                case 5:
                    this.treasureShop = new TreasureHuntTreasureShopData(<TreasureHuntTreasureShopInDb>data); break;
            }
        });
    }

    public getShowResult() {
        return {
            ...this,
            tasks: this.tasks.getShowResult()
        }
    }
}