local DungeonMaterialComp = class("DungeonMaterialComp", LuaComponent)

local DUNGEON_MATERIAL_CELL = "app/ui/dungeon/cell/dungeon_material_cell"

function DungeonMaterialComp:init()
	local uiMap = self:getUIMap()
	self.scrollrect = uiMap["material_comp.scrollrect"]
	self.titleTx = uiMap["material_comp.title_tx"]
	self.descTx = uiMap["material_comp.desc_tx"]
	self.powerTx = uiMap["material_comp.img_bg.tx_power"]
end

function DungeonMaterialComp:onRefresh(isFirstEnter)
	self.titleTx:setText(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_TITLE_7))
	local todayMaxTimes = DataManager.DungeonDailyData.MaterialData:getTodayMaxTimes()
	local timesStr = DataManager.DungeonDailyData.MaterialData:getTodayRemainTimes() .. "/" .. todayMaxTimes
	self.descTx:setText(I18N:getGlobalText(I18N.GlobalConst.TODAY_REMAIN_TIMES, timesStr))
	-- local curPower = DataManager.PlayerData:getSelfEntity():getShowPower(ModuleManager.BattleManager.BATTLE_TYPE.DUNGEON)
	-- self.powerTx:setText(GFunc.getPowerShow(curPower))
	local curPower = DataManager.HeroData:getShowPower()
	self.powerTx:setText(curPower)
	if not self.scrollRectComp then
		self.scrollRectComp = self.scrollrect:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
		self.scrollRectComp:addInitCallback(function()
			return DUNGEON_MATERIAL_CELL
		end)
		self.scrollRectComp:addRefreshCallback(function(index, cell)
			cell:refresh(index)
		end)
	end
	local allChaptersInfo = DataManager.DungeonDailyData.MaterialData:getLimitChaptersInfo()
	local count = #allChaptersInfo
	if self.scrollRectComp:getTotalCount() == nil or self.scrollRectComp:getTotalCount() <= 0 then
		self.scrollRectComp:refillCells(count)
	elseif self.scrollRectComp:getTotalCount() ~= count then
		self.scrollRectComp:clearCells()
		self.scrollRectComp:refillCells(count)
	else
		self.scrollRectComp:updateAllCell()
	end
	if isFirstEnter then
		local findIndex = 0
		local challengeId = DataManager.DungeonDailyData.MaterialData:getChallengeId()
		local maxPassedId = DataManager.DungeonDailyData.MaterialData:getMaxPassedId()
		if challengeId == maxPassedId then -- 全部通关了
			self.scrollRectComp:moveToIndex(count)
		else
			for k, v in ipairs(allChaptersInfo) do
				if v.id == challengeId and challengeId ~= maxPassedId then
					findIndex = k - 1
					break
				end
			end
			 if findIndex < 1 then
				findIndex = 1
			end
			self.scrollRectComp:moveToIndex(findIndex)
		end
	end
end

return DungeonMaterialComp