local HeroEntity = require "app/userdata/hero/hero_entity"
local HeroData = class("HeroData", BaseData)

function HeroData:ctor()
	self.heroes = {}
	self.data.activeCount = 0
	self.data.isDirty = false
	self.matchActiveHeroMap = {}
	self.maxHeroLvOnInit = 0
	self.showHeroUnlockChapter = 0
	self.showHeroUnlockDan = 0
	self.heroChapterUnlockMap = {}
	self.heroChapterUnlockMapBi = {}

	self.heroDanUnlockMap = {}
	self.heroDanUnlockMapBi = {}

	self.allAtkpAttr = {}
	self.allAtkpAttrByHero = {}
end

function HeroData:clear()
	self.heroes = {}
end

function HeroData:init(data)
	self.heroes = {}
	for k, v in pairs(self.heroChapterUnlockMap) do
		self.heroChapterUnlockMap[k] = false
	end
	for k, v in pairs(self.heroChapterUnlockMapBi) do
		self.heroChapterUnlockMapBi[k] = false
	end
	for k, v in pairs(self.heroDanUnlockMap) do
		self.heroDanUnlockMap[k] = false
	end
	for k, v in pairs(self.heroDanUnlockMapBi) do
		self.heroDanUnlockMapBi[k] = false
	end
	if data then
		for id, heroInfo in pairs(data) do
			self:addHero(heroInfo)
			if self.maxHeroLvOnInit < heroInfo.level then
				self.maxHeroLvOnInit = heroInfo.level
			end
		end
	end

	for heroId, entity in pairs(self.heroes) do
		if entity and entity:isActived() then
			local matchType = entity:getMatchType()
			if not self.matchActiveHeroMap[matchType] then
				self.matchActiveHeroMap[matchType] = {}
			end
			self.matchActiveHeroMap[matchType][entity:getCfgId()] = true
		end
		-- if info.unlock_chapter and info.is_show == 1 then
		-- 	self.heroChapterUnlockMap[info.unlock_chapter] = true
		-- end
		-- if info.unlock_chapter then
		-- 	self.heroChapterUnlockMapBi[info.unlock_chapter] = true
		-- end

		-- if info.unlock_arena and info.is_show == 1 then
		-- 	self.heroDanUnlockMap[info.unlock_arena] = true
		-- end
		-- if info.unlock_arena then
		-- 	self.heroDanUnlockMapBi[info.unlock_arena] = true
		-- end
	end
	self.showHeroUnlockChapter = 0
	self.showHeroUnlockDan = 0
end

-- 是否是合法的英雄
function HeroData:isExistHeroById(id)
	if not id or id == 0 then
		return false
	end

	return ConfigManager:getConfig("hero")[id] ~= nil
end

function HeroData:addHero(heroStruct)
	if self.heroes[heroStruct.id] then
		return
	end
	local entity = self:getEntity(heroStruct)

	self.heroes[heroStruct.id] = entity
	self.data.activeCount = self.data.activeCount + 1
end

function HeroData:getEntity(heroStruct)
	return HeroEntity:create(heroStruct.id, heroStruct.level, heroStruct.skin, heroStruct.star)
end

function HeroData:getHeroById(id)
	if not self:isExistHeroById(id) then
		return
	end
	if not self.heroes[id] then
		self.heroes[id] = self:getEntity({id = id, level = 0, skin = 0, star = 0})
	end
	return self.heroes[id]
end

function HeroData:getAllHeroes()
	return self.heroes
end

function HeroData:getActiveHeroCount()
	return self.data.activeCount
end

function HeroData:getHeroIsActive(id)
	local entity = self.heroes[id]
	if entity == nil then
		return false
	end
	return entity:isActived()
end


function HeroData:getHeroIsUnlock(id)
	local entity = self.heroes[id]
	if entity == nil then
		return false
	end
	return entity:isUnlock()
end

function HeroData:getUnlockHeroCount()
	local count = 0
	for id, entity in pairs(self.heroes) do
		if entity:isUnlock() then
			count = count + 1
		end
	end
	return count
