local MainComp = class("MainComp", LuaComponent)
local CHAPTER_COMP = "app/ui/main_city/component/chapter_comp"
local DAILY_CHALLENGE_COMP = "app/ui/main_city/component/daily_challenge_comp"
local DUNGEON_COMP = "app/ui/main_city/component/dungeon_comp"
local ARENA_COMP = "app/ui/main_city/component/arena_comp"

local BOTTOM_HEIGHT = 120

function MainComp:init()
	self.uiMap = self:getBaseObject():genAllChildren()

	self:initStageFormation()
	self:refreshModule(ModuleManager.MaincityManager:getCurModule())
end

function MainComp:refreshTime()
	if not self.moduleMap then
		return
	end
	if self.moduleMap[self.curModuleType] and self.moduleMap[self.curModuleType].refreshTime then
		self.moduleMap[self.curModuleType]:refreshTime()
	end
end

function MainComp:refreshModule(selectModule)
	if not self.moduleMap then
        self.moduleMap = {}
		-- 章节
		local chapterComp = self.uiMap["main_comp.chapter_comp"]
		self.chapterComp = CellManager:addCellComp(chapterComp, CHAPTER_COMP)
		self.chapterComp:initWithParentUI(self)
		self.moduleMap[GConst.MainCityConst.MAIN_MODULE.CHAPTER] = self.chapterComp
		-- 每日挑战
		local dailyChallengeComp = self.uiMap["main_comp.daily_challenge_comp"]
		self.dailyChallengeComp = CellManager:addCellComp(dailyChallengeComp, DAILY_CHALLENGE_COMP)
		self.dailyChallengeComp:initWithParentUI(self)
		self.moduleMap[GConst.MainCityConst.MAIN_MODULE.DAILY_CHALLENGE] = self.dailyChallengeComp
		-- 活动副本
		local dungeonComp = self.uiMap["main_comp.dungeon_comp"]
		self.dungeonComp = CellManager:addCellComp(dungeonComp, DUNGEON_COMP)
		self.dungeonComp:initWithParentUI(self)
		self.moduleMap[GConst.MainCityConst.MAIN_MODULE.DUNGEON] = self.dungeonComp
		-- 竞技场
		local arenaComp = self.uiMap["main_comp.arena_comp"]
		self.arenaComp = CellManager:addCellComp(arenaComp, ARENA_COMP)
		self.arenaComp:initWithParentUI(self)
		self.moduleMap[GConst.MainCityConst.MAIN_MODULE.ARENA] = self.arenaComp
    end

	-- 左侧活动入口
	if not self.leftEntrance then
		self.leftEntrance = {}
		self.leftEntrance[GConst.MainCityConst.MAIN_MODULE.CHAPTER] = self.uiMap["main_comp.left.chapter"]
		self.leftEntrance[GConst.MainCityConst.MAIN_MODULE.ARENA] = self.uiMap["main_comp.left.arena"]
		self.leftEntrance[GConst.MainCityConst.MAIN_MODULE.DAILY_CHALLENGE] = self.uiMap["main_comp.left.daily_challenge"]
	end

	-- 右侧活动入口
	if not self.rightEntrance then
		self.rightEntrance = {}
		self.rightEntrance[GConst.MainCityConst.MAIN_MODULE.CHAPTER] = self.uiMap["main_comp.right.chapter"]
		self.rightEntrance[GConst.MainCityConst.MAIN_MODULE.DUNGEON] = self.uiMap["main_comp.right.dungeon"]
	end

	if self.curModuleType ~= selectModule then
		self.curModuleType = selectModule
		ModuleManager.MaincityManager:setCurModule(self.curModuleType)

		if self.curModuleType == GConst.MainCityConst.MAIN_MODULE.CHAPTER then
			-- 切换到主线章节
		elseif self.curModuleType == GConst.MainCityConst.MAIN_MODULE.DAILY_CHALLENGE then
			-- 切换到每日挑战
			if not DataManager.TutorialData:getIsInTutorial() and DataManager.DailyChallengeData:getIsPopTask() then
				ModuleManager.DailyChallengeManager:showBattleTaskUI()
			end
		elseif self.curModuleType == GConst.MainCityConst.MAIN_MODULE.DUNGEON then
			-- 切换到活动副本
		elseif self.curModuleType == GConst.MainCityConst.MAIN_MODULE.ARENA then
			-- 切换到竞技场
			ModuleManager.ArenaManager:reqArenaInfo()
		end
		self:refreshHeroFormationVisible()
		EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.CHANGE_MAIN_COMP_MODULE, self.curModuleType)
	end

	if self.curModuleType == GConst.MainCityConst.MAIN_MODULE.ARENA then
		if DataManager.ArenaData:getGiftId() then
			local showType = BIReport.PAY_UI_SHOW_TYPE.ENTER_SHOW
			if DataManager.ArenaData:needShowPopGift() then
				showType = BIReport.PAY_UI_SHOW_TYPE.TRIGGER_POP
			end
			local mainUI = UIManager:getUIByIndex(UIManager.UI_PATH.MAINCITY_UI)
			if mainUI and mainUI.isFirstEnter then
				showType = BIReport.PAY_UI_SHOW_TYPE.LOGIN_POP
			end
			ModuleManager.ArenaManager:showGiftPopUI(showType)
		end
		local adBoxState = ModuleManager.ArenaManager:getAdBoxState()
		if adBoxState ~= nil then
			ModuleManager.ShopManager:showArenaAdBoxUI(adBoxState)
			ModuleManager.ArenaManager:markAdBox(nil)
		end
		-- 是否是否有英雄解锁弹窗
		if DataManager.HeroData:getIfCanShowHeroUnlock() then
			local list = DataManager.HeroData:getHeroChapterUnlockList()
			DataManager.HeroData:markShowHeroUnlock()
			if list and #list > 0 then
				ModuleManager.HeroManager:showHeroUnlockUI(list)
				return
			end
		end
	elseif self.curModuleType == GConst.MainCityConst.MAIN_MODULE.DUNGEON then
		if DataManager.TutorialData:getIsInTutorial() then
			local moduleKey = DataManager.TutorialData:getTargetFuncId()
			if moduleKey then
				local dungeonComp = self.moduleMap[self.curModuleType]
				dungeonComp:refreshShow(moduleKey)
			end
		end
	end

	for idx, cell in pairs(self.moduleMap) do
		cell:getBaseObject():setActive(self.curModuleType == idx)
	end

	self:refreshBtns()
