import { dicHero, dicMyHeroes, loadHero } from "./dictionary/DicHero";
import { dicGoods, blueprt, dicJewel, figureCondition, loadGoods } from "./dictionary/DicGoods";
import { dicBlueprtCompose, loadBlueprtCompose } from "./dictionary/DicBlueprtCompose";
import { dicBlueprtPossibility, loadBlueprtPossibility } from "./dictionary/DicBlueprtPossibility";
import { dicDaily, loadDaily } from "./dictionary/DicDaily";
import { dicEvent, dicEventList, loadEvent } from "./dictionary/DicEvent";
import { dicExpedition, DicExpedition, loadExpedition } from "./dictionary/DicExpedition";
import { dicExpeditionPoint, loadExpeditionPoint } from "./dictionary/DicExpeditionPoint";
import { dicFuncSwitch, loadFuncSwitch } from "./dictionary/DicFuncSwitch";
import { dicHeroSkill, loadHeroSkill } from "./dictionary/DicHeroSkill";
import { dicJob, jobClassAndgrades, jobClassMaxGrades, loadJob } from "./dictionary/DicJob";
import { dicKingExp, maxPlayerLv, loadKingExp } from "./dictionary/DicKingExp";
import { dicCharExp, loadCharExp } from "./dictionary/DicCharExp";
import { dicQuestion, loadQuestion } from "./dictionary/DicQuestion";
import { dicSe, loadSe } from "./dictionary/DicSe";
import { dicTower, loadTower } from "./dictionary/DicTower";
import { dicTowerTask, loadTowerTask } from "./dictionary/DicTowerTask";
import { dicWar, dicWarPvp, dicDailyWarByType, loadWar } from "./dictionary/DicWar";
import { dicWarJson, loadWarJson } from "./dictionary/DicWarJson";
import { dicXunbao, loadXunbao } from "./dictionary/DicXunbao";
import { AUCTION_TIME, SPECIAL_ATTR } from "../consts";
import { dicFashions, dicFashionsByHeroId, loadFashions } from "./dictionary/DicFashions";
import { friendShips, friendShipHidAandIds, loadFriendShip } from "./dictionary/DicFriendShip";
import { maxFriendShipLv, dicFriendShipLevelMap, loadFriendShipLevel } from "./dictionary/DicFriendShipLevel";
import { dicHeroQualityUp, loadHeroQualityUp } from "./dictionary/DicHeroQualityUp";
import { dicHeroStar, loadHeroStar } from "./dictionary/DicHeroStar";
import { dicHeroWake, loadHeroWake } from "./dictionary/DicHeroWake";
import { dicRandomEffectPool, loadRandomEffectPool } from './dictionary/DicRandomEffectPool';
import { dicStrengthenCost, loadStrengthenCost } from './dictionary/DicStrengthenCost';
import { dicRefine, loadRefine } from './dictionary/DicRefine';
import { dicHeroEquip, loadHeroEquip } from './dictionary/DicHeroEquip';
import { dicSuit, dicSuitByTypeAndLv, loadSuit } from './dictionary/DicSuit';
import { dicTitle, loadTitle } from './dictionary/DicTitle';
import { dicTeraph, loadTeraph } from './dictionary/DicTeraph';
import { dicSchool, loadSchool } from './dictionary/DicSchool';
import { dicSchoolRate, loadSchoolRate } from './dictionary/DicSchoolRate';
import { dicHeroScroll, preHeroScroll, loadHeroScroll } from './dictionary/DicHeroScroll';
import { dicPvpOpponent, loadPvpOpponent } from './dictionary/DicPvpOpponent';
import { dicPvpTeamLevel, loadPvpTeamLevel } from './dictionary/DicPvpTeamLevel';
import { dicPvpRefreshConsume, maxPvpRefreshCnt, loadPvpRefreshConsume } from './dictionary/DicPvpRefreshConsume';
import { dicHeroRewads, loadPvpHeroReward } from './dictionary/DicPvpHeroReward';
import { dicRankRewads, dicRankMax, loadPvpRankReward } from './dictionary/DicPvpRankReward';
import { dicPvpBoxs, loadPvpBox } from './dictionary/DicPvpBox';
import { dicGuildAuth, loadGuildAuth } from './dictionary/DicGuildAuth';
import { dicCenterBase, dicEquipPriduceBase, dicBossBase, dicTrainBase, dicDonateBase, dicWishPoolBase, dicStoreBase, dicStructureConsume, dicBossBaseByBossLv, loadStructure } from "./dictionary/DicStructure";
import { dicGuildActiveDayReward, loadGuildActiveDayReward } from './dictionary/DicGuildActiveDayReward';
import { dicGuildActiveWeekReward, loadGuildActiveWeekReward } from './dictionary/DicGuildActiveWeekReward';
import { dicGuildActiveWays, loadGuildActiveWays } from './dictionary/DicGuildActiveWays';
import { dicGuildPosition, loadGuildPosition } from "./dictionary/DicGuildPosition";
import { dicMail, loadMail } from "./dictionary/DicMail";
import { dicArmyTrainJuDian, loadArmyTrainJuDian, dicLastGuildTrainIdOfLv, dicFirstGuildTrainIdOfLv } from './dictionary/DicArmyTrainJuDian';
import { dicTrainSoloReward, loadTrainSoloReward } from './dictionary/DicTrainSoloReward';
import { RewardInter } from "./interface";
import { dicArmyDevelopConsume, loadArmyDevelopConsume } from './dictionary/DicArmyDevelopConsume';
import { dicArmyBossRank, loadArmyBossRank } from './dictionary/DicArmyBossRank';
import { dicArmyDonate, loadArmyDonate } from './dictionary/DicArmyDonateBoxReward';
import { dicRoleFriend, DicRoleFriend, loadRoleFriend } from "./dictionary/DicRoleFriend";
import { dicRoleFriendLv, loadRoleFriendLv } from "./dictionary/DicRoleFriendLv";
import { AttributeCal } from "../domain/roleField/attribute";
import { dicGuildActivity, DicGuildActivity, loadGuildActivity } from './dictionary/DicGuildActivity';
import { dicGateActivityPoint, loadGateActivityPoint } from './dictionary/DicGateActivityPoint';
import { dicGuildAuction, loadGuildAuction } from './dictionary/DicGuildAuction';
import { getCurDay } from "./timeUtil";
import { dicCityActivity, loadCityActivity } from "./dictionary/DicCityActivity";
import { dicChatAccuse, loadChatAccuse } from "./dictionary/DicChatAccuse";
import { dicCityActivityReward, loadCityActivityReward } from "./dictionary/DicCityActivityReward";
import { dicRaceActivity, dicRaceTypes, loadRaceActivity } from './dictionary/DicRaceActivity';
import { GUILDACTIVITY, RECRUIT } from "./dicParam";
import * as param from "./dicParam";
import { decodeIdCntArrayStr, parseGoodStr, decodeArrayListStr, getRandValueByMinMax, getRandEelm, readTsFile, getRandEelmWithWeight } from "./util";
import { RACE_EVENT_TYPE } from "../consts";
import { dicShop, dicShopItem, loadShop } from "./dictionary/DicShop";
import { dicShopList, loadShopList } from "./dictionary/DicShopList";
import { dicRank, loadRank } from "./dictionary/DicRank";
import { dicRankReward, loadRankReward } from "./dictionary/DicRankReward";
import { dicTaskType, taskMap, dicMainTask, dicDailyTask, dicAchievement, loadTask, dicPvpDailyTask } from "./dictionary/DicTask";
import { dicMainTaskStage, loadMainTaskStage } from "./dictionary/DicMainTaskStage";
import { dicTaskBox, loadTaskBox } from './dictionary/DicTaskBox';
import { dicGacha, loadGacha } from "./dictionary/DicGacha";
import { dicGachaContent, dicGachaContentHero, loadGachaContent } from "./dictionary/DicGachaContent";
import { dicGiftPackage, loadGiftPackage } from "./dictionary/DicGiftPackage";
import { dicRecruit, loadRecruit } from './dictionary/DicRecruit';
import { loadRMB, dicRMB } from './dictionary/DicRMB';
import { dicActivityType, loadActivityType } from './dictionary/DicActivityType';
import { dicTaskTypeDesc, loadTaskType } from './dictionary/DicTaskType';
import { dicServerName, dicServerGroupName, loadServerName } from "./dictionary/DicServerName";
import { dicAp, loadAp, dicApMaxLevel } from './dictionary/DicAp';
import { dicApBuy, dicApMaxBuyTimes, loadApBuy } from "./dictionary/DicApBuy";
import { dicKingExpRatio, loadKingExpRatio } from './dictionary/DicKingExpRatio';
import { dicQuenchByQuality, dicQuenchRangeByQuality, dicQuenchRangeByQualityAndGrade, loadQuenchQuality } from './dictionary/DicQuenchQuality';
import { dicQuenchConsume, loadQuenchConsume } from './dictionary/DicQuenchConsume';
import { dicHoliday, loadHoliday } from './dictionary/DicHoliday';
import { dicExpeditionSubAttr, loadExpeditionSubAttr } from './dictionary/DicExpeditionSubAttr';
import { dicAuctionPool, loadAuctionReward } from './dictionary/DicAuctionReward';
import { dicGuildTrainInfo, loadGuildTrainInfo } from './dictionary/DicGuildTrainInfo';
import { dicPvpDifficultRatio, loadPvpDifficultRatio } from './dictionary/DicPvpDifficultRatio';
import { pick } from "underscore";