end

function HeroData:setHeroLv(id, lv)
	local entity = self:getHeroById(id)
	local activeBefore = true
	if not entity:isActived() then
		self.data.activeCount = self.data.activeCount + 1
		ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_NEW_HERO_GOT)
		ModuleManager.PlayerManager:checkUnlockAvatar(id)
		activeBefore = false
		BIReport:postFirstGetHero(self.data.activeCount)
	end
	local beforeLv = entity:getLv()
	entity:setLv(lv)
	if entity:isActived() then
		local matchType = entity:getMatchType()
		if not self.matchActiveHeroMap[matchType] then
			self.matchActiveHeroMap[matchType] = {}
		end
		self.matchActiveHeroMap[matchType][entity:getCfgId()] = true
	end

	if activeBefore then
		BIReport:postHeroOpt(id, BIReport.HERO_OPT_TYPE.LEVEL_UP)
	else
		if not entity:getUnlcokChapter() then
			BIReport:postHeroOpt(id, BIReport.HERO_OPT_TYPE.UNLOCK)
		end
		BIReport:postHeroOpt(id, BIReport.HERO_OPT_TYPE.ACTIVE)
	end

	BIReport:postHeroLev(beforeLv, lv)
	BIReport:postFirstDayHeroLevel(id)
end

function HeroData:getMatchActiveHeroMap()
	return self.matchActiveHeroMap
end

function HeroData:setDirty()
	self.data.isDirty = not self.data.isDirty
end

function HeroData:getRp()
	local formationMap = DataManager.FormationData:getStageFormation()
	if not formationMap then
		return false
	end
	local heroMap = {}
	for _, heroId in pairs(formationMap) do
		heroMap[heroId] = true
	end

	for id, entity in pairs(self.heroes) do
		if entity:canLvUp() then
			if heroMap[id] or not entity:isActived() then
				return true
			end
		end
	end

	if DataManager.CollectionData:hasRedPoint() then
		return true
	end

	return false
end

function HeroData:getMaxHeroLvOnInit()
	return self.maxHeroLvOnInit
end

function HeroData:getIfCanShowHeroUnlock()
	return self.showHeroUnlockChapter > 0 or self.showHeroUnlockDan > 0
end

function HeroData:markShowHeroUnlock()
	self.showHeroUnlockChapter = 0
	self.showHeroUnlockDan = 0
end

function HeroData:checkIfCanShowHeroUnlock(chapterId)
	if self.heroChapterUnlockMapBi[chapterId] then -- 日志上报
		for id, entity in pairs(self.heroes) do
			if not entity:isActived() and entity:getUnlcokChapter() == chapterId then
				BIReport:postHeroOpt(id, BIReport.HERO_OPT_TYPE.UNLOCK)
			end
		end
	end

	if not self.heroChapterUnlockMap[chapterId] then
		return
	end
	self.showHeroUnlockChapter = chapterId
end

function HeroData:checkIfCanShowHeroUnlockDan(dan)
	if self.heroDanUnlockMapBi[dan] then -- 日志上报
		for id, entity in pairs(self.heroes) do
			if not entity:isActived() and entity:getUnlockDan() == dan then
				BIReport:postHeroOpt(id, BIReport.HERO_OPT_TYPE.UNLOCK)
			end
		end
	end

	if not self.heroDanUnlockMap[dan] then
		return
	end
	self.showHeroUnlockDan = dan
end

function HeroData:getHeroChapterUnlockList()
	local list = {}
	for id, entity in pairs(self.heroes) do
		if not entity:isActived() and entity:getIsShowUnlcokChapter() and (entity:getUnlcokChapter() == self.showHeroUnlockChapter or entity:getUnlockDan() == self.showHeroUnlockDan) then
			table.insert(list, id)
		end
	end
	return list
end

function HeroData:getAllHeroesBIStr()
	local str
	for heroId, entity in pairs(self:getAllHeroes()) do
		if str then
			str = str .. "|"
		else
			str = GConst.EMPTY_STRING
		end
		str = str .. heroId .. ":" .. entity:getLv()
	end
	return str
