local ActPvpSelectUI  = class("ActPvpSelectUI", BaseUI)

local INFO_BG = {
    [1] = "common_board_quality_2",
    [2] = "common_board_quality_2",
    [3] = "common_board_quality_3",
    [4] = "common_board_quality_4",
}

local BG_SPINE = {
    [GConst.BattleConst.ELEMENT_TYPE.RED] = "ui_hero_red",
    [GConst.BattleConst.ELEMENT_TYPE.YELLOW] = "ui_hero_yellow",
    [GConst.BattleConst.ELEMENT_TYPE.GREEN] = "ui_hero_green",
    [GConst.BattleConst.ELEMENT_TYPE.BLUE] = "ui_hero_blue",
    [GConst.BattleConst.ELEMENT_TYPE.PURPLE] = "ui_hero_purple",
}

local SIMPLE_HERO_CELL = "app/ui/activity/act_pvp/cell/simple_hero_cell"

function ActPvpSelectUI:getBGMId()
    return AudioManager.BGM_ID.ACT_PVP_CHOOSEBGM
end

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

function ActPvpSelectUI:onClose()
    if self.aniSeq then
        self.aniSeq:Kill()
        self.aniSeq = nil
    end
end

function ActPvpSelectUI:onLoadRootComplete()
    self:_display()
    self:_addListeners()
end