export const gameData = {
    blurprtCompose: dicBlueprtCompose,
    blueprtPossibility: dicBlueprtPossibility,
    daily: dicDaily,
    event: dicEvent,
    eventList: dicEventList,
    expedition: dicExpedition,
    expeditionPoint: dicExpeditionPoint,
    funcsSwitch: dicFuncSwitch,
    goods: dicGoods,
    hero: dicHero,
    heroQualityUp: dicHeroQualityUp,
    heroSkill: dicHeroSkill,
    heroStar: dicHeroStar,
    heroWake: dicHeroWake,
    job: dicJob,
    jobClassMaxGrades: jobClassMaxGrades,
    jobClassAndgrades: jobClassAndgrades,
    kingexp: dicKingExp,
    maxPlayerLv: maxPlayerLv,
    charexp: dicCharExp,
    question: dicQuestion,
    se: dicSe,
    tower: dicTower,
    towerTask: dicTowerTask,
    war: dicWar,
    warJson: dicWarJson,
    dailyWarByType: dicDailyWarByType,
    xunbao: dicXunbao,
    btlBossHpSum: new Map<number, number>(),
    btlBossHp: new Map<number, Array<{ dataId: number, hp: number, actorId: number }>>(),
    blueprtToWar: new Map<number, number>(),
    blueprt: blueprt,
    fashion: dicFashions,
    fashionBySkinId: dicFashionsByHeroId,
    friendShips: friendShips,
    friendShipHidAandIds: friendShipHidAandIds,
    maxFriendShipLv: maxFriendShipLv,
    friendShipLevelMap: dicFriendShipLevelMap,
    randomEffectPool: dicRandomEffectPool,
    strengthenCost: dicStrengthenCost,
    refine: dicRefine,
    jewels: dicJewel,
    dicHeroEquip: dicHeroEquip,
    suit: dicSuit,
    suitByTypeAndLv: dicSuitByTypeAndLv,
    title: dicTitle,
    teraphs: dicTeraph,
    school: dicSchool,
    schoolRate: dicSchoolRate,
    heroScroll: dicHeroScroll,
    preHeroScroll: preHeroScroll,
    pvpOpponent: dicPvpOpponent,
    pvpTeamLevel: dicPvpTeamLevel,
    pvpWar: dicWarPvp,
    pvpRefreshConsume: dicPvpRefreshConsume,
    pvpDifficultRatio: dicPvpDifficultRatio,
    maxPvpRefreshCnt: maxPvpRefreshCnt,
    pvpHeroRewards: dicHeroRewads,
    pvpRankRewards: dicRankRewads,
    pvpBoxs: dicPvpBoxs,
    pvpRankMax: dicRankMax,
    guildAuth: dicGuildAuth,
    centerBase: dicCenterBase,
    equipProduceBase: dicEquipPriduceBase,
    bossBase: dicBossBase,
    bossBaseByBossLv: dicBossBaseByBossLv,
    trainBase: dicTrainBase,
    donateBase: dicDonateBase,
    armyWishPool: dicWishPoolBase,
    storeBase: dicStoreBase,
    guildTrainInfo: dicGuildTrainInfo,
    structureConsume: dicStructureConsume,
    guildActiveDayReward: dicGuildActiveDayReward,
    guildActiveWeekReward: dicGuildActiveWeekReward,
    guildPosition: dicGuildPosition,
    armyTrainJuDian: dicArmyTrainJuDian,
    lastGuildTrainIdOfLv: dicLastGuildTrainIdOfLv,
    firstGuildTrainIdOfLv: dicFirstGuildTrainIdOfLv,
    trainSoloReward: dicTrainSoloReward,
    mail: dicMail,
    guildActiveWays: dicGuildActiveWays,
    armyDevelopConsume: dicArmyDevelopConsume,
    armyBossRank: dicArmyBossRank,
    armyDonateBox: dicArmyDonate,
    roleFriend: dicRoleFriend,
    roleFriendLv: dicRoleFriendLv,
    figureCondition: figureCondition,
    guildActivity: dicGuildActivity,
    gateActivityPoint: dicGateActivityPoint,
    guildAuction: dicGuildAuction,
    cityActivity: dicCityActivity,
    chatAccuse: dicChatAccuse,
    cityActivityReward: dicCityActivityReward,
    raceActivityEvents: dicRaceActivity,
    raceTypes: dicRaceTypes,
    raceActivityEncounter: { events: new Map<number, number>(), eventNum: 0 },
    raceNormalItems: new Array<{id: number, min: number, max: number}>(),
    raceEventItems: new Array<{id: number, count: number}>(),
    shop: dicShop,
    shopItem: dicShopItem,
    shopList: dicShopList,
    dicMyHeroes: dicMyHeroes,
    rank: dicRank,
    generalRankReward: dicRankReward,
    taskType: dicTaskType,
    tasks: taskMap,
    mainTask: dicMainTask,
    dailyTask: dicDailyTask,
    achievement: dicAchievement,
    pvpDailyTask: dicPvpDailyTask,
    mainTaskStage: dicMainTaskStage,
    taskBox: dicTaskBox,
    gacha: dicGacha,
    gachaContent: dicGachaContent,
    gachaContentHero: dicGachaContentHero,
    gachaHope: new Array<{id: number, weight: number}>(),
    gachaTurntable: new Array<{quality: number, count: number}>(),
    heroTransPiece: new Map<number, number>(),
    giftPackage: dicGiftPackage,
    comBtlLvRange: new Map<number, {min: number, max: number}>(),
    recruit: dicRecruit,
    rmb: dicRMB,
    activityType: dicActivityType,
    taskTypeDesc: dicTaskTypeDesc,
    serverNames: dicServerName,
    serverGroupNames: dicServerGroupName,
    ap: dicAp,
    apMaxLevel: dicApMaxLevel,
    apBuy: dicApBuy,
    apMaxBuyTimes: dicApMaxBuyTimes,
    kingExpRaio: dicKingExpRatio,
    quenchRangeByQuality: dicQuenchRangeByQuality,
    quenchRangeByQualityAndGrade: dicQuenchRangeByQualityAndGrade,
    quenchConsume: dicQuenchConsume,
    quenchByQuality: dicQuenchByQuality,
    equipAttributeRatio: new Map<number, number>(),
    ceRatio: new Array<{type: number, val: number}>(),
    holiday: dicHoliday,
    expeditionSubAttr: dicExpeditionSubAttr,
    auctionPool: dicAuctionPool,
    auctionTime: new Map<number, { hour: number, minute: number, seconds: number}>()
};

