local BattleRuneResultUI = class("BattleRuneResultUI", BaseUI)

local RUNE_TASK_CELL = "app/ui/dungeon_rune/cell/rune_task_cell"
local UNIT_RESULT_RERPORT_CELL = "app/ui/battle/cell/unit_result_report_cell"
local MAX_SCROLL_SHOW_COUNT = 10

function BattleRuneResultUI:getPrefabPath()
    return "assets/prefabs/ui/battle/battle_rune_result_ui.prefab"
end

function BattleRuneResultUI:ctor(params)
    if EDITOR_MODE then
        Logger.printTable(params)
    end
    -- 通用
    self.battleType = params.battleType
    self.isWin = params.combatReport.victory
    self.rewards = params.rewards
    self.remainRound = params.remainRound

    -- pve特有
    self.atkReport = params.combatReport.atkReport
    self.wave = params.wave

    self.totalDmg = 0
    if self.atkReport then
        for _, info in ipairs(self.atkReport) do
            self.totalDmg = self.totalDmg + info.dmg
        end
    end

    self.runeData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.RUNES_OPEN)
    self.chapterId = ModuleManager.BattleManager.battleController.chapterId
end

function BattleRuneResultUI:onClose()
    if self.animNode then
        self.animNode:Kill()
        self.animNode = nil
    end
    if self.animRewards then
        for idx, anim in pairs(self.animRewards) do
            if anim then
                anim:Kill()
            end
        end
    end
end

function BattleRuneResultUI:onLoadRootComplete()
    local uiMap = self.root:genAllChildren()

    self.continue = uiMap["battle_rune_result_ui.continue"]
    -- 胜利节点
    self.victoryNode = uiMap["battle_rune_result_ui.victory_node"]
    self.victoryMask = uiMap["battle_rune_result_ui.victory_node.mask_v"]
    self.victoryTxTitle = uiMap["battle_rune_result_ui.victory_node.title_bg.desc"]
    self.victorySpine = uiMap["battle_rune_result_ui.victory_node.ui_spine_obj"]
    self.victoryUnitNode = uiMap["battle_rune_result_ui.victory_node.unit_node"]
    -- 失败节点
    self.defeatNode = uiMap["battle_rune_result_ui.defeat_node"]
    self.defeatMask = uiMap["battle_rune_result_ui.defeat_node.mask_d"]
    self.defeatTxTitle = uiMap["battle_rune_result_ui.defeat_node.title_bg.desc"]
    self.defeatSpine = uiMap["battle_rune_result_ui.defeat_node.ui_spine_obj"]
    self.defeatUnitNode = uiMap["battle_rune_result_ui.defeat_node.unit_node"]
    -- 战斗信息
    self.unitNode = uiMap["battle_rune_result_ui.unit_node"]
    self.unitImgBattleIcon = uiMap["battle_rune_result_ui.unit_node.icon"]
    self.unitTxDesc1 = uiMap["battle_rune_result_ui.unit_node.desc_1"]
    self.unitTxDesc2 = uiMap["battle_rune_result_ui.unit_node.desc_2"]
    self.unitTxDesc3 = uiMap["battle_rune_result_ui.unit_node.desc_3"]
    self.unitTxDesc3 = uiMap["battle_rune_result_ui.unit_node.desc_3"]
    self.unitImgReportV = uiMap["battle_rune_result_ui.unit_node.report_img_v"]
    self.unitImgReportD = uiMap["battle_rune_result_ui.unit_node.report_img_d"]
    if not self.unitResultReportCells then
        self.unitResultReportCells = {}
        for index = 1, 5 do
            self.unitResultReportCells[index] = CellManager:addCellComp(uiMap["battle_rune_result_ui.unit_node.unit_result_report_cell_" .. index], UNIT_RESULT_RERPORT_CELL)
        end
    end
    -- 奖励节点
    self.rewardNode = uiMap["battle_rune_result_ui.reward_node"]
    self.rewardTxTitle = uiMap["battle_rune_result_ui.reward_title"]
    self.rewardScrollRect = uiMap["battle_rune_result_ui.reward_node.scroll_rect"]
    self.rewardScrollRectComp = self.rewardScrollRect:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.descRoundMin = uiMap["battle_rune_result_ui.reward_node.desc"]
    self.imgRoundmIn = uiMap["battle_rune_result_ui.reward_node.icon"]
    self.imgRoundNew = uiMap["battle_rune_result_ui.reward_node.icon_new"]
    self.descRoundMin:setVisible(false)
    self.imgRoundmIn:setVisible(false)

    -- 任务节点
    self.taskNode = uiMap["battle_rune_result_ui.task_node"]
    self.runeTaskCells = {}
    for index = 1, 3 do
        self.runeTaskCells[index] = {}
        self.runeTaskCells[index].cell = CellManager:addCellComp(uiMap["battle_rune_result_ui.task_node.rune_task_cell_" .. index], RUNE_TASK_CELL)
        self.runeTaskCells[index].desc = uiMap["battle_rune_result_ui.task_node.desc_" .. index]
        self.runeTaskCells[index].descUnDone = uiMap["battle_rune_result_ui.task_node.desc_undone_" .. index]
        self.runeTaskCells[index].check = uiMap["battle_rune_result_ui.task_node.check_" .. index]
    end

    self.victoryMask:addClickListener(function()
        self:onClickMask()
    end)
    self.defeatMask:addClickListener(function()
        self:onClickMask()
    end)