function ActPvpSelectUI:_display()
    local curPairIds = DataManager.ActPvpData:getCurSelectPairId()
    if not curPairIds or not curPairIds[1] then
        AudioManager:playEffect(AudioManager.EFFECT_ID.ACT_PVP_FINISH)
        self:closeUI()
        return
    end

    local uiMap = self.root:genAllChildren()
    local heroId = DataManager.ActPvpData:getSelectHeroId(curPairIds[1])
    local heroCfg = ConfigManager:getConfig("hero")[heroId]
    local matchType = heroCfg and heroCfg.position or GConst.BattleConst.ELEMENT_TYPE.RED
    local matchStr = ModuleManager.HeroManager:getMatchTypeName(matchType, true)
    local txTitle = uiMap["act_pvp_select_ui.bg.title_tx"]
    txTitle:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_8, matchStr))
    txTitle:setSizeDeltaX(txTitle:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT_MESH_PRO).preferredWidth)
    uiMap["act_pvp_select_ui.bg.desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_9))
    uiMap["act_pvp_select_ui.bg.hero_cell_1.select_btn.tx_desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_12))
    uiMap["act_pvp_select_ui.bg.hero_cell_2.select_btn.tx_desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_12))

    if not self.bigHeroInfos then
        self.bigHeroInfos = {}
        for i = 1, 2 do
            local unit = {}
            local prefix = "act_pvp_select_ui.bg.hero_cell_" .. i
            unit.node = uiMap[prefix]
            unit.spineBg = uiMap[prefix .. ".ui_spine_obj_bg"]
            unit.spineHero = uiMap[prefix .. ".ui_spine_obj_hero"]
            unit.simpleHeroCell = CellManager:addCellComp(uiMap[prefix .. ".simple_hero_cell"], SIMPLE_HERO_CELL)
            unit.info = uiMap[prefix .. ".info"]
            unit.matchIcon = uiMap[prefix .. ".info.icon"]
            unit.name = uiMap[prefix .. ".info.name"]
            unit.nextNode = uiMap[prefix .. ".next_node"]
            unit.nextDesc = uiMap[prefix .. ".next_node.desc"]
            unit.nextBg1 = uiMap[prefix .. ".next_node.bg_1"]
            unit.nextBg1Icon = uiMap[prefix .. ".next_node.bg_1.icon"]
            unit.nextBg1Dec = uiMap[prefix .. ".next_node.bg_1.dec"]
            unit.nextBg1Match = uiMap[prefix .. ".next_node.bg_1.match_img"]
            unit.nextBg2 = uiMap[prefix .. ".next_node.bg_2"]
            unit.nextBg2Icon = uiMap[prefix .. ".next_node.bg_2.icon"]
            unit.nextBg2Dec = uiMap[prefix .. ".next_node.bg_2.dec"]
            unit.nextBg2Match = uiMap[prefix .. ".next_node.bg_2.match_img"]
            unit.selectBtn = uiMap[prefix .. ".select_btn"]
            unit.selectDesc = uiMap[prefix .. ".select_btn.tx_desc"]
            unit.clickMask = uiMap[prefix .. ".info.click_mask"]
            self.bigHeroInfos[i] = unit
        end
    end

    self:rfreshRefreshBtns()
    self:refreshSelectInfo()
    self:refreshFormation()
end

function ActPvpSelectUI:_addListeners()
    local uiMap = self.root:genAllChildren()
    uiMap["act_pvp_select_ui.down.close_btn"]:addClickListener(function()
        local heroes = DataManager.ActPvpData:getHeros()
        if #heroes < GConst.BattleConst.ELEMENT_TYPE_COUNT then
            EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ACT_PVP_EVENT, {closeMainUI = true})
        end
        self:closeUI()
    end)

    uiMap["act_pvp_select_ui.bg.refresh_btn"]:addClickListener(function()
        if DataManager.ActPvpData:getCanAdFlush() then
            SDKManager:showFullScreenAds(BIReport.ADS_CLICK_TYPE.ACT_PVP_AD_REFRESH_HERO, function()
                ModuleManager.ActPvpManager:reqRefreshHero()
            end)
        else
            ModuleManager.ActPvpManager:reqRefreshHero()
        end
    end)

    uiMap["act_pvp_select_ui.bg.hero_cell_1.select_btn"]:addClickListener(function()
        ModuleManager.ActPvpManager:reqDecideHero(0)
    end)

    uiMap["act_pvp_select_ui.bg.hero_cell_2.select_btn"]:addClickListener(function()
        ModuleManager.ActPvpManager:reqDecideHero(1)
    end)

    self:addEventListener(EventManager.CUSTOM_EVENT.ACT_PVP_EVENT, function(params)
        if params and params.selectIndex then
            if not self.heroEntities or not self.bigHeroInfos or not self.simpleHeroCells then
                self:_display()
                return
            end
            local heroEntity
            local cell
            local node
            if params.selectIndex == 0 then -- 左边的
                heroEntity = self.heroEntities[1]
                cell = self.bigHeroInfos[1] and self.bigHeroInfos[1].simpleHeroCell
                node = self.bigHeroInfos[1] and self.bigHeroInfos[1].node
                if cell then
                    cell:getBaseObject():setAnchoredPosition(-170, 190)
                end
            else
                heroEntity = self.heroEntities[2]
                cell = self.bigHeroInfos[2] and self.bigHeroInfos[2].simpleHeroCell
                node = self.bigHeroInfos[2] and self.bigHeroInfos[2].node
                if cell then
                    cell:getBaseObject():setAnchoredPosition(170, 190)
                end
            end
            if not heroEntity or not cell then
                self:_display()
                return
            end

            local target = self.simpleHeroCells[heroEntity:getMatchType()]
            if not target then
                self:_display()
                return
            end
            self:disableUITouch()
            local targetPos = target:getBaseObject():getTransform().position
            local sPoint = UIManager:getUICameraComponent():WorldToScreenPoint(targetPos)
            targetPos = CS.BF.Utils.RectTransformScreenPointToLocalPointInRectangle(node:getTransform(), sPoint.x, sPoint.y, UIManager:getUICameraComponent())
            if self.aniSeq then
                self.aniSeq:Kill()
                self.aniSeq = nil
            end
            self.aniSeq = self.root:createBindTweenSequence()
            self.aniSeq:AppendCallback(function()
                cell:getBaseObject():setActive(true)
            end)
            self.aniSeq:Append(cell:getBaseObject():getTransform():DOAnchorPos(targetPos, 0.3))
            self.aniSeq:AppendCallback(function()
                self:_display()
                self:enableUITouch()
            end)
        elseif params and params.refreshHero then
            self:_display()
        end
    end)
end

function ActPvpSelectUI:refreshSelectInfo()
    if not self.bigHeroInfos then
        return
    end

    local curPairIds = DataManager.ActPvpData:getCurSelectPairId()
    local nextPairIds = DataManager.ActPvpData:getNextSelectFourId()
    local list = {}
    table.insert(list, {curPairIds[1], nextPairIds[1], nextPairIds[2]})
    table.insert(list, {curPairIds[2], nextPairIds[3], nextPairIds[4]})
    self.heroEntities = {}
    for inedx, ids in pairs(list) do
        local curId = ids[1]
        local nextId1 = ids[2]
        local nextId2 = ids[3]
        local unit = self.bigHeroInfos[inedx]
        if curId then
            local heroId = DataManager.ActPvpData:getSelectHeroId(curId)
            if heroId then
                local heroEntity = DataManager.HeroData:getEntity({id = heroId, level = DataManager.ActPvpData:getHeroLv()})
                self.heroEntities[inedx] = heroEntity
                unit.node:setVisible(true)
                unit.clickMask:addClickListener(function()
                    ModuleManager.HeroManager:showHeroDetailUI(nil, true, heroEntity)
                end)
                unit.simpleHeroCell:refresh(heroEntity)
                unit.simpleHeroCell:getBaseObject():setActive(false)
                unit.info:setSprite(GConst.ATLAS_PATH.COMMON, INFO_BG[heroEntity:getQlt()])
                local heroInfo = heroEntity:getConfig()
                unit.matchIcon:setSprite(GConst.ATLAS_PATH.ICON_HERO, GConst.HeroConst.MATCH_ICON_NAME[heroInfo.position])
                unit.name:setText(heroEntity:getName())
                unit.spineBg:setVisible(false)
                unit.spineBg:loadAssetAsync(BG_SPINE[heroEntity:getMatchType()], function()
                    unit.spineBg:setVisible(true, 1.8)
                    unit.spineBg:playAnim("idle", true, true, true)
                end)
                unit.spineHero:setVisible(false)
                unit.spineHero:loadAssetAsync(heroEntity:getModelId(), function()
                    unit.spineHero:setVisible(true)
                    unit.spineHero:playAnim("idle", true, true, true)
                end, true)
                if nextId1 and nextId2 then
                    unit.nextNode:setVisible(true)
                    unit.nextDesc:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_11))
                    local heroId = DataManager.ActPvpData:getSelectHeroId(nextId1)
                    local heroInfo = ConfigManager:getConfig("hero")[heroId]
                    if heroInfo then
                        unit.nextBg1:addClickListener(function()
                            ModuleManager.HeroManager:showHeroDetailUI(nil, true, heroEntity)
                        end)
                        local itemInfo = ConfigManager:getConfig("item")[heroInfo.item_id]
                        if itemInfo then
                            unit.nextBg1:setSprite(GConst.ATLAS_PATH.ICON_ITEM, GConst.FRAME_QLT[itemInfo.qlt])
                        end
                        unit.nextBg1Icon:setSprite(GConst.ATLAS_PATH.ICON_HERO, heroInfo.icon)
                        unit.nextBg1Dec:setSprite(GConst.ATLAS_PATH.ICON_HERO, GConst.HERO_DEC_QLT[heroInfo.qlt])
                        unit.nextBg1Match:setSprite(GConst.ATLAS_PATH.ICON_HERO, GConst.HeroConst.MATCH_ICON_NAME[heroInfo.position])
                    end

                    heroId = DataManager.ActPvpData:getSelectHeroId(nextId2)
                    heroInfo = ConfigManager:getConfig("hero")[heroId]
                    if heroInfo then
                        unit.nextBg2:addClickListener(function()
                            ModuleManager.HeroManager:showHeroDetailUI(nil, true, heroEntity)
                        end)
                        local itemInfo = ConfigManager:getConfig("item")[heroInfo.item_id]
                        if itemInfo then
                            unit.nextBg2:setSprite(GConst.ATLAS_PATH.ICON_ITEM, GConst.FRAME_QLT[itemInfo.qlt])
                        end
                        unit.nextBg2Icon:setSprite(GConst.ATLAS_PATH.ICON_HERO, heroInfo.icon)
                        unit.nextBg2Dec:setSprite(GConst.ATLAS_PATH.ICON_HERO, GConst.HERO_DEC_QLT[heroInfo.qlt])
                        unit.nextBg2Match:setSprite(GConst.ATLAS_PATH.ICON_HERO, GConst.HeroConst.MATCH_ICON_NAME[heroInfo.position])
                    end
                else
                    unit.nextNode:setVisible(false)
                end
            else
                unit.node:setVisible(false)
            end
        else
            unit.node:setVisible(false)
        end
    end