// 在此提供一些原先在gamedata中提供的方法，以便更方便获取gameData数据

/**
 * 根据主公当前经验获得当前等级
 * @param exp 累积经验
 */
export function getLvByExp(exp: number) {
    let curLv = 0;
    let entries = gameData.kingexp.entries();
    for (let [lv, { sum }] of entries) {
        curLv = lv;
        if (exp < sum) break;
    }

    return curLv;
}

/**
 * 根据主公当前等级，获得累积经验，1=> 1级满经验
 * @param lv 等级
 */
export function getExpByLv(lv: number) {
    return gameData.kingexp.get(lv);
}

/**
 * 根据武将当前经验获得当前等级
 * @param exp 累积经验
 */
export function getHeroLvByExp(exp: number) {
    let curLv = 0;
    let entries = gameData.charexp.entries();
    for (let [lv, sum] of entries) {
        curLv = lv;
        if (exp < sum) break;
    }

    return curLv;
}

/**
 * 根据武将当前等级，获得累积经验，1=> 1级满经验
 * @param lv 
 */
export function getHeroExpByLv(lv: number) {
    return gameData.charexp.get(lv);
}

/**
 * 根据武将当前好感获得好感等级
 * @param exp 累积经验
 */
export function getFavourLvByExp(exp: number) {
    let curLv = 0;
    let entries = gameData.friendShipLevelMap.entries();
    for (let [lv, { expSum: sum }] of entries) {
        curLv = lv;
        if (exp < sum) break;
    }

    return curLv;
}