end

function BattleRuneResultUI:onClickMask()
    if not self.isWin then
        ModuleManager.BattleManager:endBattleAndExit()
    else
        if not self.showRewardInfo then
            self.showRewardInfo = true
            self:refreshRewards()
        else
            ModuleManager.BattleManager:endBattleAndExit()
        end
    end
end

function BattleRuneResultUI:onRefresh()
    if self.isWin then
        self:refreshVictoryNode()
        AudioManager:playEffect(AudioManager.EFFECT_ID.BATTLE_VICTORY)
    else
        self:refreshDefeatNode()
        AudioManager:playEffect(AudioManager.EFFECT_ID.BATTLE_DEFEAT)
    end
    self:refreshUnitInfo()

    if self.runeData:isBossChapter(self.chapterId) then
        self.showRewardInfo = true
        self:refreshRewards()
    else
        self:refreshTaskNode()
    end
end

function BattleRuneResultUI:refreshVictoryNode()
    self.victoryNode:setVisible(true)
    self.unitImgReportV:setVisible(true)
    self.defeatNode:setVisible(false)
    self.unitImgReportD:setVisible(false)

    self.victorySpine:playAnimComplete("born", false, true, function()
        self.victorySpine:playAnim("idle", true, true)
    end)

    self:showNodeAnim(self.victoryUnitNode, self.unitNode)
end

function BattleRuneResultUI:refreshDefeatNode()
    self.victoryNode:setVisible(false)
    self.unitImgReportV:setVisible(false)
    self.defeatNode:setVisible(true)
    self.unitImgReportD:setVisible(true)

    self.defeatTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_6))
    self.defeatSpine:playAnimComplete("born", false, true, function()
        self.defeatSpine:playAnim("idle", true, true)
    end)

    self:showNodeAnim(self.defeatUnitNode, self.unitNode)
end

-- 播放节点动画
function BattleRuneResultUI:showNodeAnim(parent, node)
    if not parent then
        node:setVisible(false)
        return
    else
        node:setVisible(true)
    end
    node:setParent(parent, false)
    node:setAnchoredPosition(0, 0)
    local canvasNode = parent:getComponent(GConst.TYPEOF_UNITY_CLASS.CANVAS_GROUP)

    self.animNode = self.root:createBindTweenSequence()
    self.animNode:Insert(0, canvasNode:DOFade(0, 0))
    self.animNode:Insert(0.1, canvasNode:DOFade(1, 0))
    self.animNode:Insert(0, parent:getTransform():DOScale(0, 0))
    self.animNode:Insert(0.1, parent:getTransform():DOScale(0.35, 0))
    self.animNode:Insert(0.13, parent:getTransform():DOScale(1.1, 0.16))
    self.animNode:Insert(0.26, parent:getTransform():DOScale(1, 0.14))
    self.animNode:OnComplete(function()
        self.animNode = nil
    end)
end

function BattleRuneResultUI:refreshTaskNode()
    self.taskNode:setVisible(true)
    self.rewardNode:setVisible(false)
    self.rewardTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_RUNE_DESC_1))
    local id = self.chapterId
    if not id then
        return
    end

    local chapterCondition = self.runeData:getChapterCondition(id)
    if not chapterCondition then
        return
    end

    local taskProgress = ModuleManager.DungeonRuneManager:getTaskStatus(ModuleManager.BattleManager.battleController, chapterCondition)

    for index, objs in ipairs(self.runeTaskCells) do
        local newIndex = index + 1
        local condition = chapterCondition[newIndex]
        if condition then
            objs.cell:getBaseObject():setActive(true)
            local taskNum = taskProgress[newIndex] and taskProgress[newIndex].progress
            local desc = self.runeData:getConditionDesc(condition)
            local over = false
            if taskProgress[newIndex] then
                local info = taskProgress[newIndex]
                over = info.over
                local color = "#FF4949"
                if over then
                    color = "#49FF49"
                end
                desc = desc .. string.format("<color=%s>(%s/%s)</color>", color, info.progress, info.totalProgress)
            end
            objs.cell:refresh(condition)
            objs.desc:setText(self.runeData:getConditionDesc(condition))
            if over then
                objs.descUnDone:setText(GConst.EMPTY_STRING)
                objs.check:setVisible(true)
            else
                objs.descUnDone:setText(I18N:getGlobalText(I18N.GlobalConst.UNFINISHED))
                objs.check:setVisible(false)
            end
        else
            objs.cell:getBaseObject():setActive(false)
            objs.desc:setText(GConst.EMPTY_STRING)
            objs.descUnDone:setText(GConst.EMPTY_STRING)
            objs.check:setVisible(false)
        end
    end
