local TournArenaRankComp = class("TournArenaRankComp", LuaComponent)

local SHOW_TYPE = {
    CUR_RANK = 1,
    LAST_RANK = 2,
    REWARD = 3,
}

local RANK_IMG = {"act_ranking_1", "act_ranking_2", "act_ranking_3"}

function TournArenaRankComp:onClose()
    if self.countdownSid then
        self.baseObject:unscheduleGlobal(self.countdownSid)
        self.countdownSid = nil
    end
end

function TournArenaRankComp:init()
    local uiMap = self:getUIMap()

    self.txEmpty = uiMap["rank_panel.tx_empty"]
    self.btnHelp = uiMap["rank_panel.btn_help"]
    self.btns = uiMap["rank_panel.btns"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT)
    self.btnCur = uiMap["rank_panel.btns.btn_cur"]
    self.txCur = uiMap["rank_panel.btns.btn_cur.tx_cur"]
    self.btnLast = uiMap["rank_panel.btns.btn_last"]
    self.txLast = uiMap["rank_panel.btns.btn_last.tx_last"]
    self.btnReward = uiMap["rank_panel.btns.btn_reward"]
    self.txReward = uiMap["rank_panel.btns.btn_reward.tx_reward"]
    self.txCountdown = uiMap["rank_panel.tx_countdown"]
    self.listRewardComp = uiMap["rank_panel.list_reward"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.listRankComp = uiMap["rank_panel.list_rank"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    -- 自己排名
    self.imgRank = uiMap["rank_panel.my_rank.img_rank"]
    self.txRank = uiMap["rank_panel.my_rank.tx_rank"]
    self.txName = uiMap["rank_panel.my_rank.tx_name"]
    self.txScore = uiMap["rank_panel.my_rank.tx_score"]
    self.playerHeadCell = uiMap["rank_panel.my_rank.player_head_cell"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.PLAYER_HEAD_CELL)
    self.rewards = uiMap["rank_panel.my_rank.rewards"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT)
    self.rewardCells = {}
    for i = 1, 3 do
        table.insert(self.rewardCells, uiMap["rank_panel.my_rank.rewards.reward_cell_" .. i]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.REWARD_CELL))
    end

    self.txEmpty:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_BOSS_RUSH_DESC_8))
    self.txCur:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_WAVE_BTN_1))
    self.txLast:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_WAVE_BTN_2))
    self.txReward:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_WAVE_BTN_3))

	self.listRankComp:addInitCallback(function()
		return "app/ui/activity/tourn_arena/cell/tourn_arena_rank_cell"
	end)
	self.listRankComp:addRefreshCallback(function(index, cell)
		cell:refresh(index, self.rankDataList[index])
	end)
	self.listRewardComp:addInitCallback(function()
		return "app/ui/activity/tourn_arena/cell/tourn_arena_rank_reward_cell"
	end)
	self.listRewardComp:addRefreshCallback(function(index, cell)
		cell:refresh(index)
	end)

    self.btnHelp:addClickListener(function()
        local str = I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_ARENEA_HELP_1) .. "\n"
        for id, data in ipairs(ConfigManager:getConfig("activity_tourn_arena_point")) do
            str = str .. "\n" .. I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_ARENEA_HELP_2, I18N:getGlobalText(I18N.GlobalConst["ARENA_RANKNAME_" .. id]), data.point_win, data.point_lose)
        end

        local params = {
            type = GConst.TipsConst.HELP_TIPS_TYPE.ARENA,
            title = I18N:getGlobalText(I18N.GlobalConst.COLLECTION_DESC_11),
            desc = str,
        }
        ModuleManager.TipsManager:showHelpTips(params)
    end)
    self.btnCur:addClickListener(function()
        ModuleManager.TournArenaManager:reqRankList(DataManager.TournArenaData:getCurRankStep())
        self:refresh(SHOW_TYPE.CUR_RANK)
    end)
    self.btnLast:addClickListener(function()
        local curStep = DataManager.TournArenaData:getCurRankStep()
        ModuleManager.TournArenaManager:reqRankList(curStep > 0 and curStep - 1 or DataManager.TournArenaData:getTotalTurnCount())
        self:refresh(SHOW_TYPE.LAST_RANK)
    end)
    self.btnReward:addClickListener(function()
        self:refresh(SHOW_TYPE.REWARD)
    end)
    self:bind(DataManager.TournArenaData, "isDirty", function()
        self:refresh()
	end)
end

function TournArenaRankComp:refresh(showType)
    self.showType = showType or self.showType or (DataManager.TournArenaData:isFinalDay() and SHOW_TYPE.LAST_RANK or SHOW_TYPE.CUR_RANK)

    self.btnCur:setSprite(GConst.ATLAS_PATH.COMMON, self.showType == SHOW_TYPE.CUR_RANK and "common_board_130" or "common_board_134")
    self.btnLast:setSprite(GConst.ATLAS_PATH.COMMON, self.showType == SHOW_TYPE.LAST_RANK and "common_board_130" or "common_board_134")
    self.btnReward:setSprite(GConst.ATLAS_PATH.COMMON, self.showType == SHOW_TYPE.REWARD and "common_board_130" or "common_board_134")

    local curStep = DataManager.TournArenaData:getCurRankStep()
    self.btnCur:setActive(DataManager.TournArenaData:isFinalDay() == false)
    self.btnLast:setActive(curStep > 1 or curStep == 0)
    self.btns:RefreshLayout()

    if self.showType == SHOW_TYPE.CUR_RANK then
        self:showRankList(curStep)
        self:showSelfRank(curStep)
    elseif self.showType == SHOW_TYPE.LAST_RANK then
        local lastStep = curStep > 0 and curStep - 1 or DataManager.TournArenaData:getTotalTurnCount()
        self:showRankList(lastStep)
        self:showSelfRank(lastStep)
    elseif self.showType == SHOW_TYPE.REWARD then
        self:showRankReward()
        self:showSelfRank(curStep)
    end
    self:refreshCountdown()
