local ProgressBar = require "app/tools/progress_bar"
local BattleActPvpResultUI = class("BattleActPvpResultUI", BaseUI)

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

function BattleActPvpResultUI:getPrefabPath()
    return "assets/prefabs/ui/battle/battle_actpvp_result_ui.prefab"
end

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

    -- 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
end

function BattleActPvpResultUI: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 BattleActPvpResultUI: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.unitTxDesc1 = uiMap["battle_rune_result_ui.unit_node.desc_1"]
    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"]
    self.txFightWin = uiMap["battle_actpvp_result_ui.unit_node.tx_fight"]
    self.txFightLose = uiMap["battle_actpvp_result_ui.unit_node.tx_fight_lose"]
    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.rewardTxTitle:setText(I18N:getGlobalText(I18N.GlobalConst.REWARD_DESC))
    self.continue:setText(I18N:getGlobalText(I18N.GlobalConst.CONTINUE_DESC))

    -- 战令节点

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

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

function BattleActPvpResultUI: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:refreshBountyNode()
end

function BattleActPvpResultUI: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 BattleActPvpResultUI: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 BattleActPvpResultUI: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 BattleActPvpResultUI:refreshBountyNode()
    local uiMap = self.root:genAllChildren()
    local txLv = uiMap["battle_actpvp_result_ui.reward_node.point_bg.desc_lv"]
    uiMap["battle_actpvp_result_ui.reward_node.point_bg.desc_lv_desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_DESC_12))
    local txSlider = uiMap["battle_actpvp_result_ui.reward_node.point_bg.desc_slider"]
    local slider = uiMap["battle_actpvp_result_ui.reward_node.point_bg.slider_bg.slider"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER)

    local addExp = 0
    local lastLevel, lastExp = DataManager.ActPvpData:getLastBountyLevel()
    local curLevel = DataManager.ActPvpData:getBountyLevel()
    local exp = DataManager.ActPvpData:getBountyExp()
    if not lastLevel then
        lastLevel = curLevel
    end
    if not lastExp then
        lastExp = exp
    end

    if lastLevel ~= curLevel then
        local calExp = lastExp
        for i = lastLevel, curLevel - 1 do
            local need = DataManager.ActPvpData:getBountyLevelExp(i)
            if need > 0 then
                addExp = addExp + need - calExp
                calExp = 0
            end
        end
        addExp = addExp + exp
    else
        addExp = exp - lastExp
    end

    local lastNeedExp = DataManager.ActPvpData:getBountyLevelExp(lastLevel)
    local oldSliderValue = 0
    if lastNeedExp <= 0 then
        local need = DataManager.ActPvpData:getBountyLevelExp(lastLevel - 1)
        if need <= 0 then
            need = 1
        end
        oldSliderValue = lastExp / need
    else
        oldSliderValue = lastExp / lastNeedExp
    end

    local needExp = DataManager.ActPvpData:getBountyLevelExp(curLevel)
    local newSliderValue = 0
    if needExp <= 0 then
        local need = DataManager.ActPvpData:getBountyLevelExp(curLevel - 1)
        if need <= 0 then
            need = 1
        end
        newSliderValue = needExp / need
    else
        newSliderValue = exp / needExp
    end

    local params = {}
	params.ui = self
	params.oldLv = lastLevel
	params.newLv = curLevel
	params.beginPer = oldSliderValue
	params.endPer = newSliderValue
	params.time = 0.01
	params.perStep = 0.01
	params.callback = function (curLv, curPer)
		slider.value = curPer
        local nextCount = DataManager.ActPvpData:getBountyLevelExp(curLv)
		local ss = nextCount
		if nextCount then
			ss = math.floor(curPer * nextCount + 0.0000001)
		end
		txSlider:setText(ss .. "/" .. nextCount)
        txLv:setText(curLv)
	end
	params.endCallback = function()
        txSlider:setText(exp .. "/" .. needExp)
        if needExp <= 0 then
            txSlider:setText(I18N:getGlobalText(I18N.GlobalConst.STR_MAX))
        end
        txLv:setText(curLevel)
	end
	local progressBar = ProgressBar:create()
	progressBar:runBar(params)

    uiMap["battle_actpvp_result_ui.reward_node.point_bg.desc_1"]:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_15) .. "+" .. addExp)
end

function BattleActPvpResultUI: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 actData = DataManager.ActPvpData
    self.txFightWin:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_19, actData:getWinCount() .. "/" .. actData:getWinLimit()))
    self.txFightLose:setText(I18N:getGlobalText(I18N.GlobalConst.ACT_PVP_DESC_20, actData:getLoseCount() .. "/" .. actData:getLoseLimit()))
end

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