local DungeonArmorMainUI = class("DungeonArmorMainUI", BaseUI)

local CHAPTER_LAYER_CELL = "app/ui/dungeon_armor/cell/chapter_cell"
local GIFT_CELL = "app/ui/main_city/cell/side_bar_armor_gift_cell"

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

function DungeonArmorMainUI:getPrefabPath()
    return "assets/prefabs/ui/dungeon_armor/dungeon_armor_main_ui.prefab"
end

function DungeonArmorMainUI:ctor()
    self.armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
    self.chapterList = {}
    self.targetId = self.armorData:getPassedMaxId()
    self.unlockId = nil
    for id, info in pairs(ConfigManager:getConfig("chapter_dungeon_armor")) do
        table.insert(self.chapterList, id)
        if not self.targetId then
            self.targetId = id
        end

        if id == self.armorData:getPassedMaxId() + 1 and self.armorData:canFightChapter(id) then -- 最大可挑战章节
            self.targetId = id
        end

        if (id - 1) > 0 and not self.armorData:getStagePassEnough(id - 1) then -- 显示两个未解锁的
            self.unlockId = id - 1
            break
        end
    end

    self.targetId = math.max(1, self.targetId - 1)
end

function DungeonArmorMainUI:onLoadRootComplete()
    self:_display()
    self:_addListeners()
    self:_bind()
    DataManager.ShopData:checkPopGift(PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT)

    self:refreshTime()
	self:scheduleGlobal(function()
        self:refreshTime()
	end, 1)
end

function DungeonArmorMainUI:_display()
    local uiMap = self.root:genAllChildren()
    uiMap["dungeon_armor_main_ui.banner.btn_formation.tx_ok"]:setText(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_WEAPON_DESC_4))
    self.bg1 = uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.bg_1"]
    self.bg2 = uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.bg_2"]
    self.bgNames = table.clearOrCreate(self.bgNames)
    self.bg1:setAnchoredPositionY(-1)
    self.bg2:setAnchoredPositionY(-1)
    self.btnFund = uiMap["dungeon_armor_main_ui.btn_fund"]
    self.txFund = uiMap["dungeon_armor_main_ui.btn_fund.tx_fund"]
    self.btnFund:setActive(not GFunc.isShenhe())

    self:refreshFund()
    self:initRightBtns()
    self:refreshScrollrect()
    self:refreshFormation()
    self:refreshStarNode()
end

function DungeonArmorMainUI:_addListeners()
    local uiMap = self.root:genAllChildren()
    uiMap["dungeon_armor_main_ui.banner.btn_back"]:addClickListener(function()
        self:closeUI()
    end)

    uiMap["dungeon_armor_main_ui.banner.btn_formation"]:addClickListener(function()
        ModuleManager.CommonManager:showFormationUI(GConst.BattleConst.FORMATION_TYPE.DUNGEON_ARMOR)
    end)

    uiMap["dungeon_armor_main_ui.banner.star_node"]:addClickListener(function()
        ModuleManager.DungeonArmorManager:showStarRewardUI()
    end)
    self.btnFund:addClickListener(function()
        UIManager:showUI("app/ui/dungeon_armor/armor_fund_ui")
    end)


    self:addEventListener(EventManager.CUSTOM_EVENT.GO_SHOP, function()
        self:closeUI()
    end)

    self:addEventListener(EventManager.CUSTOM_EVENT.DUNGEON_ARMOR_TO_TARGET_ID, function(params)
        if not params or not params.id then
            return
        end
        self.bgNames = table.clearOrCreate(self.bgNames)
        self.bg1:setAnchoredPositionY(-1)
        self.bg2:setAnchoredPositionY(-1)
        self.targetId = params.id
        self:refreshScrollrect()

        if self.armorData:canFarmChapter(self.targetId) then -- 可扫荡
            ModuleManager.DungeonArmorManager:showFarmUI(self.targetId)
        elseif self.armorData:canFightChapter(self.targetId) then -- 可挑战
            ModuleManager.DungeonArmorManager:showFightUI(self.targetId)
        else -- 不可挑战
            GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.PASS_REQUIRE))
        end
    end)
end

function DungeonArmorMainUI:_bind()
    self:bind(self.armorData, "isDirty", function()
        self:refreshFund()
        self:refreshFormation()
        self:refreshStarNode()
        self:refreshAllCells()
    end)

    self:bind(DataManager.FormationData, "dirty", function()
        self:refreshFormation()
    end)

    self:bind(DataManager.HeroData, "isDirty", function()
        self:refreshFormation()
    end)
end