end

-- 展示自己排名
function TournArenaRankComp:showSelfRank(step)
    local rank = DataManager.TournArenaData:getSelfRank(step)
    local score = DataManager.TournArenaData:getSelfScore(step)

    if score > 0 then
        if RANK_IMG[rank] then
            self.imgRank:setActive(true)
            self.imgRank:setSprite(GConst.ATLAS_PATH.ACT_COMMON, RANK_IMG[rank])
            self.txRank:setText(GConst.EMPTY_STRING)
        else
            self.imgRank:setActive(false)
            self.txRank:setText(rank)
        end
    else
        self.imgRank:setActive(false)
        self.txRank:setText("--")
    end
    self.playerHeadCell:refresh()
    self.txName:setText(DataManager.PlayerData:getNickname())
    self.txScore:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_16)..":"..score)

    local isReceived = step ~= DataManager.TournArenaData:getCurRankStep() and DataManager.TournArenaData:isReceivedRankReward()
    local rewards = DataManager.TournArenaData:getRewardByRank(rank)
    for index, cell in ipairs(self.rewardCells) do
        if score > 0 and rewards[index] then
            cell:setVisible(true)
            cell:refreshByConfig(rewards[index], isReceived, isReceived)
            if step ~= DataManager.TournArenaData:getCurRankStep() and DataManager.TournArenaData:isReachRankReward() then
                cell.baseObject:addRedPoint(50, 50, 0.6)
                cell:addClickListener(function()
                    ModuleManager.TournArenaManager:reqRankReward()
                end)
            else
                cell.baseObject:removeRedPoint()
                cell:addClickListener(nil)
            end
        else
            cell:setVisible(false)
        end
    end
    self.rewards:RefreshLayout()
end

-- 展示榜单
function TournArenaRankComp:showRankList(step)
    self.listRankComp:getBaseObject():setActive(true)
    self.listRewardComp:getBaseObject():setActive(false)

    self.rankDataList = DataManager.TournArenaData:getRankListData(step)
    if self.rankDataList == nil then
        self.rankDataList = {}
    end
    self.listRankComp:clearCells()
	self.listRankComp:refillCells(#self.rankDataList)
    self.txEmpty:setActive(#self.rankDataList <= 0)
end

-- 展示排行榜奖励
function TournArenaRankComp:showRankReward()
    self.listRankComp:getBaseObject():setActive(false)
    self.listRewardComp:getBaseObject():setActive(true)
    self.txEmpty:setActive(false)

    self.rankIdList = DataManager.TournArenaData:getRankIdList()
    self.listRewardComp:clearCells()
	self.listRewardComp:refillCells(#self.rankIdList)
end

-- 刷新倒计时
function TournArenaRankComp:refreshCountdown()
    if self.countdownSid then
		self.baseObject:unscheduleGlobal(self.countdownSid)
	end
    if DataManager.TournArenaData:isFinalDay() then
        -- 活动最后一天
        self.txCountdown:setText(I18N:getGlobalText(I18N.GlobalConst.EVENT_COUNTDOWN) .. Time:formatNumTimeStr(DataManager.TournArenaData:getEndRemainTime()))
        self.countdownSid = self.baseObject:scheduleGlobal(function()
            local time = DataManager.TournArenaData:getEndRemainTime()
            if time >= 0 then
                self.txCountdown:setText(I18N:getGlobalText(I18N.GlobalConst.EVENT_COUNTDOWN) .. Time:formatNumTimeStr(time))
            end
        end, 1)
    else
        -- 分组中
        local time = DataManager.TournArenaData:getCurRankStepRemainTime()
        if time < 0 then
            return
        end

        local str = DataManager.TournArenaData:getCurRankStep() >= DataManager.TournArenaData:getTotalTurnCount() and I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_WAVE_DESC_3) or I18N:getGlobalText(I18N.GlobalConst.ACT_TOURN_WAVE_DESC_2)

        self.txCountdown:setText(str .. Time:formatNumTimeStr(time))
        self.countdownSid = self.baseObject:scheduleGlobal(function()
            local time = DataManager.TournArenaData:getCurRankStepRemainTime()
            if time >= 0 then
                self.txCountdown:setText(str .. Time:formatNumTimeStr(time))
            else
                self.baseObject:unscheduleGlobal(self.countdownSid)
                if self.showType == SHOW_TYPE.CUR_RANK then
                    ModuleManager.TournArenaManager:reqRankList(DataManager.TournArenaData:getCurRankStep())
                elseif self.showType == SHOW_TYPE.LAST_RANK then
                    ModuleManager.TournArenaManager:reqRankList(DataManager.TournArenaData:getCurRankStep() - 1)
                end
            end
        end, 1)
    end
end

return TournArenaRankComp