export function getBossHpByWarId(warId: number) {
    let bossHpSum = gameData.btlBossHpSum.get(warId) || 0;
    let bossHpArr = gameData.btlBossHp.get(warId) || [];
    if (!bossHpSum || !bossHpArr) {
        const warInfo = dicWarJson.get(warId);
        if (warInfo && warInfo.length) {
            warInfo.forEach(hero => {
                let { attribute, dataId, relation, actorId } = hero;
                if (relation === 2) {
                    let newAttr = new AttributeCal();
                    newAttr.setByWarJson(attribute, 1);
                    let attrJson = newAttr.getReduceAttributes();

                    const hp = attrJson.hp || 0;
                    if (hp > 0) {
                        bossHpArr.push({ dataId, hp, actorId });
                        bossHpSum += hp;
                    }
                }
            })
            gameData.btlBossHp.set(warId, bossHpArr);
            gameData.btlBossHpSum.set(warId, bossHpSum);
        }
    }
    return { bossHpSum, bossHpArr };
}


export function getWarIdByBlueprtId(blueprtId: number) {
    let warId = gameData.blueprtToWar.get(blueprtId);
    if (!warId) {
        let blueprt = gameData.goods.get(blueprtId);
        if (blueprt) {
            const { specialAttr } = blueprt;
            warId = specialAttr.get(SPECIAL_ATTR.WAR_ID);
            if (warId)
                gameData.blueprtToWar.set(blueprtId, warId);
        }
    }
    return warId;
}

export function getBossHpByBlueprtId(blueprtId: number) {
    let { dispatchJsonId } = getWarByBlueprtId(blueprtId);
    let bossHpInfo = getBossHpByWarId(dispatchJsonId);
    return bossHpInfo;
}

export function getWarByBlueprtId(blueprtId: number) {
    let warId = getWarIdByBlueprtId(blueprtId);
    return gameData.war.get(warId);
}