end

function BattleRuneResultUI:refreshRewards()
    self.animRewards = {}
    self.taskNode:setVisible(false)
    self.rewardNode:setVisible(true)

    self.rewardTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.REWARD_DESC))
    self.continue:setText(I18N:getGlobalText(I18N.GlobalConst.CONTINUE_DESC))
    self.rewardScrollRectComp:addInitCallback(function()
		return GConst.TYPEOF_LUA_CLASS.REWARD_CELL
	end)
	self.rewardScrollRectComp:addRefreshCallback(function(index, cell)
		cell:refresh(self.rewards[index])
        if index <= MAX_SCROLL_SHOW_COUNT and self.animRewards[index] == nil then
            self.animRewards[index] = self:showRewardAppearAnim(index, cell)
        end
	end)

    self.rewardScrollRectComp:setFadeArgs(0.05, 0.3)
    self.rewardScrollRectComp:clearCells()
    local rewardCount = #self.rewards
    if rewardCount > MAX_SCROLL_SHOW_COUNT then
        local comp = self.rewardScrollRect:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_SCROLL_RECT)
		comp.movementType = CS.UnityEngine.UI.ScrollRect.MovementType.Elastic
        self.rewardScrollRectComp:setPerLineNum(5)
        self.rewardScrollRect:setSizeDeltaX(560)
	else
        local comp = self.rewardScrollRect:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_SCROLL_RECT)
        comp.movementType = CS.UnityEngine.UI.ScrollRect.MovementType.Clamped
        if rewardCount >= 5 then
            self.rewardScrollRectComp:setPerLineNum(5)
            self.rewardScrollRect:setSizeDeltaX(560)
        elseif rewardCount <= 0 then
            self.rewardScrollRectComp:setPerLineNum(1)
            self.rewardScrollRect:setSizeDeltaX(560)
        else
            self.rewardScrollRectComp:setPerLineNum(rewardCount)
            self.rewardScrollRect:setSizeDeltaX(112*rewardCount)
        end
	end
    self.rewardScrollRectComp:refillCells(rewardCount)

    -- local id = self.chapterId
    -- self.descRoundMin:setText(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_RUNE_MIN, self.runeData:getChapterPassRound(id)))
    -- GFunc.centerImgAndTx(self.imgRoundmIn, self.descRoundMin, 10)
    -- self.imgRoundNew:setVisible(self.runeData:getTagRoundNew() == true)
end

function BattleRuneResultUI:refreshUnitInfo()
    if not self.atkReport then
        self.unitNode:setVisible(false)
        return
    end

    self.unitNode:setVisible(true)
    for index, cell in ipairs(self.unitResultReportCells) do
        local info = self.atkReport[index]
        cell:getBaseObject():setVisible(info ~= nil)
        if info then
            cell:refresh(info, self.totalDmg)
        end
    end

    self.unitTxDesc2:setText(self.wave)
    self.unitTxDesc3:setText(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_7, GFunc.num2Str(self.totalDmg)))

    local iconName = "common_dec_15"
    local round = self.remainRound or 0
    self.unitTxDesc2:setText(round)
    self.unitTxDesc1:setText(I18N:getGlobalText(I18N.GlobalConst.ROUND_LEFT))
    self.unitImgBattleIcon:setSprite(GConst.ATLAS_PATH.COMMON, iconName)

    GFunc.centerImgAndTx(self.unitImgBattleIcon, self.unitTxDesc2, 7)
end

-- 展示结算奖励的出现动画
function BattleRuneResultUI:showRewardAppearAnim(idx, cell)
    local canvasGroup = cell.baseObject:getComponent(GConst.TYPEOF_UNITY_CLASS.CANVAS_GROUP)
	local selfObj = cell.baseObject
	local delay = (idx - 1) * 0.05
	local scaleX = selfObj:fastGetLocalScale()

	local animRewardAppear = selfObj:createBindTweenSequence()
    animRewardAppear:Insert(0, canvasGroup:DOFade(0, 0))
    animRewardAppear:Insert(0, selfObj:getTransform():DOScale(scaleX * 0.6, 0))
    animRewardAppear:Insert(0.3 + delay, selfObj:getTransform():DOScale(scaleX * 1.1, 0.1))
    animRewardAppear:Insert(0.3 + delay, canvasGroup:DOFade(1, 0.1))
    animRewardAppear:Insert(0.4 + delay, selfObj:getTransform():DOScale(scaleX * 1, 0.13))
    animRewardAppear:OnComplete(function()
        animRewardAppear = nil
    end)
    return animRewardAppear
end

return BattleRuneResultUI