local BountyMainUI = class("BountyMainUI", BaseUI)

function BountyMainUI:getPrefabPath()
	return "assets/prefabs/ui/bounty/bounty_main_ui.prefab"
end

function BountyMainUI:ctor()
	self.rewardCellIdx = 0
	self.rewardCellNum = 0
	self.endTime = DataManager.BountyData:getEndTime()
	self.previewRewardIndex = 1
	local maxLevel = DataManager.BountyData:getMaxLevel()
	local info = nil
	for i = 2, maxLevel do
		info = DataManager.BountyData:getSeasonInfoByLevel(i)
		if info == nil then
			break
		end
		if info.reward_type and info.reward_type == 1 then
			self.previewRewardIndex = i
			break
		end
	end
end

function BountyMainUI:onClose()
	if self.autoRotateTween then
		self.autoRotateTween:Kill()
	end
	self:clearPreviewRewardAnimation()
	if self.rewardsContentMoveTween then
		self.rewardsContentMoveTween:Kill()
	end
end

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

function BountyMainUI:onLoadRootComplete()
	local uiMap = self.root:genAllChildren()
	self.uiMap = uiMap
	local closeBtn = uiMap["bounty_main_ui.bottom_node.close_btn"]
	closeBtn:addClickListener(function()
		self:closeUI()
	end)

	self.oneKeyBtn = uiMap["bounty_main_ui.bottom_node.one_key_btn"]
	self.oneKeyBtn:addClickListener(function()
		ModuleManager.BountyManager:claimReward(0, false)
	end)
	uiMap["bounty_main_ui.bottom_node.one_key_btn.desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ONE_KEY_GET_DESC))

	self:initTitle()
	self:initTime()
	self:initLevel()
	self:initPayBtn()
	self:initPreviewReward()
	self:initRewards()

	self:bindData()

	-- 没有购买通行证的话，每日首次打开战令界面主动弹通行证购买弹窗
	if DataManager.BountyData:getIsPopBought() then
		ModuleManager.BountyManager:showBountyBuyUI()
	end
	self:scheduleGlobal(function()
		self:updateTime()
	end, 1)
	self:updateTime()

	BIReport:postPayUIShow(BIReport.GIFT_TYPE.BOUNTY, nil, BIReport.PAY_UI_SHOW_TYPE.CLICK_SHOW)
end

function BountyMainUI:initTitle()
	self.titleSpine = self.uiMap["bounty_main_ui.top_node.spine_title"]

	self.titleSpine:setVisible(false)
	self.titleSpine:loadAssetAsync(DataManager.BountyData:getBannerSpineName(), function()
		self.titleSpine:setVisible(true)
		self.titleSpine:playAnimComplete("born", false, true, function()
			self.titleSpine:playAnim("idle", true, true, true)
		end, true)
	end, false)
end

function BountyMainUI:initTime()
	self.timeIcon = self.uiMap["bounty_main_ui.top_node.time_icon"]
	self.timeTx = self.uiMap["bounty_main_ui.top_node.time_tx"]
	self.timeTx:setText(GConst.EMPTY_STRING)
	self.adjustTimeUI = false
end

function BountyMainUI:initLevel()
	self.levelSlider = self.uiMap["bounty_main_ui.top_node.progress_bg.slider"]
	self.levelItemImg = self.uiMap["bounty_main_ui.top_node.progress_bg.item_img"]
	self.levelSliderTx = self.uiMap["bounty_main_ui.top_node.progress_bg.slider_tx"]
	self.lvTx = self.uiMap["bounty_main_ui.top_node.progress_bg.lv_img.lv_tx"]
end

function BountyMainUI:initPayBtn()
	self.payBtn = self.uiMap["bounty_main_ui.top_node.buy_btn"]
	self.payBtnTx = self.uiMap["bounty_main_ui.top_node.buy_btn.tx"]
	self.payBtn:addClickListener(function()
		ModuleManager.BountyManager:showBountyBuyUI()
	end)
end

function BountyMainUI:initPreviewReward()
	self.previewReward = self.uiMap["bounty_main_ui.mid_node.preview"]
	self.uiMap["bounty_main_ui.mid_node.preview.bg"]:addClickListener(function()
		if self.rewardsContentSid then
			return
		end
		if self.showPreviewRewardSid then
			return
		end
		if self.previewRewardIndex >= self.scrollrectComp:getTotalCount() then
			self:scrollToIndex(self.previewRewardIndex)
		else
			self:scrollToIndex(self.previewRewardIndex - self.rewardCellNum/2 + 1)
		end
	end)
	self.previewRewardCellComp = self.uiMap["bounty_main_ui.mid_node.preview.bg.reward_cell"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.REWARD_CELL)
	self.previewRewardLvTx = self.uiMap["bounty_main_ui.mid_node.preview.bg.lv_tx"]
	self.previewRewardNumTx = self.uiMap["bounty_main_ui.mid_node.preview.bg.num_tx"]
	local previewRewardLight = self.uiMap["bounty_main_ui.mid_node.preview.bg.light"]
	self.autoRotateTween = previewRewardLight:getTransform():DOLocalRotate(BF.Vector3(0, 0, -360), 3, CS.DG.Tweening.RotateMode.FastBeyond360):SetEase(CS.DG.Tweening.Ease.Linear)
	self.autoRotateTween:SetLoops(-1)
	self.uiMap["bounty_main_ui.mid_node.preview.bg.desc_tx"]:setText(I18N:getGlobalText(I18N.GlobalConst.REWARD_DESC))
end

function BountyMainUI:initRewards()
	self:initRepeatReward()
	self.adjustRewardsTitleUI = false
	local rewardsLeftTitle = self.uiMap["bounty_main_ui.top_node.left"]
	rewardsLeftTitle:setAnchoredPositionX(-GConst.UI_SCREEN_WIDTH/4)
	self.rewardsLeftTitleIcon = self.uiMap["bounty_main_ui.top_node.left.icon"]
	self.rewardsLeftTitleTx = self.uiMap["bounty_main_ui.top_node.left.text"]
	local rewardsRightTitle = self.uiMap["bounty_main_ui.top_node.right"]
	rewardsRightTitle:setAnchoredPositionX(GConst.UI_SCREEN_WIDTH/4)
	self.rewardsRightTitleIcon = self.uiMap["bounty_main_ui.top_node.right.icon"]
	self.rewardsRightTitleTx = self.uiMap["bounty_main_ui.top_node.right.text"]

	self.line = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.line"]
	local buyLevelItemIcon = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.line.btn.item"]
	local buyLevelItemTx = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.line.btn.tx"]
	local cost = DataManager.BountyData:getBuyBountyLevelCost()
	local costId = GFunc.getRewardId(cost)
	local info = ConfigManager:getConfig("item")[costId]
    if info then
        buyLevelItemIcon:setSprite(GConst.ATLAS_PATH.ICON_ITEM, info.icon)
    end
	local costNum = GFunc.getRewardNum(cost)
	buyLevelItemTx:setText(tostring(costNum))
	GFunc.centerImgAndTx(buyLevelItemIcon, buyLevelItemTx)
	self.buyLevelBtn = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.line.btn"]
	self.buyLevelBtn:addClickListener(function()
		ModuleManager.BountyManager:buyBountyLevel()
	end)

	self.progressBg = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.progress_bg"]
	self.progressComp = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.progress_bg.progress"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER)
	self.rewardsMaskBg = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.mask_img"]

	self.scrollrect = self.uiMap["bounty_main_ui.mid_node.scrollrect"]
	self.scrollrectViewport = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport"]
	self.rewardsContent = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content"]
	self.scrollrectComp = self.scrollrect:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
	self.scrollrectComp:clearCells()
	self.scrollrectComp:setTotalCount(0)
	self.scrollrectComp:addInitCallback(function()
		self.rewardsMaskBg:getTransform():SetAsLastSibling()
		self.line:getTransform():SetAsLastSibling()
		self.repeatRewardRoot:getTransform():SetAsLastSibling()
		return "app/ui/bounty/cell/bounty_cell"
	end)
	self.scrollrectComp:addRefreshCallback(function(index, cell)
		local totalCount = self.scrollrectComp:getTotalCount()
		local isFinalCell = index == totalCount
		if not self.disablePreviewReward then
			if isFinalCell then
				self.rewardCellIdx = index
				self:hidePreviewReward()
			else
				if index > self.rewardCellIdx then
					self.rewardCellIdx = index
					self:showNextPreviewReward()
				elseif index < self.rewardCellIdx - self.rewardCellNum then
					self.rewardCellIdx = index + self.rewardCellNum
					self:showNextPreviewReward()
				end
			end
		end
		cell:refresh(index)
	end)
	self.cellHeight = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.cell"]:getRectHeight()
	local height = self.scrollrect:getRectHeight() - self.scrollrectComp:getTopRecoveryOffset() - self.scrollrectComp:getDownRecoveryOffset()
	self.rewardCellNum = math.ceil(height/self.cellHeight)
end

function BountyMainUI:initRepeatReward()
	self.repeatRewardRoot = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.repeat"]
	self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.repeat.title_tx"]:setText(I18N:getGlobalText(I18N.GlobalConst.REWARD_BOX_DESC))
	self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.repeat.desc_tx"]:setText(I18N:getGlobalText(I18N.GlobalConst.BOUNTY_DESC_3))
	self.repeatBox = self.uiMap["bounty_main_ui.mid_node.scrollrect.viewport.content.repeat.box"]
	self.repeatBox:addClickListener(function()
		if DataManager.BountyData:getIfCanClaimRepeatReward() then
			local level = DataManager.BountyData:getLevel()
			ModuleManager.BountyManager:claimReward(level, false)
		else
			local levelInfo = DataManager.BountyData:getRepeatLevelInfo()
			if levelInfo then
				local reward = levelInfo.reward
				if reward then
					local rewardId = GFunc.getRewardId(reward)
					local rewardType = GFunc.getRewardType(reward)
					ModuleManager.TipsManager:showRewardTips(rewardId, rewardType, self.repeatBox)
				end
			end
		end
	end)
end

function BountyMainUI:bindData()
	self:bind(DataManager.BountyData, "dirty", function()
		self:onRefresh()
	end)
end

function BountyMainUI:onRefresh()
	self:refreshLv()
	self:refreshPayBtn()
	self:refreshPreviewReward(self.previewRewardIndex)
	self:refreshRewards()
end

function BountyMainUI:refreshLv()
	local exp = DataManager.BountyData:getExp()
	local lvUpExp = DataManager.BountyData:getLvUpExp()
	local level = DataManager.BountyData:getLevel()
	local maxLevel = DataManager.BountyData:getMaxLevel()
	self.levelSliderTx:setText(exp .. "/" .. lvUpExp)
	self.levelSlider:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER).value = exp / lvUpExp
	if level >= maxLevel then
		self.lvTx:setText(I18N:getGlobalText(I18N.GlobalConst.STR_MAX))
	else
		self.lvTx:setText(tostring(level))
	end
	local expItemIcon = DataManager.BountyData:getExpItemIcon()
	self.levelItemImg:setSprite(GConst.ATLAS_PATH.ICON_ITEM, expItemIcon)
