import { GIFT_PACKAGE_TYPE, ACTIVITY_RESOURCES_TYPE } from '../../consts';
import { gameData } from '../../pubUtils/data';
import { addItems, createHeroes } from './../rewardService';
import { RewardParam } from '../../domain/activityField/rewardField';
import { CreateHeroParam } from '../../domain/roleField/hero';
import { DicGiftPackage } from '../../pubUtils/dictionary/DicGiftPackage';
import { ItemInter, RewardInter } from '../../pubUtils/interface';
import { decodeArrayListStr } from '../../pubUtils/util';



/**
 * 兑换礼包
 * @param giftID 礼包id
 * @param roleId 角色id
 * @param roleName 角色名称
 * @param giftCount 一共消耗多少个礼包
 * @param sid 
 */
export async function useGiftPackage(roleId: string, roleName: string, sid: string, serverId: number, giftID: number, selected: Array<number> = [], giftCount: number) {
    console.log("bbbbbbbb", giftID, selected)
    let result = { goods: [], addHeros: [] }
    let giftPackageData = gameData.giftPackage.get(giftID);
    if (!giftPackageData) {
        return result
    }
    console.log('dddddddddddddd', giftID, JSON.stringify(giftPackageData))
    let giftType = giftPackageData.type;//礼包类型
    let reward = giftPackageData.reward;//奖励内容,数组
    switch (giftType) {
        case GIFT_PACKAGE_TYPE.ALL://全部
            {
                let allReward = [];
                if (giftCount > 1) {
                    for (let obj of reward) {
                        allReward.push({ type: obj.type, id: obj.id, count: obj.count * giftCount })
                    }
                } else {
                    allReward = reward;
                }

                result = await addReward(roleId, roleName, sid, serverId, allReward);
                break;
            }
        case GIFT_PACKAGE_TYPE.SELECTED_X://手选
            {
                let count = giftPackageData.count;//选择个数
                if (selected.length != count) {
                    break;
                }
                let selectedReward = getSelectedReward(giftPackageData, selected)
                let allReward = [];
                if (giftCount > 1) {
                    for (let obj of selectedReward) {
                        allReward.push({ type: obj.type, id: obj.id, count: obj.count * giftCount })
                    }
                } else {
                    allReward = selectedReward;
                }
                result = await addReward(roleId, roleName, sid, serverId, allReward);
                break;
            }
        case GIFT_PACKAGE_TYPE.RANDOM_X://随机
            {
                let count = giftPackageData.count;//随机个数
                let allReward = [];
                for (let i = 0; i < giftCount; i++) {
                    let selectedArray = randomSelectedData(giftPackageData.reward.length, count);
                    let selectedReward = getSelectedReward(giftPackageData, selectedArray)
                    allReward = allReward.concat(selectedReward);
                }
                result = await addReward(roleId, roleName, sid, serverId, allReward);
                break;
            }
        default:
            break;
    }

    return result;
}

//结算奖励的内容
export async function addReward(roleId: string, roleName: string, sid: string, serverId: number, reward: Array<RewardParam>) {
    let giftReward = rewardItemData(reward);
    let goodArray = giftReward.goods;
    let heroArray = giftReward.heroes;

    //兑换物品
    let goods = await addItems(roleId, roleName, sid, goodArray)
    let addHeros = [];
    if (heroArray.length > 0) {
        let heroResult = await createHeroes(roleId, roleName, sid, serverId, heroArray);
        goods = goods.concat(heroResult.goods)
        addHeros = addHeros.concat(heroResult.heroes);
    }

    let newGoods: RewardInter[] = [];
    for (let item of goods) {
        let index = newGoods.findIndex(obj => { return obj.id == item.id });
        if (index != -1) {
            newGoods[index].count += item.count;
        } else {
            newGoods.push({ id: item.id, count: item.count })
        }
    }

    return { goods: newGoods, addHeros }
}

