local ActPvpRankUI = class("ActPvpRankUI", BaseUI)

local RANK_REWARD_CELL = "app/ui/activity/act_pvp/cell/rank_reward_cell"
local RANK_CELL = "app/ui/activity/act_pvp/cell/rank_cell"
local TOP_RANK_CELL = "app/ui/activity/act_pvp/cell/top_rank_cell"

local PAGE_ICON = {"common_menu_1", "common_menu_2"}

local PAGE_TYPE = {
    RANK = 1,
    REWARD = 2,
}

local PAGE_TX = {
    [PAGE_TYPE.RANK] = I18N.GlobalConst.ACT_BOSS_RUSH_DESC_24,
    [PAGE_TYPE.REWARD] = I18N.GlobalConst.ACT_BOSS_RUSH_DESC_22,
}

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

function ActPvpRankUI:isFullScreen()
    return false
end

function ActPvpRankUI:getPrefabPath()
    return "assets/prefabs/ui/activity/act_pvp/act_pvp_rank_ui.prefab"
end

function ActPvpRankUI:ctor()
    self.rankRewardList = {}
    self.rankRewardListCount = 0
    local cfg = DataManager.ActPvpData:getRankConfig()
    Logger.printTable(DataManager.ActPvpData:getRankRewardList())
    for index, id in ipairs(DataManager.ActPvpData:getRankRewardList()) do
        local info = cfg[id]
        table.insert(self.rankRewardList, {id = id, ranking1 = info.ranking[1], ranking2 = info.ranking[2], rewards = info.reward})
        self.rankRewardListCount = self.rankRewardListCount + 1
    end
end

function ActPvpRankUI:onLoadRootComplete()
    self:_display()
    self:_addListeners()
    self:_bind()

    self:refreshTime()
    if self.actCountdownSid then
        self:unscheduleGlobal(self.actCountdownSid)
    end
    self.actCountdownSid = self:scheduleGlobal(function()
        self:refreshTime()
	end, 1)
end

