local TaskMainUI = class("TaskMainUI", BaseUI)

local PAGE_DAILY = 1
local PAGE_CHALLENGE = 2
local TASK_TYPE_DAILY = 1
local DAILY_TASK_CELL = "app/ui/task/cell/daily_task_cell"

local function sortTask(taskList)
	table.sort(taskList, function(a, b)
		if a.claimed == b.claimed then
			if a.claimed then
				return a.id < b.id
			else
				local completeA = a.progress >= a.needProgress
				local completeB = b.progress >= b.needProgress
				if completeA == completeB then
					if completeA then
						return a.id < b.id
					else -- 没有完成的优先显示战令解锁
						if a.lock == b.lock then
							return a.id < b.id
						else
							return b.lock
						end
					end
				else
					return completeA
				end
			end
		else
			return b.claimed
		end
	end)
end

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

function TaskMainUI:ctor(params)
	self.page = params and params.page or PAGE_DAILY
	self.dailyTaskList = {}
	self.challengeTaskList = {}
	self:initTaskList()
	if DataManager.DailyTaskData:getIfCanReset() then
		ModuleManager.TaskManager:resetDailyTask()
	end
end

function TaskMainUI:isFullScreen()
    return false
end

function TaskMainUI:getPrefabPath()
    return "assets/prefabs/ui/task/task_main_ui.prefab"
end

function TaskMainUI:initTaskList()
	for i = 1, #self.dailyTaskList do
		table.remove(self.dailyTaskList)
	end
	for i = 1, #self.challengeTaskList do
		table.remove(self.challengeTaskList)
	end
	local taskAdId = DataManager.DailyTaskData:getDailyTaskAdId()
	local taskFinalId = DataManager.DailyTaskData:getDailyTaskFinalId()
	local dailyTasks = DataManager.DailyTaskData:getDailyTasks()
	for k, v in pairs(dailyTasks) do
		if k ~= taskAdId and k ~= taskFinalId then
			if v.type == TASK_TYPE_DAILY then
				table.insert(self.dailyTaskList, v)
			else
				table.insert(self.challengeTaskList, v)
			end
		end
	end
	sortTask(self.dailyTaskList)
	sortTask(self.challengeTaskList)
	-- 审核模式不显示战令任务
	if GFunc.isShenhe() then
		for i = #self.dailyTaskList, 1, -1 do
			local task = self.dailyTaskList[i]
			if task.lock then
				table.remove(self.dailyTaskList, i)
			end
		end
		for i = #self.challengeTaskList, 1, -1 do
			local task = self.challengeTaskList[i]
			if task.lock then
				table.remove(self.challengeTaskList, i)
			end
		end
	end
end

function TaskMainUI:onClose()
	if self.menuOneRedPointTween then
		self.menuOneRedPointTween:Kill()
	end
	if self.menuTwoRedPointTween then
		self.menuTwoRedPointTween:Kill()
	end
end

function TaskMainUI:onLoadRootComplete()
    self.uiMap = self.root:genAllChildren()
	self.uiMap["task_main_ui.bg.close_btn"]:addClickListener(function()
		self:closeUI()
	end)

	self:initTitle()
	self:initPage()
	self:initCountDown()
	self:bindData()
	self:scheduleGlobal(function()
		self:updateTime()
	end, 1)
	self:updateTime()
end

function TaskMainUI:initTitle()
	self.titleTx = self.uiMap["task_main_ui.bg.title"]
	self.titleTx:setText(I18N:getGlobalText(I18N.GlobalConst.TASK_NAME))
end

function TaskMainUI:initPage()
	self.menuOne = self.uiMap["task_main_ui.bg.menu_1"]
	self.menuOne:addClickListener(function()
		self:switchPage(PAGE_DAILY)
	end)
	self.menuOneOn = self.uiMap["task_main_ui.bg.menu_1.on"]
	self.menuOneOff = self.uiMap["task_main_ui.bg.menu_1.off"]
	local menuOneOnTx = self.uiMap["task_main_ui.bg.menu_1.on.text"]
	menuOneOnTx:setText(I18N:getGlobalText(I18N.GlobalConst.TASK_DAILY))
	local menuOneOffTx = self.uiMap["task_main_ui.bg.menu_1.off.text"]
	menuOneOffTx:setText(I18N:getGlobalText(I18N.GlobalConst.TASK_DAILY))
	self.menuOneRedPoint = self.uiMap["task_main_ui.bg.red_point_1"]

	self.menuTwo = self.uiMap["task_main_ui.bg.menu_2"]
	self.menuTwo:addClickListener(function()
		self:switchPage(PAGE_CHALLENGE)
	end)
	self.menuTwoOn = self.uiMap["task_main_ui.bg.menu_2.on"]
	self.menuTwoOff = self.uiMap["task_main_ui.bg.menu_2.off"]
	local menuTwoOnTx = self.uiMap["task_main_ui.bg.menu_2.on.text"]
	menuTwoOnTx:setText(I18N:getGlobalText(I18N.GlobalConst.TASK_CHALLENGE))
	local menuTwoOffTx = self.uiMap["task_main_ui.bg.menu_2.off.text"]
	menuTwoOffTx:setText(I18N:getGlobalText(I18N.GlobalConst.TASK_CHALLENGE))
	self.menuTwoRedPoint = self.uiMap["task_main_ui.bg.red_point_2"]
	self:initDaily()
	self:initChallenge()
