-- 竞技场：匹配
local ArenaMatchUI = class("ArenaMatchUI", BaseUI)

function ArenaMatchUI:isFullScreen()
	return true
end

function ArenaMatchUI:showCommonBG()
	return false
end

function ArenaMatchUI:getPrefabPath()
	return "assets/prefabs/ui/arena/arena_match_ui.prefab"
end

function ArenaMatchUI:onPressBackspace()
	self:closeUI()
end

function ArenaMatchUI:getCurrencyParams()
    if self.currencyParams == nil then
        self.currencyParams = {
            itemIds = {
				GConst.ItemConst.ITEM_ID_GEM,
				GConst.ItemConst.ITEM_ID_ARENA_TICKET
			},
			showType = GConst.CURRENCY_TYPE.HORIZONTAL
        }
    end

 	return self.currencyParams
end

function ArenaMatchUI:ctor()
end

function ArenaMatchUI:onCover()
end

function ArenaMatchUI:onReshow()
end

function ArenaMatchUI:onClose()
	if self.waitSid then
		self:unscheduleGlobal(self.waitSid)
		self.waitSid = nil
	end
	if self.countdownSid then
		self:unscheduleGlobal(self.countdownSid)
		self.countdownSid = nil
	end
	if self.existSid then
		self:unscheduleGlobal(self.existSid)
		self.existSid = nil
	end
end

function ArenaMatchUI:onLoadRootComplete()
	local uiMap = self.root:genAllChildren()

	-- 匹配等待页
	self.matchLoading = uiMap["arena_match_ui.match_loading"]
	self.txSeason = uiMap["arena_match_ui.match_loading.tx_season"]
	self.txLoading = uiMap["arena_match_ui.match_loading.tx_loading"]
	self.btnCancel = uiMap["arena_match_ui.match_loading.btn_cancel"]
	self.txCancel = uiMap["arena_match_ui.match_loading.btn_cancel.tx_cancel"]

	-- 匹配结果页
	self.matchResult = uiMap["arena_match_ui.match_result"]
	self.btnClose = uiMap["arena_match_ui.match_result.btn_close"]
	self.spineVS = uiMap["arena_match_ui.match_result.spine_vs"]
	self.matchAnimator = self.matchResult:getComponent(GConst.TYPEOF_UNITY_CLASS.ANIMATOR)
	-- 对手信息
	self.matchAvatar = CellManager:addCellComp(uiMap["arena_match_ui.match_result.match.info.player_head_cell"], GConst.TYPEOF_LUA_CLASS.PLAYER_HEAD_CELL)
	self.matchTxName = uiMap["arena_match_ui.match_result.match.info.tx_name"]
	self.matchTxLevel = uiMap["arena_match_ui.match_result.match.info.tx_level"]
	self.matchGrading = uiMap["arena_match_ui.match_result.match.arena_grading_cell"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.ARENA_GRADING_CELL)
	self.matchHeroFormationComp = uiMap["arena_match_ui.match_result.match.formation.hero_formation_comp"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.HERO_FORMATION_COMP)
	-- 自己信息
	self.selfAvatar = CellManager:addCellComp(uiMap["arena_match_ui.match_result.self.info.player_head_cell"], GConst.TYPEOF_LUA_CLASS.PLAYER_HEAD_CELL)
	self.selfTxName = uiMap["arena_match_ui.match_result.self.info.tx_name"]
	self.selfTxLevel = uiMap["arena_match_ui.match_result.self.info.tx_level"]
	self.selfGrading = uiMap["arena_match_ui.match_result.self.arena_grading_cell"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.ARENA_GRADING_CELL)
	self.selfHeroFormationComp = uiMap["arena_match_ui.match_result.self.formation.hero_formation_comp"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.HERO_FORMATION_COMP)
	-- 功能按钮
	self.btnStart = uiMap["arena_match_ui.match_result.btn_start"]
	self.imgCost = uiMap["arena_match_ui.match_result.btn_start.cost.img_cost"]
	self.txStart = uiMap["arena_match_ui.match_result.btn_start.tx_start"]
	self.txConst = uiMap["arena_match_ui.match_result.btn_start.cost.tx_cost"]
	self.btnRematch = uiMap["arena_match_ui.match_result.btn_rematch"]
	self.txRematch = uiMap["arena_match_ui.match_result.btn_rematch.tx_rematch"]
	self.txFreeCountdown = uiMap["arena_match_ui.match_result.btn_rematch.tx_free_countdown"]
	self.imgAd = uiMap["arena_match_ui.match_result.btn_rematch.img_ad"]
	self.btnFormation = uiMap["arena_match_ui.match_result.btn_formation"]
	self.txFormation = uiMap["arena_match_ui.match_result.btn_formation.tx_formation"]

	self.btnCancel:addClickListener(function()
		self:closeUI()
	end)
	self.btnClose:addClickListener(function()
		self:closeUI()
	end)
	self.btnStart:addClickListener(function()
		ModuleManager.ArenaManager:reqChallenge()
	end)
	self.btnRematch:addClickListener(function()
		self:onClickRematch()
	end)
	self.btnFormation:addClickListener(function()
		UIManager:showUI("app/ui/arena/arena_formation_ui", {type = GConst.BattleConst.FORMATION_TYPE.ARENA_ATTACK, fromMatch = true})
		self:closeUI()
	end)
	self:addEventListener(EventManager.CUSTOM_EVENT.ARENA_SEASON_SETTLEMENT, function()
		GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_31))
        self:closeUI()
    end)
	self:addEventListener(EventManager.CUSTOM_EVENT.GO_SHOP, function()
        self:closeUI()
    end)