export function getRewardByBlueprtId(blueprtId: number) {
    let { fixReward, teammateReward } = getWarByBlueprtId(blueprtId);
    return { fixReward, teammateReward };
}

function parseComBtlLvRange() {
    const lvRange = decodeArrayListStr(param.TREASURE.TREASURE_ASSIST_LIMITED);
    lvRange.forEach(range => {
        gameData.comBtlLvRange.set(parseInt(range[0]), { min: parseInt(range[1]), max: parseInt(range[2]) });
    });
}

export function comBtlRanges() {
    return Array.from(gameData.comBtlLvRange.keys());
}


export function getHeroStarByQuality(classType: number, quality: number, star: number) {
    return gameData.heroStar.get(`${classType}_${quality}_${star}`);
}

export function getHeroWakeByQuality(classType: number, quality: number, star: number) {
    return gameData.heroWake.get(`${classType}_${quality}_${star}`);
}

export function getMaxGradeByjobClass(jobClass: number) {
    const job = gameData.jobClassMaxGrades.get(jobClass);
    return job?.jobid;
}

export function getJobByGradeAndClass(jobClass: number, grade: number) {
    return gameData.jobClassAndgrades.get(jobClass + '_' + grade);
}

export function getFriendShipById(shipId: number, level: number) {
    return gameData.friendShips.get(shipId + '_' + level);
}

export function getGoodById(gid: number) {
    return gameData.goods.get(gid);
}

export function getJewelById(gid: number) {
    return gameData.jewels.get(gid);
}

export function getHeroEquipByClassId(classId: number) {
    return gameData.dicHeroEquip.get(classId);
}

export function getHeroJob(jobId: number) {
    const job = gameData.job.get(jobId);
    return job;
}

export function getTitle(titleLv: number) {
    const titleInfo = gameData.title.get(titleLv);
    return titleInfo;
}

export function getTeraph(id: number, grade: number) {
    const teraphInfo = gameData.teraphs.get(id + '_' + grade);
    return teraphInfo;
}

export function getSchoolRateByStar(star: number, colorStar: number, quality: number) {
    const schoolRate = gameData.schoolRate.get(`${star}_${colorStar}_${quality}`);
    return schoolRate;
}

export function getScollByStar(quality: number, star: number, curQuality: number, colorStar: number) {
    const heroScroll = gameData.heroScroll.get(`${quality}_${star}_${curQuality}_${colorStar}`);
    return heroScroll;
}

export function getSuit(id: number) {
    const suitInfo = gameData.suit.get(id);
    return suitInfo;
}

export function getFuncsSwitch(id: number) {
    const funcInfo = gameData.funcsSwitch.get(id);
    return funcInfo;
}

export function getPLvByScore(score: number) {
    let lv = 0;
    for (let { teamLv, topLineupMin, topLineupMax } of gameData.pvpTeamLevel) {
        if (score >= topLineupMin) lv = teamLv;
        if (score < topLineupMax) break;
    }
    return lv;
}

export function getPvpHeroRewardsByScore(score: number) {
    for (let item of gameData.pvpHeroRewards) {
        if ((item.max >= score || item.max == -1) && score >= item.min) {
            return item;
        }
    }
    return null
}

export function getPvpRankRewardsByRank(rankLv: number) {
    for (let item of gameData.pvpRankRewards) {
        if ((item.max >= rankLv || item.max == -1) && rankLv >= item.min) {
            return item;
        }
    }
    return gameData.pvpRankMax.max;
}

export function getPvpBoxs() {
    return gameData.pvpBoxs;
}

export function getResultMaxRank() {
    return gameData.pvpRankMax.max;
}

export function getStructureConsume(structureId: number, level: number) {
    return gameData.structureConsume.get(structureId).get(level);
}

export function hasStructureConsume(structureId: number, level: number) {
    return gameData.structureConsume.get(structureId).has(level);
}

export function getBossByLv(lv: number) {
    return gameData.bossBase.get(lv);
}

export function getArmyTrainJuDian(trainId: number) {
    return gameData.armyTrainJuDian.get(trainId);
}

export function getTrainSoloReward(id: number) {
    return gameData.trainSoloReward.get(id);
}

export function getTrainBaseByLv(lv: number) {
    return gameData.trainBase.get(lv);
}

export function getGuildActiveWeekReward(rank: number) {
    let result = gameData.guildActiveWeekReward.find(cur => {
        let { rankMax, rankMin } = cur;
        return rank >= rankMin && rank <= (rankMax || rankMax == -1);
    });
    let reward = new Array<RewardInter>();
    if (result) reward = result.reward;
    return reward;
}

export function getGuildActiveByIdAndType(id: number, type: number) {
    let dicWay = gameData.guildActiveWays.get(id);
    if (!dicWay) return 0;
    return dicWay.activePoint.get(type.toString());
}
export function getArmyDevelopConsumeById(id: number) {
    let result = gameData.armyDevelopConsume.get(id);
    return result;
}