end

function MainComp:refreshBtns()
	self:refreshFightBtn()
	self:refreshLeftBtn()
	self:refreshRightBtn()
end

function MainComp:refreshFightBtn()
	if self.fightBtn == nil then
		self.fightBtn = self.uiMap["main_comp.fight_btn"]
		-- 体力消耗
		self.fightCost = self.uiMap["main_comp.fight_btn.cost"]
		self.costTxDesc = self.uiMap["main_comp.fight_btn.cost.tx_desc"]
		self.costTxCost = self.uiMap["main_comp.fight_btn.cost.tx_cost"]
		-- 剩余次数
		self.countTxNum = self.uiMap["main_comp.fight_btn.tx_count"]
		-- 按钮文本
		self.txFight = self.uiMap["main_comp.fight_btn.tx_desc"]
	end

	local moduleCell = self.moduleMap[self.curModuleType]
	local isShowFight = false

	-- 体力消耗
	local cost = moduleCell:getFightHpCost()
	if cost then
		isShowFight = true
		self.fightCost:setActive(true)
		self.costTxDesc:setText(I18N:getGlobalText(I18N.GlobalConst.START_DESC))
		self.costTxCost:setText(GFunc.getRewardNum(cost))
	else
		self.fightCost:setActive(false)
	end

	-- 剩余次数
	local remainCount = moduleCell:getFightTodayRemainCount()
	if remainCount >= 0 then
		isShowFight = true
		self.countTxNum:setActive(true)
		self.countTxNum:setText(I18N:getGlobalText(I18N.GlobalConst.TODAY_REMAIN_TIMES, remainCount))
	else
		self.countTxNum:setActive(false)
	end

	-- 按钮描述
	local fightDesc = moduleCell:getFightDesc()
	if fightDesc then
		isShowFight = true
		self.txFight:setActive(true)
		self.txFight:setText(fightDesc)
		self.fightBtn:setSizeDelta(286, 119)
	else
		self.txFight:setActive(false)
		self.fightBtn:setSizeDelta(334, 122)
	end

	if isShowFight then
		self.fightBtn:setActive(true)
		self.fightBtn:addClickListener(moduleCell.onClickFight)
		self.fightBtn:setAnchoredPositionY(self.btnPosY)
	else
		self.fightBtn:setActive(false)
	end
