local BattleResultUI = class("BattleResultUI", BaseUI)

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

function BattleResultUI:getPrefabPath()
    return "assets/prefabs/ui/battle/battle_result_ui.prefab"
end

function BattleResultUI: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.mysteryBoxIdx = params.mysteryBoxIdx or 0
    -- 金币副本特有
    self.remainRound = params.remainRound
    -- 竞技场特有
    self.incrScore = params.incrScore
    self.arenaTotalCount = params.arenaTotalCount

    self.isTryShowGoldPig = false
    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 BattleResultUI:onClose()
    if self.sliderSequence then
        self.sliderSequence:Kill()
    end
    if self.animNode then
        self.animNode:Kill()
    end
    if self.animPig then
        self.animPig:Kill()
    end
    if self.animRewards then
        for idx, anim in pairs(self.animRewards) do
            if anim then
                anim:Kill()
            end
        end
    end
    if self.arenaSequence then
		self.arenaSequence:Kill()
		self.arenaSequence = nil
	end
    if self.arenaSpine then
        self.arenaSpine:destroy()
        self.arenaSpine = nil
    end
end

function BattleResultUI: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.unitImgBattleIcon = uiMap["battle_result_ui.unit_node.icon"]
    self.unitTxDesc1 = uiMap["battle_result_ui.unit_node.desc_1"]
    self.unitTxDesc2 = uiMap["battle_result_ui.unit_node.desc_2"]
    self.unitTxDesc3 = uiMap["battle_result_ui.unit_node.desc_3"]
    self.unitImgReportV = uiMap["battle_result_ui.unit_node.report_img_v"]
    self.unitImgReportD = uiMap["battle_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_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.goldPigNode = uiMap["battle_result_ui.gold_pig"]
    self.goldPigTxGem = uiMap["battle_result_ui.gold_pig.gem_bg.gem_tx"]
    self.goldPigSlider = uiMap["battle_result_ui.gold_pig.slider_bg.slider"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER)
    self.goldPigTxSlider = uiMap["battle_result_ui.gold_pig.slider_bg.text"]
    self.goldPigImgGem = uiMap["battle_result_ui.gold_pig.gem_bg.gem_img"]
    self.goldPigSpine = uiMap["battle_result_ui.gold_pig.spine_pig"]
    self.goldPigGem = uiMap["battle_result_ui.gold_pig.gem_bg"]
    self.canvasGroupPigGem = self.goldPigGem:getComponent(GConst.TYPEOF_UNITY_CLASS.CANVAS_GROUP)
    -- 竞技场
    self.arenaNode = uiMap["battle_result_ui.arena_node"]
    self.arenaSpineRoot = uiMap["battle_result_ui.arena_node.spine_root"]
    self.arenaTxGrading = uiMap["battle_result_ui.arena_node.tx_grading"]
    self.arenaTxScore = uiMap["battle_result_ui.arena_node.tx_score"]
    self.arenaImgProp = uiMap["battle_result_ui.arena_node.prog.img_prog"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER)
    self.arenaTxProg = uiMap["battle_result_ui.arena_node.prog.tx_prog"]
    -- 竞技场广告宝箱
    self.arenaBoxNode = uiMap["battle_result_ui.arena_box_node"]
    self.arenaBoxImgIcon = uiMap["battle_result_ui.arena_box_node.img_box"]
    self.arenaBoxTxTitle = uiMap["battle_result_ui.arena_box_node.tx_box"]
    self.arenaBoxBtnGet = uiMap["battle_result_ui.arena_box_node.btn_get"]
    self.arenaBoxTxGet = uiMap["battle_result_ui.arena_box_node.btn_get.tx_get"]

    self.victoryMask:addClickListener(function()
        self:onClickMask()
    end)
    self.defeatMask:addClickListener(function()
        self:onClickMask()
    end)
    self.arenaBoxBtnGet:addClickListener(function()
        ModuleManager.ShopManager:showArenaAdBoxUI(self.isWin)
    end)
    self:addEventListener(EventManager.CUSTOM_EVENT.ARENA_AD_BOX_SUCCESS, function()
        self.getedArenaAdBox = true
        self:refreshRewards()
        self:refreshArenaBoxNode()
    end)
end

function BattleResultUI:onClickMask()
    if self.isTryShowGoldPig then
        ModuleManager.BattleManager:endBattleAndExit()
    else
        if not self:tryShowGoldPig() then
            ModuleManager.BattleManager:endBattleAndExit()
        end
    end
end

function BattleResultUI: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()
    self:refreshArenaNode()
    self:refreshArenaBoxNode()
end

function BattleResultUI:refreshVictoryNode()
    self.victoryNode:setVisible(true)
    self.unitImgReportV:setVisible(true)
    self.defeatNode:setVisible(false)
    self.unitImgReportD: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)

    if self.battleType == GConst.BattleConst.BATTLE_TYPE.ARENA then
        self:showNodeAnim(self.victoryUnitNode, self.arenaNode)
    else
        self:showNodeAnim(self.victoryUnitNode, self.unitNode)
    end