export function getArmyDevelopConsume() {
    return gameData.armyDevelopConsume;
}

export function getArmyBossRank() {
    return gameData.armyBossRank;
}

export function getArmyDonateBaseByLv(lv: number) {
    return gameData.donateBase.get(lv);
}

export function getArmyDonateBoxBaseById(id: number) {
    return gameData.armyDonateBox.get(id);
}
export function getArmyWishPoolBaseByLv(lv: number) {
    return gameData.armyWishPool.get(lv);
}

export function getFriendLvByExp(exp: number) {
    let resultLv = 1;
    for (let [lv, { sum }] of gameData.roleFriendLv.entries()) {
        resultLv = lv;
        if (exp < sum) break;
    }
    return resultLv;
}

/**
 * 根据主公当前经验获得当前等级
 * @param exp 累积经验
 */
export function getDicFriendByLv(lv: number) {
    let dicFriend: DicRoleFriend;
    let entries = gameData.roleFriend.entries();
    for (let [dicLv, dic] of entries) {
        dicFriend = dic;
        if (lv > dicLv) break;
    }

    return dicFriend;
}


/**
 * @description 获取今天开启的活动的配置
 */
export function getTodayGuildActivity() {
    let today = getCurDay();
    let dic: DicGuildActivity;
    for (let [_id, dicGuildActivity] of gameData.guildActivity) {
        if (dicGuildActivity.openDay.includes(today)) {
            dic = dicGuildActivity;
            break;
        }
    }
    return dic;
}

/**
 * 根据军团活动排名获得奖励
 * @param aid 活动id
 * @param rank 排名
 */
export function getGuildAuctionRewards(aid: number, rank: number) {
    let ranksReward = gameData.guildAuction.get(aid) || [];
    let dic = ranksReward.find(cur => {
        return rank >= cur.min && (rank <= cur.max || cur.max == 0);
    });
    if(dic) {
        return getAuctionRewardByPoolId(dic.rewards);
    } else {
        return []
    }
}

export function getAuctionRewardByPoolId(poolId: number) {
    let pools = gameData.auctionPool.get(poolId);
    let rewards: { goods: RewardInter, basePrice: number, maxPrice: number, sort: number }[] = [];
    for(let { count, basicPool } of pools) {
        let { rewardBasicPool, basePrice, maxPrice, sort } = basicPool
        for(let i = 0; i < count; i++) {
            let result = getRandEelmWithWeight(rewardBasicPool);
            if(result && result.dic) {
                rewards.push({ goods: pick(result.dic, ['id', 'count']), basePrice, maxPrice, sort });
            }
        }
    }
    return rewards;
}

/**
 * 根据军团活动排名获得功勋奖励
 * @param type 城池类型
 * @param guildRank 军团排名
 * @param rank 成员在军团内部排名
 */
export function getCityActivityRewards(type: number, guildRank: number, rank: number) {
    let ranksReward = gameData.cityActivityReward.get(type) || [];
    let dic = ranksReward.find(cur => {
        return cur.guildRank == guildRank && (rank >= cur.min && (rank <= cur.max || cur.max == 0));
    });
    return dic ? dic.honour : 0;
}

function decodeRaceActivityEncounter() {
    let str = GUILDACTIVITY.RACEACTIVITY_ENCOUNTER;
    let map = decodeIdCntArrayStr(str, 1);
    let newMap = new Map<number, number>();
    let eventNum = 0;
    for (let [key, value] of map) {
        if (value == RACE_EVENT_TYPE.EVENT) eventNum++;
        newMap.set(parseInt(key), value);
    }
    gameData.raceActivityEncounter = { events: newMap, eventNum };
}

function decodeRaceNormalItems() {
    let str = GUILDACTIVITY.RACEACTIVITY_NORMAL_ITEMS;

    let result = new Array<{ id: number, min: number, max: number }>();
    if (!str) return result;
    let decodeArr = decodeArrayListStr(str);
    for (let [id, min, max] of decodeArr) {
        if (isNaN(parseInt(id)) || isNaN(parseInt(min)) || isNaN(parseInt(max))) {
            throw new Error('data table format wrong');
        }
        result.push({ id: parseInt(id), min: parseInt(min), max: parseInt(max) });
    }
    gameData.raceNormalItems = result;
}

function decodeRaceEventItems() {
    let str = GUILDACTIVITY.RACEACTIVITY_EVENT_ITEMS || "";
    gameData.raceEventItems = parseGoodStr(str);
}

export function getRaceEventItems() {
    let items = gameData.raceNormalItems;
    let result = new Array<RewardInter>();
    for (let { id, min, max } of items) {
        let count = getRandValueByMinMax(min, max, 0);
        result.push({ id, count });
    }
    return result;
}

// 根据保底类型获得保底数量
export function getDicGachaFloor(id: number) {
    let map = decodeIdCntArrayStr(RECRUIT.RECRUIT_MUST, 1);
    return map.get(id.toString())
}


