local MainComp = class("MainComp", LuaComponent)

local UISpineObject = require "app/bf/unity/ui_spine_object"

local CHAPTER_BG_PATH = "assets/arts/textures/background/chapter/%s.png"
local HERO_SPINE_ASSET_PATH = "assets/arts/spines/characters/%s/%s_skeletondata.asset"
local CHAPTER_PATH = "assets/prefabs/ui/chapter/%s.prefab"
local CHAPTER_PAGE = 5

function MainComp:onClose()
	self.currChapterId = nil
end

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

	uiMap["main_comp.arena_btn.text"]:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_1))
	uiMap["main_comp.daily_challenge_btn.text"]:setText(I18N:getGlobalText(I18N.GlobalConst.DAILY_CHALLENGE))
	uiMap["main_comp.left_btn.text"]:setText(I18N:getGlobalText(I18N.GlobalConst.IDLE_DESC_1))
	uiMap["main_comp.right_btn.text"]:setText(I18N:getGlobalText(I18N.GlobalConst.SUMMON_DESC_2))
	self.backGroundNode = uiMap["main_comp.back_ground"]
	self.arenaBtn = uiMap["main_comp.arena_btn"]
	self.dailyChallengeBtn = uiMap["main_comp.daily_challenge_btn"]

	self.chapterBg = uiMap["main_comp.bg"]
	self.fightBtn = uiMap["main_comp.fight_btn"]
	-- 体力消耗
	self.fightCost = uiMap["main_comp.fight_btn.cost"]
	self.costTxCost = uiMap["main_comp.fight_btn.cost.tx_cost"]
	-- 按钮文本
	self.txFight = uiMap["main_comp.fight_btn.tx_desc"]
	self.fightBtn:addClickListener(function ()
		ModuleManager.ChapterManager:startFight()
	end)

	self.leftArrowBtn = uiMap["main_comp.middle_bg.left_arrow.btn"]
	self.rightArrowBtn = uiMap["main_comp.middle_bg.right_arrow.btn"]

	self.leftBtn = uiMap["main_comp.left_btn"]
	self.rightBtn = uiMap["main_comp.right_btn"]
	self.heroSpineList = {}
	self.heroNodeList = {}
	for i = 1, 5 do
		self.heroNodeList[i] = uiMap["main_comp.formation.hero_" .. i]
		-- self.heroNodeList[i]:addClickListener(function()
		-- 	local heroId = self.curFormation[i]
		-- 	if heroId then
		-- 		local hero = DataManager.HeroData:getHeroById(heroId)
		-- 		if hero then
		-- 			ModuleManager.HeroManager:showHeroDetailUI(heroId, nil, nil, GConst.BattleConst.FORMATION_TYPE.STAGE)
		-- 		end
		-- 	end
		-- end)
	end

	self.chapterMiddleBg = uiMap["main_comp.middle_bg"]
	self.chapterTx = uiMap["main_comp.middle_bg.chapter_tx"]
	self.chapterMaxTx = uiMap["main_comp.middle_bg.max_tx"]
	self.chapterInfoBtn = uiMap["main_comp.middle_bg.info_btn"]
	self.chapterBoxBtn = uiMap["main_comp.middle_bg.box_btn"]
	self.chapterPageNode = uiMap["main_comp.middle_bg.page_node"]
	self.chapterPageBtns = {}
	self.chapterPageBtnCheckImgs = {}
	self.chapterPageBtnDescTxs = {}
	self.chapterPageBtnMaskImgs = {}
	self.chapterPageBtnSelectImgs = {}
	for i = 1, CHAPTER_PAGE do
		self.chapterPageBtns[i] = uiMap["main_comp.middle_bg.page_node.page_btn_" .. i]
		local bg = uiMap["main_comp.middle_bg.page_node.page_btn_" .. i .. ".bg"]
		self.chapterPageBtnCheckImgs[i] = uiMap["main_comp.middle_bg.page_node.page_btn_" .. i .. ".bg.check_img"]
		self.chapterPageBtnDescTxs[i] = uiMap["main_comp.middle_bg.page_node.page_btn_" .. i .. ".bg.desc_tx"]
		self.chapterPageBtnMaskImgs[i] = uiMap["main_comp.middle_bg.page_node.page_btn_" .. i .. ".bg.mask_img"]
		self.chapterPageBtnSelectImgs[i] = uiMap["main_comp.middle_bg.page_node.page_btn_" .. i .. ".bg.select_img"]
		bg:addClickListener(function()
			self.chapterStage = i
			local chapterId = DataManager.ChapterData:getChapterCfgByPageAndStage(self.chapterPage, self.chapterStage)
			DataManager.ChapterData:setChapterId(chapterId)
			self:refresh()
		end)
	end
	-- MaincityManager:showChapterBoxUI(chapterId)

	uiMap["main_comp.middle_bg.box_btn"]:addClickListener(function()
		local canGet = DataManager.ChapterData:getChapterBoxCanGet()
		if canGet then
			ModuleManager.ChapterManager:openBox()
		else
			local chapterId = DataManager.ChapterData:getChapterId()
			ModuleManager.MaincityManager:showChapterBoxUI(chapterId)
		end
	end)
	uiMap["main_comp.middle_bg.info_btn"]:addClickListener(function()
		local chapterId = DataManager.ChapterData:getChapterId()
		ModuleManager.MaincityManager:showChapterBoxUI(chapterId)
	end)
	uiMap["main_comp.arena_btn"]:addClickListener(function()
		if not ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.ARENA) then
			return
		end
		ModuleManager.ArenaManager:reqArenaInfo(true)
	end)
	uiMap["main_comp.daily_challenge_btn"]:addClickListener(function()
		if not ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.DAILY_CHALLENGE) then
			return
		end
		ModuleManager.DailyChallengeManager:showDailyChallengeUI()
	end)
	self.leftArrowBtn:addClickListener(function()
		self.chapterPage  = self.chapterPage - 1
		self.chapterList = DataManager.ChapterData:getChapterList(self.chapterPage)
		if self.chapterStage > #self.chapterList then
			self.chapterStage = #self.chapterList
		end
		local chapterId = DataManager.ChapterData:getChapterCfgByPageAndStage(self.chapterPage, self.chapterStage)
		DataManager.ChapterData:setChapterId(chapterId)
		self:refresh()
	end)
	self.rightArrowBtn:addClickListener(function()
		self.chapterPage = self.chapterPage + 1
			self.chapterList = DataManager.ChapterData:getChapterList(self.chapterPage)
		if self.chapterStage > #self.chapterList then
			self.chapterStage = #self.chapterList
		end
		local chapterId = DataManager.ChapterData:getChapterCfgByPageAndStage(self.chapterPage, self.chapterStage)
		DataManager.ChapterData:setChapterId(chapterId)
		self:refresh()
	end)
	self.leftBtn:addClickListener(function()
		ModuleManager.IdleManager:showIdleDropUI()
	end)
	self.rightBtn:addClickListener(function()
		ModuleManager.SummonManager:showSummonMainUI()
	end)
	local chapterId = DataManager.ChapterData:getChapterId()
	self.chapterPage = DataManager.ChapterData:getChapterPage(chapterId)
	self.chapterStage = DataManager.ChapterData:getChapterStage(chapterId)

	self.chapterScenes = {}