end

function BountyMainUI:refreshPayBtn()
	if DataManager.BountyData:getBought() then
		self.payBtn:setTouchEnable(false)
		self.payBtnTx:setText(I18N:getGlobalText(I18N.GlobalConst.ALREADY_ACTIVE))
	else
		self.payBtn:setTouchEnable(true)
		self.payBtnTx:setText(I18N:getGlobalText(I18N.GlobalConst.ACTIVE_BOUNTY))
	end
end

function BountyMainUI:refreshPreviewReward(idx)
	local info = DataManager.BountyData:getSeasonInfoByLevel(idx)
	if info == nil then
		return
	end
	self.previewRewardCellComp:refreshByConfig(info.reward_pro)
	self.previewRewardCellComp:setNumTx(GConst.EMPTY_STRING)
	self.previewRewardNumTx:setText("X" .. GFunc.getRewardNum(info.reward_pro))
	self.previewRewardLvTx:setText(I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_1, idx))
end

function BountyMainUI:refreshRewards()
	self.oneKeyBtn:setActive(DataManager.BountyData:canShowOneKeyGetBtn())
	self.rewardsLeftTitleTx:setText(I18N:getGlobalText(I18N.GlobalConst.BOUNTY_FREE_NAME))
	self.rewardsRightTitleTx:setText(I18N:getGlobalText(I18N.GlobalConst.BOUNTY_PURCHASE_NAME))
	if not self.adjustRewardsTitleUI then
		self.adjustRewardsTitleUI = true
		GFunc.centerImgAndTx(self.rewardsLeftTitleIcon, self.rewardsLeftTitleTx, 10)
		GFunc.centerImgAndTx(self.rewardsRightTitleIcon, self.rewardsRightTitleTx, 10)
	end
	local maxLv = DataManager.BountyData:getMaxLevel()
	local lv = DataManager.BountyData:getLevel()
	if self.scrollrectComp:getTotalCount() <= 0 then -- 打开界面的时候定位到当前可领取的最低等级奖励，如果没有则定位到当前等级
		self.scrollrectComp:refillCells(maxLv)
		local level = DataManager.BountyData:getMinUnclaimedRewardIndex()
		if level > 1 then
			self:scrollToIndex(level)
		end
	else
		self.disablePreviewReward = true
		self.scrollrectComp:updateAllCell()
		self.disablePreviewReward = false
	end
	local topRecoveryOffset = self.scrollrectComp:getTopRecoveryOffset()
	local downRecoveryOffset = self.scrollrectComp:getDownRecoveryOffset()
	local cellHeight = self.scrollrectComp:getCellHeight()
	if lv >= maxLv then
		self.line:setVisible(false)
	else
		self.line:setVisible(true)
		self.line:setAnchoredPositionY(-topRecoveryOffset - lv*cellHeight)
	end

	self.progressBg:setAnchoredPositionY((topRecoveryOffset + downRecoveryOffset)/2 - cellHeight/2)
	self.progressBg:setSizeDeltaY(cellHeight*(maxLv - 1))
	local percent = (lv - 1) / (maxLv - 1)
	if percent < 0 then
		percent = 0
	end
	self.progressComp.value = percent

	self.rewardsMaskBg:setAnchoredPositionY(-topRecoveryOffset - lv*cellHeight)
	self.rewardsMaskBg:setSizeDeltaY(cellHeight*maxLv + GConst.UI_SCREEN_HEIGHT)

	self.repeatRewardRoot:setAnchoredPositionY(downRecoveryOffset)
	if DataManager.BountyData:getIfCanClaimRepeatReward() then
		self.repeatRewardRoot:addRedPoint(74, 15)
	else
		self.repeatRewardRoot:removeRedPoint()
	end