end

function BattleResultUI: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)

    if self.battleType == GConst.BattleConst.BATTLE_TYPE.ARENA then
        self:showNodeAnim(self.defeatUnitNode, self.arenaNode)
    else
        self:showNodeAnim(self.defeatUnitNode, self.unitNode)
    end
end

-- 播放节点动画
function BattleResultUI: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 BattleResultUI:refreshArenaNode()
    if self.battleType ~= GConst.BattleConst.BATTLE_TYPE.ARENA then
        self.arenaNode:setVisible(false)
        return
    end

    self.arenaNode:setVisible(true)
    local totalScore = DataManager.ArenaData:getScore()
    local lastScore = totalScore - self.incrScore
    local curId = DataManager.ArenaData:getGradingId()
    local lastId = DataManager.ArenaData:getGradingIdFromScore(lastScore)

    if curId == nil or lastId == nil then
        return
    end

    self.arenaTxGrading:setText(DataManager.ArenaData:getGradingName(lastId))
    self:refreshArenaGradingSpine(lastId)

    if self.arenaSequence then
        self.arenaSequence:Kill()
    end
    self.arenaSequence = DOTweenManager:createSeqWithIntId()
    local tween = DOTweenManager:createDOTweenTo(
        function()
            return lastScore
        end,
        function(value)
            local maxScore = DataManager.ArenaData:getGradingScoreTotal(value)
            local curScore = DataManager.ArenaData:getGradingScore(value)
            if maxScore then
                self.arenaImgProp.value = curScore/maxScore
                self.arenaTxProg:setText(math.floor(curScore).."/"..maxScore)
            else
                self.arenaImgProp.value = 1
                self.arenaTxProg:setText(math.floor(curScore))
            end
        end,
        totalScore, 1.5)
    self.arenaSequence:Append(tween)
    self.arenaSequence:AppendCallback(function()
        self.arenaTxGrading:setText(DataManager.ArenaData:getGradingName(curId))
        if lastId ~= curId then
            self:refreshArenaGradingSpine(curId, curId > lastId)
        end
        self.arenaSequence = nil
    end)

    if self.incrScore > 0 then
        self.arenaTxScore:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_27, "+"..self.incrScore))
    elseif self.incrScore == 0 then
        self.arenaTxScore:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_27, "-"..self.incrScore))
    else
        self.arenaTxScore:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_27, self.incrScore))
    end
end

function BattleResultUI:hasArenaBoxNode()
    if self.battleType ~= GConst.BattleConst.BATTLE_TYPE.ARENA then
        return false
    end
    if not DataManager.ArenaData:hasAdBox(self.isWin, self.arenaTotalCount) then
        return false
    end
    if self.getedArenaAdBox then
        return false
    end

    return true
end

function BattleResultUI:refreshArenaBoxNode()
    self.arenaBoxNode:setVisible(false)
    if not self:hasArenaBoxNode() then
        return
    end
    self.arenaBoxNode:setVisible(true)
    self.arenaBoxBtnGet:setActive(not self.getedArenaAdBox)
    self.arenaBoxTxGet:setText(I18N:getGlobalText(I18N.GlobalConst.BTN_CLAIM))

    if self.isWin then
        -- 胜利宝箱
        self.arenaBoxNode:setSprite(GConst.ATLAS_PATH.ARENA, "arena_bg_6")
        self.arenaBoxImgIcon:setSprite(GConst.ATLAS_PATH.SHOP, "shop_chest_5")
        self.arenaBoxTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_33))
    else
        -- 鼓励宝箱
        self.arenaBoxNode:setSprite(GConst.ATLAS_PATH.ARENA, "arena_bg_5")
        self.arenaBoxImgIcon:setSprite(GConst.ATLAS_PATH.SHOP, "shop_chest_4")
        self.arenaBoxTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.ARENA_DESC_34))
    end
    ModuleManager.ArenaManager:markAdBox(self.isWin)
end