function DungeonArmorMainUI:refreshScrollrect()
    if not self.scrollRect then
        local uiMap = self.root:genAllChildren()
        self.scrollRect = uiMap["dungeon_armor_main_ui.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
        self.scrollRect:addInitCallback(function()
            return CHAPTER_LAYER_CELL
        end)
        self.scrollRect:addRefreshCallback(function(index, cell)
            cell:refresh(self.chapterList[index])
            self:refreshBG(self.chapterList[index], index)
        end)
    end
    self.scrollRect:refillCells(#self.chapterList, nil, self.targetId)
    self:refreshCloud(self.unlockId)
end

function DungeonArmorMainUI:refreshAllCells()
    if not self.scrollRect then
        return
    end

    self.scrollRect:refreshAll()
end

function DungeonArmorMainUI:refreshFormation()
    if not self.formationComp then
        local uiMap = self.root:genAllChildren()
        self.formationComp = uiMap["dungeon_armor_main_ui.hero_formation_comp"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.HERO_FORMATION_COMP)
    end
    self.formationComp:refreshByFormation(DataManager.FormationData:getDungeonArmorFormation())
end

function DungeonArmorMainUI:refreshStarNode()
    local uiMap = self.root:genAllChildren()
    local starNode = uiMap["dungeon_armor_main_ui.banner.star_node"]
    local pSlider = uiMap["dungeon_armor_main_ui.banner.star_node.p_slider"]
    local pTx = uiMap["dungeon_armor_main_ui.banner.star_node.p_tx"]

    local id, progress, totalProgress = self.armorData:getMinStarTarget()
    if progress <= 0 then
        progress = 0
    end

    if totalProgress <= 0 then
        totalProgress = 1
    end

    pTx:setText(progress .. "/" .. totalProgress)
    pSlider:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER).value = progress / totalProgress

    if self.armorData:canClaimStarReward() then
        starNode:addRedPoint(110, 40, 0.8)
    else
        starNode:removeRedPoint()
    end
end

function DungeonArmorMainUI:refreshBG(chapterId, index)
    if not self.bg1 then
        return
    end
    local config = self.armorData:getConfig(chapterId)
    local bgName = config.chapter_bg
    if not self.bgNames then
        self.bgNames = {}
    end

    for _, name in pairs(self.bgNames) do
        if name == bgName then -- 已存在
            return
        end
    end

    local isUp = true
    local zheng = index // 6
    local yu = index % 6
    if yu == 0 then -- 每一张的最后一个
        isUp = false
    end

    local obj
    local y1 = self.bg1:fastGetAnchoredPositionY()
    local y2 = self.bg2:fastGetAnchoredPositionY()
    if y1 == -1 then
        obj = self.bg1
    elseif y2 == -1 then
        obj = self.bg2
    end
    if not obj then
        if isUp then
            if y1 == y2 then
                obj = self.bg1
            elseif y1 < y2 then
                obj = self.bg1
            else
                obj = self.bg2
            end
        else
            if y1 == y2 then
                obj = self.bg2
            elseif y1 < y2 then
                obj = self.bg2
            else
                obj = self.bg1
            end
        end
    end

    if self.bgNames[obj] ~= bgName then
        obj:setTexture("assets/arts/textures/background/dungeon_armor/" .. bgName .. ".png")
        self.bgNames[obj] = bgName
        if isUp then
            obj:setAnchoredPositionY(1200 * zheng)
        else
            obj:setAnchoredPositionY(1200 * (zheng - 1))
        end
    end
end

function DungeonArmorMainUI:refreshCloud(id)
    local uiMap = self.root:genAllChildren()
    local cloud = uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.cloud"]
    if not id then
        cloud:setVisible(false)
        return
    end
    cloud:setVisible(true)
    local unlock, p, needP = self.armorData:getStagePassEnough(id)
    if unlock then
        cloud:setVisible(false)
    else
        cloud:setVisible(true)
        uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.cloud.mask"]:addClickListener(function()
            GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_10, needP))
        end)
        p = p or 0
        needP = needP or 1
        uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.cloud.lock_info.p_slider"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER).value = p / needP
        uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.cloud.lock_info.desc_1"]:setText(I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_10, needP))
        uiMap["dungeon_armor_main_ui.scrollrect.viewport.content.cloud.lock_info.desc_2"]:setText(p .. "/" .. needP)

        -- 位置
        local zheng = id // 6
        cloud:setAnchoredPositionY(1200 * zheng)
    end
end

function DungeonArmorMainUI:refreshFund()
    self.txFund:setText(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_ARMOR_DESC_12))

    if DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR):isHasFundRedDot() then
        self.btnFund:addRedPoint(30, 40, 0.6)
    else
        self.btnFund:removeRedPoint()
    end
end

function DungeonArmorMainUI:refreshTime()
    self:refreshRightBtns()
end

function DungeonArmorMainUI:initRightBtns()
    if self.rightBtnCells then
        return
    end
    local uiMap = self.root:genAllChildren()
    self.rightNode = uiMap["dungeon_armor_main_ui.right_node"]
    self.rightArrow = uiMap["dungeon_armor_main_ui.right_node.arrow_node"]
    self.rightBtnCells = {}
    self.rightBtnCells.giftCell = CellManager:addCellComp(uiMap["dungeon_armor_main_ui.right_node.side_bar.side_bar_cell"], GIFT_CELL)

    self.rightArrow:setVisible(false)

    self:refreshRightBtns()
end

function DungeonArmorMainUI:refreshRightBtns()
    local y = 0
    if self.rightBtnCells.giftCell:checkIsOpen() then
        y = y - 60
        self.rightBtnCells.giftCell:setActive(true)
        self.rightBtnCells.giftCell:setVisible(true)
        self.rightBtnCells.giftCell:getBaseObject():setAnchoredPositionY(y)
        self.rightBtnCells.giftCell:refresh()
    else
        self.rightBtnCells.giftCell:setVisible(false)
    end

    -- 暂不处理箭头的问题
    self.rightNode:setVisible(y < 0)
end

return DungeonArmorMainUI