end

-- 获取所有英雄列表（等级>品质>id）
function HeroData:getAllHeroesSort(formationType)
	local formationMap
	if formationType then
		local formation = DataManager.FormationData:getFormation(formationType)
		formationMap = {}
		for _, heroId in pairs(formation) do
			formationMap[heroId] = true
		end
	end
	local result = {}
	local heroCfg = ConfigManager:getConfig("hero")
	for id, v in pairs(heroCfg) do
		table.insert(result, {cfgId = id, sort = id, elementType = v.position})
	end

	for _, info in ipairs(result) do
		local heroEntity = self:getHeroById(info.cfgId)
		local sort = info.cfgId -- id 预留6位
		sort = sort + (10 - info.elementType) * 1000000 -- 位置预留1位
		sort = sort + 10000000000 * heroEntity:getQlt() -- 品质1位
		sort = sort + 10000000 * heroEntity:getLv() -- 预留3位

		if formationMap and formationMap[info.cfgId] then --在布阵中
			sort = sort + 10000000000000
		end

		if not heroEntity:isActived() and heroEntity:canLvUp() then
			sort = sort + 1000000000000
		else
			if heroEntity:isUnlock() then
				sort = sort + 300000000000
				if heroEntity:isActived() then
					sort = sort + 400000000000
				else
					sort = sort + 300000000000
				end
			elseif DataManager.BagData.ItemData:getItemNumById(heroEntity:getFragmentId()) > 0 then
				sort = sort + 200000000000
			else
				sort = sort + 100000000000
			end
		end

		info.sort = sort
	end
	table.sort(result, function(a, b)
		return a.sort > b.sort
	end)

	return result
end

-- region 配置相关
function HeroData:getHeroConfig(id)
	if id then
		return ConfigManager:getConfig("hero")[id]
	else
		return ConfigManager:getConfig("hero")
	end
end

function HeroData:getHeroQlt(id)
	local cfg = self:getHeroConfig(id)
	if cfg then
		return cfg.qlt
	end
end

function HeroData:getHeroLevelConfig(lv)
	if lv then
		return ConfigManager:getConfig("hero_level")[lv]
	else
		return ConfigManager:getConfig("hero_level")
	end
end

-- 升级目前跟质量无关
function HeroData:getHeroLevelCost(lv, qlt)
    local cfg = self:getHeroLevelConfig(lv)
    if cfg then
        return cfg.cost
    end
end
-- endregion

-- region 升星相关
function HeroData:isStarOpen()
	return true
end

function HeroData:getStarById(id)
	local hero = self.heroes[id]
	if hero then
		return hero:getStar()
	end
	return 0
end

function HeroData:onHeroStarUp(id)
	local entity = self:getHeroById(id)
	if entity then
		entity:onHeroStarUp()
	end
	-- BIReport:postHeroLev(beforeLv, lv)
	-- BIReport:postFirstDayHeroLevel(id)
end
-- endregion

-- region 皮肤相关
function HeroData:isSkinOpen()
	return true
end
-- endregion

-- region 属性相关
function HeroData:getAttrByMatchType(matchType, attrType)
	self.allAtkpAttr[matchType] = self.allAtkpAttr[matchType] or {}
	return self.allAtkpAttr[matchType][attrType] or 0
end

function HeroData:setHeroAttr(heroId, attr)
	self.allAtkpAttrByHero[heroId] = attr
	self:calcAttr()
end

function HeroData:calcAttr()
	for heroId, attrs in pairs(self.allAtkpAttrByHero) do
		-- self.baseAttrOriginal[ATTR_NAME.ATK_RED] = 0
		local matchType = self.heroes[heroId]:getMatchType()
		self.allAtkpAttr[matchType] = self.allAtkpAttr[matchType] or {}
		for k,v in pairs(attrs) do
			self.allAtkpAttr[matchType][k] = (self.allAtkpAttr[matchType][k] or 0) + v
		end
	end
end
-- endregion

return HeroData