end

function TaskMainUI:initDaily()
	self.dailyNode = self.uiMap["task_main_ui.bg.daily"]
	self:initDailyTaskAdCell()
	self:initDailyTaskFinalCell()
end

function TaskMainUI:initDailyTaskAdCell()
	self.dailyTaskAdCellNameTx = self.uiMap["task_main_ui.bg.daily.task_ad_cell.name_tx"]
	self.dailyTaskAdCellProgress = self.uiMap["task_main_ui.bg.daily.task_ad_cell.progress"]
	self.dailyTaskAdCellProgressTx = self.uiMap["task_main_ui.bg.daily.task_ad_cell.progress_tx"]
	self.dailyTaskAdCellBox = self.uiMap["task_main_ui.bg.daily.task_ad_cell.box"]
	self.dailyTaskAdCellBox:addClickListener(function()
		local taskId = DataManager.DailyTaskData:getDailyTaskAdId()
		if DataManager.DailyTaskData:getDailyTaskCanClaimTask(taskId) then
			ModuleManager.TaskManager:claimDailyTask(taskId)
		else
			local reward = DataManager.DailyTaskData:getDailyTaskAdReward()
			if reward and reward[1] then
				local rewardId = GFunc.getRewardId(reward[1])
				local rewardType = GFunc.getRewardType(reward[1])
				ModuleManager.TipsManager:showRewardTips(rewardId, rewardType, self.dailyTaskAdCellBox)
			end
		end
	end)
	self.dailyTaskAdCellBoxInfo = self.uiMap["task_main_ui.bg.daily.task_ad_cell.box.info"]
	self.adBoxSpineObj = self.uiMap["task_main_ui.bg.daily.task_ad_cell.box.ui_spine_obj"]
end

function TaskMainUI:initDailyTaskFinalCell()
	self.dailyTaskFinalCellNameTx = self.uiMap["task_main_ui.bg.daily.task_final_cell.name_tx"]
	self.dailyTaskFinalCellProgress = self.uiMap["task_main_ui.bg.daily.task_final_cell.progress"]
	self.dailyTaskFinalCellProgressTx = self.uiMap["task_main_ui.bg.daily.task_final_cell.progress_tx"]
	self.dailyTaskFinalCellBox = self.uiMap["task_main_ui.bg.daily.task_final_cell.box"]
	self.dailyTaskFinalCellBox:addClickListener(function()
		local taskId = DataManager.DailyTaskData:getDailyTaskFinalId()
		if DataManager.DailyTaskData:getDailyTaskCanClaimTask(taskId) then
			ModuleManager.TaskManager:claimDailyTask(taskId)
		else
			local reward = DataManager.DailyTaskData:getDailyTaskFinalReward()
			if reward and reward[1] then
				local rewardId = GFunc.getRewardId(reward[1])
				local rewardType = GFunc.getRewardType(reward[1])
				ModuleManager.TipsManager:showRewardTips(rewardId, rewardType, self.dailyTaskFinalCellBox)
			end
		end
	end)
	self.dailyTaskFinalCellBoxInfo = self.uiMap["task_main_ui.bg.daily.task_final_cell.box.info"]
	self.finalBoxSpineObj = self.uiMap["task_main_ui.bg.daily.task_final_cell.box.ui_spine_obj"]
end