export function getRandExpedition(cnt = 1) {
    let arr: DicExpedition[] = [];
    for (let [_id, dicExpedition] of gameData.expedition) {
        arr.push(dicExpedition);
    }
    return getRandEelm(arr, cnt);
}

// 抽卡心愿单概率
function getGachaHopePercent() {
    let arr = decodeArrayListStr(RECRUIT.RECRUIT_WISH_LIST);
    gameData.gachaHope = arr.map(cur => {
        return { id: parseInt(cur[0]), weight: parseInt(cur[1]) }
    });
}

// 抽卡转盘概率
function getGachaTurntablePercent() {
    let arr = decodeArrayListStr(RECRUIT.RECRUIT_BONUS_HERO_QUANTITY);
    gameData.gachaTurntable = arr.map(cur => {
        return { quality: parseInt(cur[0]), count: parseInt(cur[1]) }
    });
}

function getHeroTransPiece() {
    let map = decodeIdCntArrayStr(RECRUIT.RECRUIT_CHANGE_SHARD, 1);
    let newMap = new Map<number, number>();
    for (let [id, count] of map) {
        newMap.set(parseInt(id), count);
    }
    gameData.heroTransPiece = newMap
}

function getCeRatio() {
    let arr = decodeArrayListStr(param.ATTRIBUTE.ATTRIBUTE_POWER);
    gameData.ceRatio = arr.map(cur => {
        return { type: parseInt(cur[0]), val: parseFloat(cur[1]) }
    });
}


// 根据groupId获得当前大区名
export function getServerGroupName(groupId: number) {
    let name = gameData.serverGroupNames.get(groupId);
    if(!name) {
        let maxId = 0;
        gameData.serverGroupNames.forEach((gname, id) => {
            if(id > maxId) {
                maxId = id;
                name = gname;
            }
        })
    }
    return name;
}

// 根据服务器id获得当前大区名
export function getServerName(id: number) {
    let name = gameData.serverNames.get(id);
    if(!name) {
        let maxId = 0;
        gameData.serverNames.forEach((sname, id) => {
            if(id > maxId) {
                maxId = id;
                name = sname;
            }
        })
    }
    return name;
}

export function getDicApByLv(level: number) {
    if(level > gameData.apMaxLevel.max) {
        return gameData.ap.get(gameData.apMaxLevel.max);
    } else {
        return gameData.ap.get(level);
    }
}

export function getDicSuitByTypeAndLv(suitType: number, starLevel: number) {
    return gameData.suitByTypeAndLv.get(`${suitType}_${starLevel}`);
}

export function getQuenchGradeByValue(quality: number, value: number) {
    
    let dicQuench = gameData.quenchByQuality.get(quality)||[];
    let grade = 0;
    for(let [_grade, { singleRatioMin, singleRatioMax }] of dicQuench) {
        if((value >= singleRatioMin && value < singleRatioMax) || (value == singleRatioMin && value == singleRatioMax) ) {
            grade = _grade;
        }
    }
    return grade;
}

/**
 * 根绝品质和品相获得上下限，当grade为0，获取该品质下全阶的上下限
 * @param quality 品质
 * @param grade 品相
 * @returns {{ min: number, max: number }}
 */
export function getQuenchByQualityAndGrade(quality: number, grade: number) {
    if(grade == 0) { // 这个品质的上下限
        return gameData.quenchRangeByQuality.get(quality);
    } else { // 该品质该品相的上下限
        return gameData.quenchRangeByQualityAndGrade.get(`${quality}_${grade}`);
    }
}

export function getQuenchConsume(lvLimited: number, quality: number) {
    return gameData.quenchConsume.get(`${lvLimited}_${quality}`);
}

/**
 * 根据TrainJuDian的id和武将id，获得信息（包括多个难度）
 * @param trainId 据点id
 * @param heroId 武将id
 */
export function getGuildTrainGkInfo(trainId: number, heroId: number) {
    return gameData.guildTrainInfo.get(`${trainId}_${heroId}`);
}

export function getPvpDifficultByScore(score: number) {
    for(let obj of gameData.pvpDifficultRatio) {
        if(obj.teamLineupMin <= score && (obj.teamLineupMax >= score || obj.teamLineupMax == -1)) {
            return obj;
        }
    }
    return null;
}

function loadEquipAttributeRatio() {
    let arr = decodeArrayListStr(param.ATTRIBUTE.ATTRIBUTE_EQUIP_RATIO);
    for(let [id, ratio] of arr) {
        gameData.equipAttributeRatio.set(parseInt(id), parseInt(ratio));
    }
}