function ActPvpRankUI:_display()
    local uiMap = self.root:genAllChildren()
    uiMap["act_pvp_rank_ui.bg.rank_node.rank_desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_BOSS_RUSH_DESC_24))
    uiMap["act_pvp_rank_ui.bg.rank_node.player_desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_BOSS_RUSH_DESC_25))
    uiMap["act_pvp_rank_ui.bg.rank_node.record_desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_BOSS_RUSH_DESC_26))

    if not DataManager.ActPvpData:isFinalDay() then
        self:switchPage(PAGE_TYPE.RANK)
    else
        self:switchPage(PAGE_TYPE.REWARD)
    end
end

function ActPvpRankUI:_addListeners()
    local uiMap = self.root:genAllChildren()
    uiMap["act_pvp_rank_ui.close_btn"]:addClickListener(function()
        self:closeUI()
    end)

    uiMap["act_pvp_rank_ui.bg.rank_bg.btn_help"]:addClickListener(function()
        local params = {
            type = GConst.TipsConst.HELP_TIPS_TYPE.NORMAL,
            title = I18N:getGlobalText(I18N.GlobalConst.COLLECTION_DESC_11),
            desc = I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_18),
        }
        ModuleManager.TipsManager:showHelpTips(params)
    end)
end

function ActPvpRankUI:_bind()
    self:bind(DataManager.ActPvpData, "isDirty", function()
        if self.curPage ~= PAGE_TYPE.REWARD then
            self:refreshRankNode()
        else
            self:refreshRewardNode()
        end
        self:refreshMyRankInfo()
        self:refreshPages()
    end)
end

function ActPvpRankUI:refreshRankNode()
    local uiMap = self.root:genAllChildren()
    uiMap["act_pvp_rank_ui.bg.rank_node"]:setActive(true)
    uiMap["act_pvp_rank_ui.bg.reward_node"]:setActive(false)
    local text = I18N.GlobalConst.ACT_BOSS_RUSH_DESC_10
    self.rankList = DataManager.ActPvpData:getRankList()
    uiMap["act_pvp_rank_ui.bg.title"]:setText(I18N:getGlobalText(text))
    if not self.topRankCells then
        self.topRankCells = {}
        for i = 1, 3 do
            self.topRankCells[i] = CellManager:addCellComp(uiMap["act_pvp_rank_ui.bg.rank_node.top_rank_cell_" .. i], TOP_RANK_CELL)
        end
    end
    for index, cell in ipairs(self.topRankCells) do
        cell:refresh(self.rankList[index])
    end
    local count = #self.rankList - 3
    if count < 0 then
        count = 0
    end
    if self.rankScrollRectComp then
        self.rankScrollRectComp:refillCells(count)
        return
    end

    self.rankScrollRectComp = uiMap["act_pvp_rank_ui.bg.rank_node.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.rankScrollRectComp:addInitCallback(function()
		return RANK_CELL
	end)
	self.rankScrollRectComp:addRefreshCallback(function(index, cell)
        local info = self.rankList[index + 3]
		cell:refresh(index + 3, info)
	end)
    self.rankScrollRectComp:clearCells()
    self.rankScrollRectComp:setTotalCount(0)
    self.rankScrollRectComp:refillCells(count)
end

function ActPvpRankUI:refreshRewardNode()
    local uiMap = self.root:genAllChildren()
    uiMap["act_pvp_rank_ui.bg.rank_node"]:setActive(false)
    uiMap["act_pvp_rank_ui.bg.reward_node"]:setActive(true)
    uiMap["act_pvp_rank_ui.bg.title"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_BOSS_RUSH_DESC_22))
    if self.rewardScrollRectComp then
        self.rewardScrollRectComp:updateAllCell()
    return
    end

    self.rewardScrollRectComp = uiMap["act_pvp_rank_ui.bg.reward_node.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.rewardScrollRectComp:addInitCallback(function()
		return RANK_REWARD_CELL
	end)
	self.rewardScrollRectComp:addRefreshCallback(function(index, cell)
        local info = self.rankRewardList[index]
		cell:refresh(info.ranking1, info.ranking2, info.rewards, self.rankRewardListCount)
	end)
    self.rewardScrollRectComp:clearCells()
    self.rewardScrollRectComp:setTotalCount(0)
    self.rewardScrollRectComp:refillCells(#self.rankRewardList)
end

function ActPvpRankUI:refreshPages()
    if not self.pageObjs then
        local uiMap = self.root:genAllChildren()
        self.pageObjs = {}
        for i = 1, 2 do
            self.pageObjs[i] = {
                page = uiMap["act_pvp_rank_ui.bg.page_" .. i],
                tx1 = uiMap["act_pvp_rank_ui.bg.page_" .. i .. ".tx"],
                tx2 = uiMap["act_pvp_rank_ui.bg.page_" .. i .. ".tx_hl"],
            }
            self.pageObjs[i].page:addClickListener(function()
                self:switchPage(i)
            end)
        end
    end
    for index, objs in ipairs(self.pageObjs) do
        if index == self.curPage then
            objs.page:setSprite(GConst.ATLAS_PATH.COMMON, PAGE_ICON[1])
            objs.page:setAnchoredPositionY(-451.5)
            objs.tx1:setText(GConst.EMPTY_STRING)
            objs.tx2:setText(I18N:getGlobalText(PAGE_TX[index]))
        else
            objs.page:setSprite(GConst.ATLAS_PATH.COMMON, PAGE_ICON[2])
            objs.page:setAnchoredPositionY(-442.5)
            objs.tx1:setText(I18N:getGlobalText(PAGE_TX[index]))
            objs.tx2:setText(GConst.EMPTY_STRING)
        end
    end

    if DataManager.ActPvpData:canGetRankReward() then
        self.pageObjs[2].page:addRedPoint(77, -6.5, 1)
    else
        self.pageObjs[2].page:removeRedPoint()
    end
end

function ActPvpRankUI:switchPage(page)
    if self.curPage == page then
        return
    end
    self.curPage = page

    if self.curPage ~= PAGE_TYPE.REWARD then
        self:refreshRankNode()
    else
        self:refreshRewardNode()
    end

    self:refreshPages()
    self:refreshMyRankInfo()
end

function ActPvpRankUI:refreshMyRankInfo()
    local myRank = DataManager.ActPvpData:getSelfRank()
    local totalWin = DataManager.ActPvpData:getTotalWinCount()
    local canGot = DataManager.ActPvpData:canGetRankReward()

    local uiMap = self.root:genAllChildren()
    if not self.playerHeadCell then
        self.playerHeadCell = CellManager:addCellComp(uiMap["act_pvp_rank_ui.bg.rank_bg.player_head_cell"], GConst.TYPEOF_LUA_CLASS.PLAYER_HEAD_CELL)
        self.selfRewardCells = {}
        for i = 1, 2 do
            self.selfRewardCells[i] = CellManager:addCellComp(uiMap["act_pvp_rank_ui.bg.rank_bg.reward_cell_" .. i], GConst.TYPEOF_LUA_CLASS.REWARD_CELL)
        end
    end

    self.playerHeadCell:refresh()
    uiMap["act_pvp_rank_ui.bg.rank_bg.name"]:setText(DataManager.PlayerData:getNickname())
    local rankObj = uiMap["act_pvp_rank_ui.bg.rank_bg.tx_rank"]
    if not myRank or myRank <= 0 then
        rankObj:setText("--")
    else
        rankObj:setText(myRank)
    end

    local winObj = uiMap["act_pvp_rank_ui.bg.rank_bg.tx_win"]
    winObj:setText(GConst.EMPTY_STRING)

    local winDesc = uiMap["act_pvp_rank_ui.bg.rank_bg.tx_win_desc"]
    winDesc:setText(GConst.EMPTY_STRING)

    if self.curPage ~= PAGE_TYPE.REWARD then
        for index, cell in ipairs(self.selfRewardCells) do
            cell:getBaseObject():setActive(false)
        end
        if totalWin and totalWin > 0 then
            winObj:setText(totalWin)
        else
            winObj:setText("--")
        end
        winDesc:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_17))
    else
        local got = DataManager.ActPvpData:getGotRankReward()
        local rewards = DataManager.ActPvpData:getRankRewards(myRank)

        for index, cell in ipairs(self.selfRewardCells) do
            if rewards and rewards[index] then
                cell:refreshByConfig(rewards[index], got, got)
                cell:getBaseObject():setActive(true)
                if canGot then
                    cell:showFrameAnimation()
                    cell:addClickListener(function()
                        ModuleManager.ActPvpManager:reqRankReward()
                    end)
                else
                    cell:hideFrameAnimation()
                    cell:addClickListener(nil)
                end
            else
                cell:getBaseObject():setActive(false)
            end
        end
    end
end

function ActPvpRankUI:refreshTime()
    local uiMap = self.root:genAllChildren()
    local remainTime = DataManager.ActPvpData:getRemainTime()
    local str
    if remainTime <= 0 then
        str = I18N:getGlobalText(I18N.GlobalConst.ACTIVITY_OVER_EDSC)
    else
        str = Time:formatNumTimeStr(remainTime)
    end
    local icon = uiMap["act_pvp_rank_ui.bg.time_node.icon"]
    local tx = uiMap["act_pvp_rank_ui.bg.time_node.tx_time"]
    tx:setText(str)
    GFunc.centerImgAndTx(icon, tx, 5)
end

return ActPvpRankUI