end

-- 刷新左侧活动模块入口
function MainComp:refreshLeftBtn()

	local showCount = 0
	local leftIdxList = self:getCurLeftModuleIdxList()
	for module, entrance in pairs(self.leftEntrance) do
		if leftIdxList ~= nil and table.containValue(leftIdxList, module) then
			local isShow = self:refreshModuleEntrance(entrance, module, true)
			if isShow then
				showCount = showCount + 1
			end
		else
			entrance:setActive(false)
		end
	end

	if showCount >= 2 then
		self.uiMap["main_comp.left"]:setAnchoredPositionY(self.btnPosY - 20)
		table.foreach(self.leftEntrance, function(idx, entrance)
			entrance:setLocalScale(0.8,0.8)
		end)
	else
		self.uiMap["main_comp.left"]:setAnchoredPositionY(self.btnPosY)
		table.foreach(self.leftEntrance, function(idx, entrance)
			entrance:setLocalScale(1,1)
		end)
	end
end

-- 刷新右侧活动模块入口
function MainComp:refreshRightBtn()

	local showCount = 0
	local rightIdxList = self:getCurRightModuleIdxList()
	for module, entrance in pairs(self.rightEntrance) do
		if rightIdxList ~= nil and table.containValue(rightIdxList, module) then
			local isShow = self:refreshModuleEntrance(entrance, module, false)
			if isShow then
				showCount = showCount + 1
			end
		else
			entrance:setActive(false)
		end
	end

	if showCount >= 2 then
		self.uiMap["main_comp.right"]:setAnchoredPositionY(self.btnPosY - 20)
		table.foreach(self.rightEntrance, function(idx, entrance)
			entrance:setLocalScale(0.8,0.8)
		end)
	else
		self.uiMap["main_comp.right"]:setAnchoredPositionY(self.btnPosY)
		table.foreach(self.rightEntrance, function(idx, entrance)
			entrance:setLocalScale(1,1)
		end)
	end
end

-- 刷新活动模块入口
function MainComp:refreshModuleEntrance(entrance, moduleType, isLeft)
	entrance:setActive(false)
	local module = self.moduleMap[moduleType]
	if moduleType == nil or module == nil then
		return false
	end
	if not module:getIsOpen() then
		return false
	end

	entrance:setActive(true)
	local uiMap = entrance:genAllChildren()
	uiMap["desc"]:setText(module:getEntranceName())
	-- 竞技场图标显示特殊处理
	if moduleType == GConst.MainCityConst.MAIN_MODULE.ARENA then
		local curId = DataManager.ArenaData:getGradingId()
		uiMap["img_num"]:setSprite(GConst.ATLAS_PATH.ARENA, DataManager.ArenaData:getGradingNumName(curId))
		uiMap["icon"]:setSprite(GConst.ATLAS_PATH.ARENA, DataManager.ArenaData:getGradingIconName(curId))
	end

	if module:getShowEntranceRedPoint() then
		if isLeft then
			entrance:addRedPoint(65, 35, 0.6)
		else
			entrance:addRedPoint(-65, 35, 0.6)
		end
	else
		entrance:removeRedPoint()
	end
	entrance:addClickListener(function()
		self:refreshModule(moduleType)
	end)
	return true
end

