local BattleArmorResultUI = class("BattleArmorResultUI", BaseUI)

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

function BattleArmorResultUI:getPrefabPath()
    return "assets/prefabs/ui/battle/battle_armor_result_ui.prefab"
end

function BattleArmorResultUI:ctor(params)
    if EDITOR_MODE then
        Logger.printTable(params)
    end
    -- 通用
    self.battleType = params.battleType
    self.isWin = params.isWin
    self.rewards = params.rewards
    self.firstPassIdx = params.firstPassIdx or 0
    self.noMergeReward = params.noMergeReward

    -- pve特有
    self.atkReport = params.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

    if not self.noMergeReward then
        local newRewards = {}
        GFunc.mergeRewards2(self.rewards, newRewards)
        self.rewards = newRewards
    end
end

function BattleArmorResultUI: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 BattleArmorResultUI:onLoadRootComplete()
    local uiMap = self.root:genAllChildren()

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

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

function BattleArmorResultUI:onClickMask()
    ModuleManager.BattleManager:endBattleAndExit()
end

function BattleArmorResultUI: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()
    self:refreshRewards()
end

function BattleArmorResultUI:refreshVictoryNode()
    self.victoryNode:setVisible(true)
    self.defeatNode:setVisible(false)

    -- self.victoryTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_5))
    self.victorySpine:playAnimComplete("born", false, true, function()
        self.victorySpine:playAnim("idle", true, true)
    end)

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

function BattleArmorResultUI:refreshDefeatNode()
    self.victoryNode:setVisible(false)
    self.defeatNode: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 BattleArmorResultUI: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 BattleArmorResultUI:refreshRewards()
    self.animRewards = {}
    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
        cell:showFirstPass(index <= self.firstPassIdx)
	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)
end

function BattleArmorResultUI: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.unitTxDesc3:setText(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_7, GFunc.num2Str(self.totalDmg)))

    local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
    local battleController = ModuleManager.BattleManager.battleController
    if not battleController then
        return
    end
    local chapterId = battleController.chapterId
    local taskProgrees = armorData:formatTaskByController(battleController, chapterId)

    local uiMap = self.root:genAllChildren()
    local y = 431
    for index = 1, 3 do
        local star = uiMap["battle_armor_result_ui.unit_node.star_" .. index]
        local starDesc = uiMap["battle_armor_result_ui.unit_node.star_desc_" .. index]
        local desc, over = armorData:getTaskDescByIndex(chapterId, index, nil, taskProgrees)
        starDesc:setText(desc)
        if over then
            star:setSprite(GConst.ATLAS_PATH.BATTLE, "battle_star_1")
        else
            star:setSprite(GConst.ATLAS_PATH.BATTLE, "battle_star_2")
        end

        local h = starDesc:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT_MESH_PRO).preferredHeight
        starDesc:setAnchoredPositionY(y)
        star:setAnchoredPositionY(y + 5)
        y = y - h - 19
    end

    local starNum = armorData:getStarNum(chapterId)
    local starSpine = uiMap["battle_armor_result_ui.unit_node.ui_spine_obj"]

    if starNum > 0 then
        local openAni = "open" .. starNum
        local idleAni = "idle" .. starNum
        starSpine:playAnimComplete(openAni, false, true, function()
            starSpine:playAnim(idleAni, true, true)
        end)
    else
        -- 处理
    end
end

-- 展示结算奖励的出现动画
function BattleArmorResultUI: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 BattleArmorResultUI