end

function ArenaMatchUI:onRefresh()
	if DataManager.ArenaData:getMatchInfo() == nil then
		ModuleManager.ArenaManager:reqMatch()
		self:showMatchLoading()
	else
		self:showMatchResult()
	end
end

-- 展示匹配等待页
function ArenaMatchUI:showMatchLoading()
	self.matchLoading:setActive(true)
	self.matchResult:setActive(false)
	UIManager:setBarsVisible(self, false)

	self.txSeason:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_21, DataManager.ArenaData:getSeason()))
	self.txLoading:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_22))
	self.txCancel:setText(I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_CANCEL))

	-- 等待
	if self.waitSid then
		self:unscheduleGlobal(self.waitSid)
	end
	self.waitSid = self:performWithDelayGlobal(function()
		self:showMatchResult()
	end, 1.5)
end

-- 展示匹配结果页
function ArenaMatchUI:showMatchResult()
	local matchInfo = DataManager.ArenaData:getMatchInfo()
	if not matchInfo then
		Logger.logError("没有获取到匹配对象，检查匹配响应，查看原因")
		return
	end

	self.matchLoading:setActive(false)
	self.matchResult:setActive(true)
	UIManager:setBarsVisible(self, true)

	self.spineVS:playAnimComplete("born", false, true, function()
        self.spineVS:playAnim("idle", true, true)
    end)

	self.txStart:setText(I18N:getGlobalText(I18N.GlobalConst.TASK_CHALLENGE))
	self.txConst:setText(DataManager.ArenaData:getFightCostNum())
	self.txRematch:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_23))
	self.txFormation:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_10))
	self.imgAd:setActive(DataManager.ArenaData:canAdRematch())

    self.matchAvatar:refresh(matchInfo.avatar, matchInfo.avatar_frame)
	local name = matchInfo.name
    if name == nil or #name == 0 then
        name = I18N:getGlobalText(I18N.GlobalConst.NEW_PLAYER)
    end
	self.matchTxName:setText(name)
	self.matchTxLevel:setText(I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_1, matchInfo.level))
	self.matchGrading:refresh(DataManager.ArenaData:getGradingIdFromScore(matchInfo.score))
	self.matchHeroFormationComp:refreshByEntitys(GFunc.formatPlayerFormationInfo(matchInfo))

	self.selfAvatar:refresh()
	self.selfTxName:setText(DataManager.PlayerData:getNickname())
	self.selfTxLevel:setText(I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_1, DataManager.PlayerData:getLv()))
	self.selfGrading:refresh(DataManager.ArenaData:getGradingId())

	GFunc.centerImgAndTx(self.imgCost, self.txConst, 5)

	local formation = {}
	for idx, id in pairs(DataManager.FormationData:getArenaAttackFormation()) do
		local hero = DataManager.HeroData:getHeroById(id)

		if hero then
			formation[idx] = hero
		else
			formation[idx] = nil
		end
	end
	self.selfHeroFormationComp:refreshByEntitys(formation)

	-- 对手存在倒计时
	self.matchExistCd = DataManager.ArenaData:getMatchExistRemainTime()
	if self.existSid then
		self:unscheduleGlobal(self.existSid)
	end
	self.existSid = self:scheduleGlobal(function()
		self.matchExistCd = self.matchExistCd - 1
		if self.matchExistCd <= 0 then
			self:unscheduleGlobal(self.existSid)
			GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_26))
			self:closeUI()
		end
	end, 1)

	-- 免费匹配cd倒计时
	self.freeRematchCD = DataManager.ArenaData:getFreeRematchCd()
	if self.countdownSid then
		self:unscheduleGlobal(self.countdownSid)
	end
	self.countdownSid = self:scheduleGlobal(function()
		self:refreshCountdown()
	end, 1)
	self:refreshCountdown()
end

function ArenaMatchUI:refreshCountdown()
	self.freeRematchCD = self.freeRematchCD - 1
	if self.freeRematchCD <= 0 then
		-- 冷却已好
		self.txFreeCountdown:setText(I18N:getGlobalText(I18N.GlobalConst.STR_FREE))
		self.imgAd:setActive(false)

		self:unscheduleGlobal(self.countdownSid)
	else
		-- 冷却未好
		self.txFreeCountdown:setText(GFunc.getTimeStrWithHMS(self.freeRematchCD))
	end
end

-- 点击重新匹配
function ArenaMatchUI:onClickRematch()
	if self.freeRematchCD > 0 then
		-- 在cd时间内
		if DataManager.ArenaData:canAdRematch() then
			-- 看视频
			SDKManager:showFullScreenAds(BIReport.ADS_CLICK_TYPE.ARENA_REMATCH, function ()
				ModuleManager.ArenaManager:reqOverCD(true)
				self:showMatchLoading()
			end)
		else
			-- 钻石
			local cost = DataManager.ArenaData:getRematchConstGem()
			local params ={
				content = I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_25, cost),
				boxType = GConst.MESSAGE_BOX_TYPE.MB_OK_CANCEL,
				costId = GConst.ItemConst.ITEM_ID_GEM,
				costNum = cost,
				okFunc = function()
					if not GFunc.checkCost(GConst.ItemConst.ITEM_ID_GEM, cost, true) then
						return
					end
					ModuleManager.ArenaManager:reqOverCD(false)
					self:showMatchLoading()
				end,
			}
			GFunc.showMessageBox(params)
		end
	else
		-- 冷却已好
		ModuleManager.ArenaManager:reqMatch()
		self:showMatchLoading()
	end
end

return ArenaMatchUI