function loadAuctionTime() {
    gameData.auctionTime.set(AUCTION_TIME.GUILD_PREVIEW, splitTime(param.AUCTION.GUILD_AUCTION_PREVIEW_TIME));
    gameData.auctionTime.set(AUCTION_TIME.GUILD_OPEN, splitTime(param.AUCTION.GUILD_AUCTION_OPEN_TIME));
    gameData.auctionTime.set(AUCTION_TIME.GUILD_CLOSE, splitTime(param.AUCTION.GUILD_AUCTION_CLOSE_TIME));
    gameData.auctionTime.set(AUCTION_TIME.WORLD_PREVIEW, splitTime(param.AUCTION.WORLD_AUCTION_PREVIEW_TIME));
    gameData.auctionTime.set(AUCTION_TIME.WORLD_OPEN, splitTime(param.AUCTION.WORLD_AUCTION_OPEN_TIME));
    gameData.auctionTime.set(AUCTION_TIME.WORLD_CLOSE, splitTime(param.AUCTION.WORLD_AUCTION_CLOSE_TIME));
}

function splitTime(str: string) {
    let arr = str.split(':');
    return { hour: parseInt(arr[0]), minute: parseInt(arr[1]), seconds: parseInt(arr[2]) }
}

// 初始加载
function initDatas() {
    parseDicParam();
    loadDatas();
}

// 解析一部分dicParam的数据
function parseDicParam() {
    decodeRaceActivityEncounter();
    decodeRaceNormalItems();
    decodeRaceEventItems();
    getGachaHopePercent();
    getGachaTurntablePercent();
    getHeroTransPiece();
    parseComBtlLvRange();
    getCeRatio();
    loadAuctionTime();
}

// 加载json
function loadDatas() {
    loadHero();
    loadGoods();
    loadBlueprtCompose();
    loadBlueprtPossibility();
    loadDaily();
    loadEvent();
    loadExpedition();
    loadExpeditionPoint();
    loadFuncSwitch();
    loadHeroSkill();
    loadJob();
    loadKingExp();
    loadCharExp();
    loadQuestion();
    loadSe();
    loadTower();
    loadTowerTask();
    loadWar();
    loadWarJson();
    loadXunbao();
    loadFashions();
    loadFriendShip();
    loadFriendShipLevel();
    loadHeroQualityUp();
    loadHeroStar();
    loadHeroWake();
    loadRandomEffectPool();
    loadStrengthenCost();
    loadRefine();
    loadHeroEquip();
    loadSuit();
    loadTitle();
    loadTeraph();
    loadSchool();
    loadSchoolRate();
    loadHeroScroll();
    loadPvpOpponent();
    loadPvpTeamLevel();
    loadPvpRefreshConsume();
    loadPvpHeroReward();
    loadPvpRankReward();
    loadPvpBox();
    loadGuildAuth();
    loadStructure();
    loadGuildActiveDayReward();
    loadGuildActiveWeekReward();
    loadGuildActiveWays();
    loadGuildPosition();
    loadMail();
    loadArmyTrainJuDian();
    loadTrainSoloReward();
    loadArmyDevelopConsume();
    loadArmyBossRank();
    loadArmyDonate();
    loadRoleFriend();
    loadRoleFriendLv();
    loadGuildActivity();
    loadGateActivityPoint();
    loadGuildAuction();
    loadCityActivity();
    loadChatAccuse();
    loadCityActivityReward();
    loadRaceActivity();
    loadShop();
    loadShopList();
    loadRank();
    loadRankReward();
    loadTask();
    loadMainTaskStage();
    loadTaskBox();
    loadGacha();
    loadGachaContent();
    loadGiftPackage();
    loadRecruit();
    loadRMB();
    loadActivityType();
    loadTaskType();
    loadServerName();
    loadAp();
    loadApBuy();
    loadKingExpRatio();
    loadQuenchQuality();
    loadQuenchConsume();
    loadEquipAttributeRatio();
    loadHoliday();
    loadExpeditionSubAttr();
    loadAuctionReward();
    loadGuildTrainInfo();
    loadPvpDifficultRatio();
}

// 重载dicParam
export function reloadDicParam() {
    let file = readTsFile('dicParam');
    if(file) {
        let lines = file.split('\n');
        let outer = '';
        lines.forEach(line => {
            if(line.replace(/ /g, '')) {
                if(line.indexOf('export') != -1) {
                    outer = line.split(' ')[2];
                    // console.log(outer)
                }
                if(line.indexOf('export') == -1 && line.indexOf('}') == -1) {
                    let s = line.split(', //')[0];
                    let key = s.slice(0, s.indexOf(':')).replace(/ /g, '');
                    let value = s.slice(s.indexOf(':' + 1)).replace(/ /g, '');
                    let isString = value.match(/(?<=')[^']*/);
                    if(!param[outer]) {
                        param[outer] = {}
                    }
                    if(isString) {
                        param[outer][key] = isString[0];
                    } else {
                        param[outer][key] = parseFloat(value);
                    }
                }
            }
        });
        parseDicParam();
    }

}

// 后台调用重载资源
export function reloadResources() {
    loadDatas();
    reloadDicParam();
}

initDatas();