end

function BountyMainUI:showNextPreviewReward()
	local nextRewardIndex = -1
	local maxLevel = DataManager.BountyData:getMaxLevel()
	for i = self.rewardCellIdx, maxLevel do
		local info = DataManager.BountyData:getSeasonInfoByLevel(i)
		if info and info.reward_type and info.reward_type == 1 then
			nextRewardIndex = i
			break
		end
	end
	if self.previewRewardIndex == nextRewardIndex then
		return
	end
	self.previewRewardIndex = nextRewardIndex
	if nextRewardIndex <= 0 then
		self:hidePreviewReward()
	else
		self.previewReward:setVisible(true)
		self:showPreviewRewardAnimation()
	end
end

function BountyMainUI:showPreviewRewardAnimation()
	local time = 0.3
	local maxY = 106
	local moveOutTime = 0
	local posY = self.previewReward:getAnchoredPositionY()
	if posY > 0.1 then
		moveOutTime = time/maxY*posY
		if self.previewRewardMoveOutTween == nil then
			self.previewRewardMoveOutTween = self.previewReward:getTransform():DOAnchorPosY(0, moveOutTime):SetEase(CS.DG.Tweening.Ease.InCubic)
			self.previewRewardMoveOutTween:SetAutoKill(false)
		else
			local CacheVector2 = BF.CacheVector2
			CacheVector2.x = 0
			CacheVector2.y = 0
			self.previewRewardMoveOutTween:ChangeEndValue(CacheVector2, moveOutTime, true)
			self.previewRewardMoveOutTween:Restart()
		end
	end
	if self.showPreviewRewardSid then
		self:unscheduleGlobal(self.showPreviewRewardSid)
	end
	self.showPreviewRewardSid = self:performWithDelayGlobal(function()
		self.showPreviewRewardSid = nil
		if self.previewRewardIndex > 0 then
			self:refreshPreviewReward(self.previewRewardIndex)
		end
		if self.previewRewardMoveInTween == nil then
			self.previewRewardMoveInTween = self.previewReward:getTransform():DOAnchorPosY(maxY, time):SetEase(CS.DG.Tweening.Ease.InCubic)
			self.previewRewardMoveInTween:SetAutoKill(false)
		else
			local CacheVector2 = BF.CacheVector2
			CacheVector2.x = 0
			CacheVector2.y = maxY
			self.previewRewardMoveInTween:ChangeEndValue(CacheVector2, time, true)
			self.previewRewardMoveInTween:Restart()
		end
	end, moveOutTime)