function TaskMainUI:initDailyTasks()
	self.dailyTaskScrollRect = self.uiMap["task_main_ui.bg.daily.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.dailyTaskScrollRect:addInitCallback(function()
        return DAILY_TASK_CELL
    end)
    self.dailyTaskScrollRect:addRefreshCallback(function(index, cell)
        cell:refresh(self.dailyTaskList[index])
    end)
    self.dailyTaskScrollRect:clearCells()
    self.dailyTaskScrollRect:refillCells(#self.dailyTaskList)
end

function TaskMainUI:initChallenge()
	self.challengeNode = self.uiMap["task_main_ui.bg.challenge"]
end

function TaskMainUI:initChallengeTasks()
	self.challengeTaskScrollRect = self.uiMap["task_main_ui.bg.challenge.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.challengeTaskScrollRect:addInitCallback(function()
        return DAILY_TASK_CELL
    end)
    self.challengeTaskScrollRect:addRefreshCallback(function(index, cell)
        cell:refresh(self.challengeTaskList[index])
    end)
    self.challengeTaskScrollRect:clearCells()
    self.challengeTaskScrollRect:refillCells(#self.challengeTaskList)
end

function TaskMainUI:initCountDown()
	local helpBtn = self.uiMap["task_main_ui.bg.time_btn"]
	helpBtn:addClickListener(function()
		self:showHelp()
	end)
	self.timeTx = self.uiMap["task_main_ui.bg.time_tx"]
end

function TaskMainUI:bindData()
	self:bind(DataManager.DailyTaskData, "dailyTaskDirty", function()
		if self.delayRefreshSid then
			self:unscheduleGlobal(self.delayRefreshSid)
		end
		self.delayRefreshSid = self:performWithDelayGlobal(function()
			self.delayRefreshSid = nil
			sortTask(self.dailyTaskList)
			sortTask(self.challengeTaskList)
			self:onRefresh()
		end, 0.1)
	end)
	self:bind(DataManager.DailyTaskData, "resetFlag", function()
		if self.delayRefreshSid then
			self:unscheduleGlobal(self.delayRefreshSid)
		end
		self.delayRefreshSid = self:performWithDelayGlobal(function()
			self.delayRefreshSid = nil
			self:initTaskList()
			self:onRefresh()
		end, 0.1)
	end)
end

function TaskMainUI:onRefresh()
	self:switchPage(self.page)
end

function TaskMainUI:switchPage(page)
	self.page = page
	if page == PAGE_DAILY then
		self.menuOneOn:setVisible(true)
		self.menuOneOff:setVisible(false)
		self.menuTwoOn:setVisible(false)
		self.menuTwoOff:setVisible(true)
		self.dailyNode:setAnchoredPositionX(0)
		self.challengeNode:setAnchoredPositionX(GConst.NOT_VISIBLE_POS)
		self:refreshDaily()
		if DataManager.DailyTaskData:getIsShowChallengeTaskRedPoint() then
			self.menuTwoRedPoint:setVisible(true)
			if self.menuTwoRedPointTween == nil then
				self.menuTwoRedPointTween = self:getShakeTween(self.menuTwoRedPoint)
			else
				self.menuTwoRedPointTween:Restart()
			end
		else
			if self.menuTwoRedPointTween then
				self.menuTwoRedPointTween:Pause()
			end
			self.menuTwoRedPoint:setVisible(false)
		end
		if self.menuOneRedPointTween then
			self.menuOneRedPointTween:Pause()
		end
		self.menuOneRedPoint:setVisible(false)
	else
		self.menuOneOn:setVisible(false)
		self.menuOneOff:setVisible(true)
		self.menuTwoOn:setVisible(true)
		self.menuTwoOff:setVisible(false)
		self.dailyNode:setAnchoredPositionX(GConst.NOT_VISIBLE_POS)
		self.challengeNode:setAnchoredPositionX(0)
		self:refreshChallenge()
		if DataManager.DailyTaskData:getIsShowDailyTaskRedPoint() then
			self.menuOneRedPoint:setVisible(true)
			if self.menuOneRedPointTween == nil then
				self.menuOneRedPointTween = self:getShakeTween(self.menuOneRedPoint)
			else
				self.menuOneRedPointTween:Restart()
			end
		else
			if self.menuOneRedPointTween then
				self.menuOneRedPointTween:Pause()
			end
			self.menuOneRedPoint:setVisible(false)
		end
		if self.menuTwoRedPointTween then
			self.menuTwoRedPointTween:Pause()
		end
		self.menuTwoRedPoint:setVisible(false)
	end
end

function TaskMainUI:refreshDaily()
	self:refreshDailyTaskAdCell()
	self:refreshDailyTaskFinalCell()
	self:refreshDailyTasks()
end

function TaskMainUI:refreshDailyTaskAdCell()
	local taskId = DataManager.DailyTaskData:getDailyTaskAdId()
	local taskDesc = DataManager.DailyTaskData:getDailyTaskDesc(taskId)
	self.dailyTaskAdCellNameTx:setText(taskDesc)
	local count, needCount = DataManager.DailyTaskData:getDailyTaskProgress(taskId)
	if count >= needCount then
		count = needCount
	end
	if DataManager.DailyTaskData:getDailyTaskCanClaimTask(taskId) then
		self.dailyTaskAdCellBoxInfo:setVisible(false)
		self.dailyTaskAdCellBox:addRedPoint(40, 28, 0.7)
		self.adBoxSpineObj:playAnim("ready", true, false)
		self.curAdCanGet = true
	else
		self.dailyTaskAdCellBoxInfo:setVisible(true)
		self.dailyTaskAdCellBox:removeRedPoint()

		if self.curAdCanGet then
			self.adBoxSpineObj:playAnimComplete("open", false, true, function()
				self.adBoxSpineObj:playAnim("idle01", true, false)
			end)
		else
			self.adBoxSpineObj:playAnim("idle01", true, false)
		end

		self.curAdCanGet = false
	end
	self.dailyTaskAdCellProgressTx:setText(count .. "/" .. needCount)
	self.dailyTaskAdCellProgress:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER).value = count/needCount
end

function TaskMainUI:refreshDailyTaskFinalCell()
	local taskId = DataManager.DailyTaskData:getDailyTaskFinalId()
	local taskDesc = DataManager.DailyTaskData:getDailyTaskDesc(taskId)
	self.dailyTaskFinalCellNameTx:setText(taskDesc)
	local count, needCount = DataManager.DailyTaskData:getDailyTaskProgress(taskId)
	if count > needCount then
		count = needCount
	end
	if DataManager.DailyTaskData:getDailyTaskCanClaimTask(taskId) then
		self.dailyTaskFinalCellBoxInfo:setVisible(false)
		self.dailyTaskFinalCellBox:addRedPoint(40, 28, 0.7)
		self.finalBoxSpineObj:playAnim("ready", true, false)
		self.curFinalCanGet = true
	else
		self.dailyTaskFinalCellBoxInfo:setVisible(true)
		self.dailyTaskFinalCellBox:removeRedPoint()
		if DataManager.DailyTaskData:getDailyTaskCalaimed(taskId) then
			if self.curFinalCanGet then
				self.finalBoxSpineObj:playAnimComplete("open", false, true, function()
					self.finalBoxSpineObj:playAnim("idle02", true, false)
				end)
			else
				self.finalBoxSpineObj:playAnim("idle02", true, false)
			end
		else
			self.finalBoxSpineObj:playAnim("idle01", true, false)
		end
		self.curFinalCanGet = false
	end
	self.dailyTaskFinalCellProgressTx:setText(count .. "/" .. needCount)
	self.dailyTaskFinalCellProgress:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER).value = count/needCount