//表中的奖励数据(包括礼包)转换成具体对应奖励物品的实例
function rewardItemData(reward: Array<RewardParam>) {
    let goods: Array<RewardInter> = [];
    let heroes: Array<CreateHeroParam> = [];
    for (let obj of reward) {
        switch (obj.type) {
            case ACTIVITY_RESOURCES_TYPE.HERO:
                heroes.push({ hid: obj.id, count: obj.count })
                break;
            case ACTIVITY_RESOURCES_TYPE.GOODS:
                goods.push({ id: obj.id, count: obj.count })
                break;
            case ACTIVITY_RESOURCES_TYPE.GIFTPACKAGE://配置成礼包会立刻兑换，配置成物品会把礼包放入背包中
                let goodData = gameData.goods.get(obj.id);//礼包物品
                let giftPackageData = gameData.giftPackage.get(1)//gameData.giftPackage.get(goodData.gift);//礼包数据
                let giftReward = rewardItemData(giftPackageData.reward)
                goods = goods.concat(giftReward.goods)
                heroes = heroes.concat(giftReward.heroes)
                break;
            default:
                break;
        }
    }
    return { goods, heroes }
}

export function getSelectedReward(giftData: DicGiftPackage, selected: Array<number>): Array<RewardParam> {
    console.log('bbbbbbbbbbbbbbbbbbb', JSON.stringify(selected), JSON.stringify(giftData))

    let selectedReward: Array<RewardParam> = [];
    for (let i = 0; i < selected.length; i++) {
        let index = selected[i];
        if (giftData.reward.length > index) {
            selectedReward.push(giftData.reward[index]);
        }
    }
    return selectedReward;
}

function randomSelectedData(total: number, count: number) {
    var selected: number[] = [];    //temp存放生成的随机数组
    var arr = Array.from({ length: total }, (v, k) => k);
    for (let i = 0; i < count; i++) {
        var num = Math.floor(Math.random() * arr.length); //生成随机数num
        selected.push(arr[num]);    //获取arr[num]并放入temp
        arr.splice(num, 1);
    }
    return selected;
}

//数据格式转换'类型&id&数量|类型&id&数量|' ->> Array<RewardParam> 活动奖励
export function stringToRewardParam(rewardStr: string): Array<RewardParam> {
    let result = new Array<{ type: number, id: number, count: number }>();
    if (!rewardStr) return result;
    let decodeArr = decodeArrayListStr(rewardStr);
    for (let [type, id, count] of decodeArr) {
        if (isNaN(parseInt(type)) || isNaN(parseInt(id)) || isNaN(parseInt(count))) {
            throw new Error('data table format wrong');
        }
        result.push({ type: parseInt(type), id: parseInt(id), count: parseInt(count) });
    }
    return result
}

//数据格式转换'类型&id&数量|类型&id&数量|' ->> Array<ItemInter> 资源消耗
export function stringToConsumeParam(rewardStr: string): Array<ItemInter> {
    let result = new Array<{ type: number, id: number, count: number }>();
    if (!rewardStr) return result;
    let decodeArr = decodeArrayListStr(rewardStr);
    for (let [type, id, count] of decodeArr) {
        if (isNaN(parseInt(type)) || isNaN(parseInt(id)) || isNaN(parseInt(count))) {
            throw new Error('data table format wrong');
        }
        result.push({ type: parseInt(type), id: parseInt(id), count: parseInt(count) });
    }
    return result
}

//数据格式转换'id&数量|id&数量|' ->> Array<RewardInter> 老资源格式
export function stringToRewardInter(rewardStr: string): Array<RewardInter> {
    let result = new Array<{ id: number, count: number }>();
    if (!rewardStr) return result;
    let decodeArr = decodeArrayListStr(rewardStr);
    for (let [type, id, count] of decodeArr) {
        if (isNaN(parseInt(id)) || isNaN(parseInt(count))) {
            throw new Error('data table format wrong');
        }
        result.push({ id: parseInt(id), count: parseInt(count) });
    }
    return result
}