end

function ActPvpSelectUI:rfreshRefreshBtns()
    local uiMap = self.root:genAllChildren()
    local tx = uiMap["act_pvp_select_ui.bg.refresh_btn.tx_desc"]
    local txCost = uiMap["act_pvp_select_ui.bg.refresh_btn.tx_cost"]
    local imgCost = uiMap["act_pvp_select_ui.bg.refresh_btn.img_cost"]
    local ad = uiMap["act_pvp_select_ui.bg.refresh_btn.img_ad"]

    if DataManager.ActPvpData:getCanAdFlush() then
        tx:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_10))
        txCost:setVisible(false)
        imgCost:setVisible(false)
        ad:setVisible(true)
    else
        tx:setText(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_3))
        txCost:setVisible(true)
        imgCost:setVisible(true)
        txCost:setText(DataManager.ActPvpData:getFlushCost().num)
        GFunc.centerImgAndTx(imgCost, txCost, 0)
        ad:setVisible(false)
    end
end

function ActPvpSelectUI:refreshFormation()
    local uiMap = self.root:genAllChildren()
    if not self.simpleHeroCells then
        self.simpleHeroCells = {}
        for i = 1, 5 do
            self.simpleHeroCells[i] = CellManager:addCellComp(uiMap["act_pvp_select_ui.down.simple_hero_cell_" .. i], SIMPLE_HERO_CELL)
        end
    end

    local heroes = DataManager.ActPvpData:getHeros()
    for matchType, cell in ipairs(self.simpleHeroCells) do
        local entity = heroes[matchType]
        if entity then
            cell:getBaseObject():setVisible(true)
            cell:refresh(entity)
        else
            cell:getBaseObject():setVisible(false)
        end
    end
end

return ActPvpSelectUI