end

function TaskMainUI:refreshDailyTasks()
	if self.dailyTaskScrollRect == nil then
		self:initDailyTasks()
	else
		if self.dailyTaskScrollRect:getTotalCount() == #self.dailyTaskList then
			self.dailyTaskScrollRect:updateAllCell()
		else
			self.dailyTaskScrollRect:clearCells()
			self.dailyTaskScrollRect:refillCells(#self.dailyTaskList)
		end
	end
end

function TaskMainUI:refreshChallenge()
	if self.challengeTaskScrollRect == nil then
		self:initChallengeTasks()
	else
		if self.challengeTaskScrollRect:getTotalCount() == #self.challengeTaskList then
			self.challengeTaskScrollRect:updateAllCell()
		else
			self.challengeTaskScrollRect:clearCells()
			self.challengeTaskScrollRect:refillCells(#self.challengeTaskList)
		end
	end
end

function TaskMainUI:showHelp()
	local params = {
		content = I18N:getGlobalText(I18N.GlobalConst.TASK_HELP_1),
		boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
		okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
	}
	GFunc.showMessageBox(params)
end

function TaskMainUI:updateTime()
	local time = DataManager.DailyTaskData:getDailyResetTime()
	if self.resetTime == time then
		return
	end
	if DataManager.DailyTaskData:getIfCanReset() then -- 跨天了
		ModuleManager.TaskManager:resetDailyTask()
	end
	self.resetTime = time
	self.timeTx:setText(GFunc.getTimeStrWithHMS2(self.resetTime))
end

function TaskMainUI:getShakeTween(obj)
	return GFunc.getShakeSeq(obj, false, 1, true)
end

return TaskMainUI