-- 获取当前左侧活动type list
function MainComp:getCurLeftModuleIdxList()
	if self.curModuleType < GConst.MainCityConst.MAIN_MODULE.CHAPTER then
		return nil
	end

	local leftIdx = {}
	if self.curModuleType == GConst.MainCityConst.MAIN_MODULE.CHAPTER then
		for module, idx in pairs(GConst.MainCityConst.MAIN_MODULE) do
			if idx < GConst.MainCityConst.MAIN_MODULE.CHAPTER then
				table.insert(leftIdx, idx)
			end
		end
		table.sort(leftIdx, function(a, b)
			return math.abs(a) < math.abs(b)
		end)
	else
		table.insert(leftIdx, GConst.MainCityConst.MAIN_MODULE.CHAPTER)
	end

	return leftIdx
end

-- 获取当前右侧活动type list
function MainComp:getCurRightModuleIdxList()
	if self.curModuleType > GConst.MainCityConst.MAIN_MODULE.CHAPTER then
		return nil
	end

	local rightIdx = {}
	if self.curModuleType == GConst.MainCityConst.MAIN_MODULE.CHAPTER then
		for module, idx in pairs(GConst.MainCityConst.MAIN_MODULE) do
			if idx > GConst.MainCityConst.MAIN_MODULE.CHAPTER then
				table.insert(rightIdx, idx)
			end
		end
		table.sort(rightIdx, function(a, b)
			return math.abs(a) < math.abs(b)
		end)
	else
		table.insert(rightIdx, GConst.MainCityConst.MAIN_MODULE.CHAPTER)
	end

	return rightIdx
end

function MainComp:initStageFormation()
	self.heroCells = self.uiMap["main_comp.hero_formation_comp"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.HERO_FORMATION_COMP)

	local heroBgPosY = self.heroCells:getFormationPosY()
	local sWidth, sHeight = GFunc.getUIExpandScreenSize()
	local hSHeight = sHeight / 2
	self.btnPosY = (heroBgPosY + (BOTTOM_HEIGHT / 2 - hSHeight)) / 2
end

function MainComp:refreshHeroFormationVisible()
	self.heroCells:setFormationActive(self.moduleMap[self.curModuleType]:isShowHeroFormation())
end

function MainComp:refresh()
	self:refreshStageFormaion()
	self:refreshChallenge()
	self:refreshDungeon()
	self:refreshArena()
end

function MainComp:onClose()
	for type, cell in pairs(self.moduleMap) do
		if cell.onClose then
			cell:onClose()
		end
	end
end

function MainComp:getCurModuleType()
	return self.curModuleType
end

function MainComp:getCurModule()
	return self.moduleMap[self.curModuleType]
end

function MainComp:refreshChapter(force)
	self.chapterComp:refreshChapter(force)
end

function MainComp:refreshChallenge()
	self:refreshBtns()
	self.dailyChallengeComp:refreshShow()
end

function MainComp:refreshDungeon()
	self:refreshBtns()
	self.dungeonComp:refreshShow()
end

function MainComp:refreshArena()
	self:refreshBtns()
	self.arenaComp:refreshShow()
end

function MainComp:refreshStageFormaion()
	self.heroCells:refresh()
	self:refreshHeroFormationVisible()
end

function MainComp:getDailyChallengeIconPos()
	local idx = table.indexof(self:getCurLeftModuleIdxList(), GConst.MainCityConst.MAIN_MODULE.DAILY_CHALLENGE)
	if idx and self.leftEntrance[idx] then
		return self.leftEntrance[idx]:getPosition()
	end
	idx = table.indexof(self:getCurRightModuleIdxList(), GConst.MainCityConst.MAIN_MODULE.DAILY_CHALLENGE)
	if idx and self.rightEntrance[idx] then
		return self.rightEntrance[idx]:getPosition()
	end
end

function MainComp:getLeftOrRightEntrancePos(module)
	if self.leftEntrance[module] then
		return self.leftEntrance[module]:getPosition()
	end
	if self.rightEntrance[module] then
		return self.rightEntrance[module]:getPosition()
	end
end

function MainComp:refreshArenaBounty()
	if self.arenaComp then
		self.arenaComp:refreshBounty()
	end
end

return MainComp