end

function BountyMainUI:hidePreviewReward()
	self.previewReward:setVisible(false)
	if self.previewRewardMoveOutTween then
		self.previewRewardMoveOutTween:Pause()
	end
	if self.previewRewardMoveInTween then
		self.previewRewardMoveInTween:Pause()
	end
	self.previewReward:setAnchoredPositionY(0)
end

function BountyMainUI:clearPreviewRewardAnimation()
	if self.previewRewardMoveInTween then
		self.previewRewardMoveInTween:Kill()
		self.previewRewardMoveInTween = nil
	end
	if self.previewRewardMoveOutTween then
		self.previewRewardMoveOutTween:Kill()
		self.previewRewardMoveOutTween = nil
	end
	if self.showPreviewRewardSid then
		self:unscheduleGlobal(self.showPreviewRewardSid)
		self.showPreviewRewardSid = nil
	end
end

function BountyMainUI:scrollToIndex(targetIndex)
	-- 未避免scrollrect没填充完毕，延迟一帧执行
	if self.rewardsContentSid then
		self:unscheduleGlobal(self.rewardsContentSid)
	end
	self.rewardsContentSid = self:performWithDelayGlobal(function()
		self.rewardsContentSid = nil
		if self.rewardsContentMaxY == nil then
			local maxLv = DataManager.BountyData:getMaxLevel()
			self.rewardsContentMaxY = maxLv*self.cellHeight + self.scrollrectComp:getTopRecoveryOffset() + self.scrollrectComp:getDownRecoveryOffset() - self.scrollrectViewport:getRectHeight()
		end
		-- 最多移动6格,超过6格就先整体移动后再移动6格
		local moveTimePerCell = 0.05
		local moveCount = 6
		local moveTime = moveCount * moveTimePerCell
		if targetIndex > 7 then
			local tartgetY = (targetIndex - 7)*self.cellHeight
			if tartgetY > self.rewardsContentMaxY then
				self.rewardsContent:setAnchoredPositionY(self.rewardsContentMaxY)
				return
			else
				self.rewardsContent:setAnchoredPositionY(tartgetY)
			end
		else
			moveTime = (targetIndex - 1) * moveTimePerCell
		end
		local y = (targetIndex - 1) * self.cellHeight
		if y > self.rewardsContentMaxY then
			y = self.rewardsContentMaxY
		end
		if self.rewardsContentMoveTween == nil then
			self.rewardsContentMoveTween = self.rewardsContent:getTransform():DOAnchorPosY(y, moveTime)
			self.rewardsContentMoveTween:SetAutoKill(false)
		else
			local CacheVector2 = BF.CacheVector2
			CacheVector2.x = 0
			CacheVector2.y = y
			self.rewardsContentMoveTween:ChangeEndValue(CacheVector2, moveTime, true)
			self.rewardsContentMoveTween:Restart()
		end
	end, 0)
end

function BountyMainUI:updateTime()
	local remainTime = self.endTime - Time:getServerTime()
	if remainTime < 0 then
		UIManager:closeUnderUI(self)
		return self:closeUI()
	end
	self.timeTx:setText(GFunc.getTimeStr(remainTime))
	if not self.adjustTimeUI then
		self.adjustTimeUI = true
		GFunc.centerImgAndTx(self.timeIcon, self.timeTx, 4)
	end
end

return BountyMainUI