function BattleResultUI:refreshArenaGradingSpine(gradingId, isUp)
    if gradingId == nil then
        return
    end

    if self.arenaSpine then
        self.arenaSpine:playAnimComplete("vanish", false, false, function()
            if self.arenaSpine then
                self.arenaSpine:destroy()
                self.arenaSpine = nil
                self:refreshArenaGradingSpine(gradingId, isUp)
            end
        end)
    else
        SpineManager:loadUISpineWidgetAsync(DataManager.ArenaData:getGradingIconName(gradingId).."_spine", self.arenaSpineRoot, function(spineObject)
            self.arenaSpine = spineObject
            self.arenaSpine:setLocalScale(0.8, 0.8, 1)
            self.arenaSpine:setSkin(DataManager.ArenaData:getGradingNumName(gradingId))
            self.arenaSpine:playAnimComplete("born", false, false, function()
                if self.arenaSpine then
                    self.arenaSpine:playAnim("idle", true, false)
                end
            end)
        end)
        if isUp then
            EffectManager:loadUIEffectAsync("assets/prefabs/effects/ui/vfx_ui_".. DataManager.ArenaData:getGradingIconName(gradingId) ..".prefab", self, self.arenaSpineRoot, GConst.UI_EFFECT_ORDER.LEVEL5, function(obj)
                obj:play()
            end)
        end
	end
end

function BattleResultUI:refreshRewards()
    self.animRewards = {}
    self.rewardNode:setVisible(true)
    self.goldPigNode:setVisible(false)

    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:showRightUpIcon(index <= self.mysteryBoxIdx, GConst.ATLAS_PATH.COMMON, "common_chest_1")
        cell:showFirstPass(index <= self.firstPassIdx)
	end)
    if self:hasArenaBoxNode() then
        self.rewardScrollRect:setSizeDeltaY(SCROLL_LINE_HEIGHT)
        self.rewardScrollRect:setAnchoredPositionY(-255)
    else
        self.rewardScrollRect:setSizeDeltaY(SCROLL_LINE_HEIGHT * 2)
        self.rewardScrollRect:setAnchoredPositionY(-268)
    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 BattleResultUI: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_3"
    if self.battleType == GConst.BattleConst.BATTLE_TYPE.DUNGEON_GOLD then
        iconName = "common_dec_15"
        local round = self.remainRound or 0
        self.unitTxDesc2:setText(round)
        self.unitTxDesc1:setText(I18N:getGlobalText(I18N.GlobalConst.ROUND_LEFT))
    else
        self.unitTxDesc1:setText(GConst.EMPTY_STRING)
    end
    self.unitImgBattleIcon:setSprite(GConst.ATLAS_PATH.COMMON, iconName)

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

function BattleResultUI:tryShowGoldPig()
    self.isTryShowGoldPig = true
    if self.battleType ~= GConst.BattleConst.BATTLE_TYPE.STAGE then
        return false
    end
    if not DataManager.GoldPigData:getIsOpen() then
        return false
    end
    self.rewardNode:setVisible(false)
    self.goldPigNode:setVisible(true)
    local lastGemCount = DataManager.GoldPigData:getLastCount()
    local currGemCount = DataManager.GoldPigData:getCount()
    local maxGemCount = DataManager.GoldPigData:getMaxCount()
    if lastGemCount > currGemCount then
        lastGemCount = currGemCount
    end

    self.animPig = self.root:createBindTweenSequence()
    self.animPig:Insert(0, self.canvasGroupPigGem:DOFade(0, 0))
    self.animPig:Insert(1.5, self.canvasGroupPigGem:DOFade(1, 0.3))
    self.animPig:SetAutoKill(false)
    self.animPig:OnComplete(function()
        self.animPig = nil
    end)

    self.goldPigSpine:playAnimComplete("idle1", false, false, function()
        self.goldPigSpine:playAnim("idle2", true, false)
    end)

    self.goldPigTxGem:setText("+" .. currGemCount - lastGemCount)
    GFunc.centerImgAndTx(self.goldPigImgGem, self.goldPigTxGem, 0, -4)
    if currGemCount > lastGemCount then
        self.sliderSequence = DOTweenManager:createSeqWithIntId()
		local curProgress = 0
		local remain = currGemCount - lastGemCount
		local startPercent = lastGemCount / maxGemCount
		local remainPercent = currGemCount / maxGemCount - startPercent
		self.goldPigSlider.value = startPercent
		self.goldPigTxSlider:setText(lastGemCount .. "/" .. currGemCount)
        local tween = DOTweenManager:createDOTweenTo(
            function()
                return curProgress
            end,
            function(value)
                curProgress = value
				self.goldPigSlider.value = startPercent + remainPercent*curProgress
				self.goldPigTxSlider:setText(lastGemCount + math.floor(remain*curProgress) .. "/" .. maxGemCount)
            end,
        	1, 1)
		self.sliderSequence:Append(tween)
		self.sliderSequence:AppendCallback(function()
			self.sliderSequence = nil
		end)
    else -- 相等就不跑动画了
        self.goldPigSlider.value = currGemCount / maxGemCount
        self.goldPigTxSlider:setText(currGemCount .. "/" .. maxGemCount)
    end
    return true
end

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

    cell:setTouchEnable(false)
	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
        cell:setTouchEnable(true)
    end)
    return animRewardAppear
end

return BattleResultUI