end

function MainComp:refreshTime()
	self:refreshRedPoint()
end

function MainComp:refresh()
	self:refreshChapter()
	self:refreshRedPoint()
	self:refreshHero()
end

function MainComp:refreshChapter(force)
	local chapterId = DataManager.ChapterData:getChapterId()
	self.chapterList = DataManager.ChapterData:getChapterList(self.chapterPage)
	if self.currChapterId ~= chapterId or force then
		self.currChapterId = chapterId
		self.chapterPage = DataManager.ChapterData:getChapterPage(chapterId)
		self.chapterStage = DataManager.ChapterData:getChapterStage(chapterId)
		self:refreshChapterBg()
		self:refreshFightBtn()
	end
	self.currChapterId = chapterId
	self:refreshChapterInfo()
	self:refreshChapterBtn()

	self.leftBtn:setActive(ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.IDLE_DROP, true))
	self.rightBtn:setActive(ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.SUMMON_OPEN, true))
end

function MainComp:refreshChapterBg()
	if self.isLoading then
		return
	end
	local chapterId = DataManager.ChapterData:getChapterId()
	local icon = DataManager.ChapterData:getChapterCfg()[chapterId].icon
	local scene = DataManager.ChapterData:getChapterCfg()[chapterId].scene
	local bgPath = string.format(CHAPTER_PATH, icon)
	if self.currScenePath == bgPath then
		return
	end
	if self.chapterScenes[bgPath] then
		self.chapterScenes[bgPath]:setActive(true)
		if self.currScenePath and self.chapterScenes[self.currScenePath] then
			self.chapterScenes[self.currScenePath]:setActive(false)
		end
		self.currScenePath = bgPath
		self.chapterBg:setTexture(string.format(CHAPTER_BG_PATH, scene))
	else
		self.isLoading = true
		local oldPath = self.currScenePath
		UIPrefabManager:loadUIWidgetAsync(bgPath, self.backGroundNode, function(prefab)
			self.isLoading = false
			if oldPath and self.chapterScenes[oldPath] then
				self.chapterScenes[oldPath]:setActive(false)
			end
			self.currScenePath = bgPath
			self.chapterScenes[self.currScenePath] = prefab
			self.chapterBg:setTexture(string.format(CHAPTER_BG_PATH, scene))
		end)
	end
end

function MainComp:refreshChapterBtn()
	local chapterNewId = DataManager.ChapterData:getNewChapterId()
	local maxPage = DataManager.ChapterData:getChapterPage(chapterNewId)
	self.leftArrowBtn:setActive(self.chapterPage > 1)
	self.rightArrowBtn:setActive(self.chapterPage < maxPage)
end

function MainComp:refreshFightBtn()
	-- 体力消耗
	local cost = DataManager.ChapterData:getFightCost()
	self.fightCost:setActive(true)
	self.txFight:setText(I18N:getGlobalText(I18N.GlobalConst.START_DESC))
	self.costTxCost:setText(GFunc.getRewardNum(cost))
end

function MainComp:refreshChapterInfo()
	local chapterId = DataManager.ChapterData:getChapterId()
	local chapterMaxId = DataManager.ChapterData:getMaxChapterId()
	for i = 1, CHAPTER_PAGE do
		if i <= #self.chapterList then
			self.chapterPageBtns[i]:setActive(true)
			self.chapterPageBtnSelectImgs[i]:setActive(i == self.chapterStage)
			self.chapterPageBtnDescTxs[i]:setText(i)
			local selChapterId = DataManager.ChapterData:getChapterCfgByPageAndStage(self.chapterPage, i)
			self.chapterPageBtnCheckImgs[i]:setActive(selChapterId <= chapterMaxId)
			self.chapterPageBtnMaskImgs[i]:setActive(selChapterId > (chapterMaxId + 1))
		else
			self.chapterPageBtns[i]:setActive(false)
		end
	end
	self.chapterPageNode:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT):RefreshLayout()

	if chapterId <= chapterMaxId + 1 then
		self.fightBtn:setTouchEnable(true)
		self.fightBtn:setSprite(GConst.ATLAS_PATH.MAIN, "main_btn_1")
	else
		self.fightBtn:setTouchEnable(false)
		self.fightBtn:setSprite(GConst.ATLAS_PATH.MAIN, "main_btn_4")
	end

	local chapterI18NInfo = I18N:getConfig("chapter")[chapterId]
	if chapterI18NInfo then	
		self.chapterTx:setText(chapterI18NInfo.name)
	end
	if chapterId <= chapterMaxId then
		self.chapterMaxTx:setText(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_ARMOR_DESC_7))
	elseif chapterId == chapterMaxId + 1 then
		self.chapterMaxTx:setText(I18N:getGlobalText(I18N.GlobalConst.CHAPTER_DESC_1, DataManager.ChapterData:getChapterMaxWave()))
	else
		self.chapterMaxTx:setText(I18N:getGlobalText(I18N.GlobalConst.EQUIP_DESC_22))
	end
end

function MainComp:refreshRedPoint()
	local time = Time:getServerTime() - DataManager.IdleData:getLastDropTime()
	-- local idleMaxTime = DataManager.IdleData:getIdleMaxTime()
	local idleMaxTime = 3600
	if time >= idleMaxTime then
		self.leftBtn:addRedPoint(70, -36, 1)
	else
		self.leftBtn:removeRedPoint()
	end

	if DataManager.SummonData:hasSummonCostRedPoint() then
		self.rightBtn:addRedPoint(-70, -36, 1)
	else
		self.rightBtn:removeRedPoint()
	end

	if DataManager.ArenaData:hasEntranceRedDot() then
		self.arenaBtn:addRedPoint(70, 26, 1)
	else
		self.arenaBtn:removeRedPoint()
	end

	if DataManager.DailyChallengeData:showRedPoint() then
		self.dailyChallengeBtn:addRedPoint(-70, 26, 1)
	else
		self.dailyChallengeBtn:removeRedPoint()
	end

	if DataManager.ChapterData:getChapterBoxCanGet() then
		self.chapterBoxBtn:addRedPoint(24, 24, 1)
	else
		self.chapterBoxBtn:removeRedPoint()
	end
end

function MainComp:getArenaBtnPosition()
	return self.arenaBtn:getPosition()
end

function MainComp:getDailyChallengeBtnPosition()
	return self.dailyChallengeBtn:getPosition()
end

function MainComp:getIdleBtnPosition()
	local pos = self.leftBtn:getPosition()
	return {x = pos.x + 0.5, y = pos.y + 0.5, z = 0}
end

function MainComp:getSummonBtnPosition()
	local pos = self.rightBtn:getPosition()
	return {x = pos.x - 0.5, y = pos.y + 0.5, z = 0}
end

function MainComp:refreshHero()
	self.curFormation = DataManager.FormationData:getStageFormation()
	for i = 1, 5 do
		local heroId = self.curFormation[i]
		local hero = DataManager.HeroData:getHeroById(heroId)
		if hero and hero:getLv() > 0 then
			if self.heroSpineList[i] and self.heroSpineList[i]:getModelId() == hero:getModelId() then
				self.heroSpineList[i]:setActive(true)
				self.heroSpineList[i]:playAnimation("move", true)
			else
				SpineManager:loadHeroAsync(hero:getModelId(), self.heroNodeList[i], function(spineObject)
					if heroId ~= self.curFormation[i] then
						return
					end
					if self.heroSpineList[i] then
						self.heroSpineList[i]:destroy()
					end
					spineObject:playAnimation("move", true)
					spineObject:setLocalScale(0.7, 0.7, 0.7)
					self.heroSpineList[i] = spineObject
					self.heroSpineList[i]:setLocalPosition(0, -60, 0)
				end)
			end
		else
			if self.heroSpineList[i] then
				self.heroSpineList[i]:setActive(false)
			end
		end
	end
end

return MainComp