local ArenaManager = class("ArenaManager", BaseModule)

function ArenaManager:checkSeasonChange()
    if not DataManager.ArenaData:isInSeasonTime() then
        -- 不在赛季时间段，赛季改变
       self:onSeasonChanged() 
    elseif not DataManager.ArenaData:isInSeasonSettlementTime() then
        -- 不在赛季结算时间段，赛季锁定
        self:onSeasonSettlement()
    else
        -- 赛季未发生改变，不处理
    end
end

-- 赛季结算
function ArenaManager:onSeasonSettlement()
    if EDITOR_MODE then
        Logger.logHighlight("赛季结算")
    end
    EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ARENA_SEASON_SETTLEMENT)
end

-- 赛季改变
function ArenaManager:onSeasonChanged()
    if EDITOR_MODE then
        Logger.logHighlight("赛季改变")
    end
    if self.isResetting then
		return
	end

    DataManager.ArenaData:onSeasonChanged()
    self:reqArenaInfo()
    EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ARENA_SEASON_END)
end

-- 标记ad宝箱
function ArenaManager:markAdBox(isWin)
    self.willShowAdBoxState = isWin
end

-- 获取ad宝箱弹出状态
function ArenaManager:getAdBoxState()
    return self.willShowAdBoxState
end

-- 匹配
function ArenaManager:reqMatch()
    self:sendMessage(ProtoMsgType.FromMsgEnum.MatchReq, {}, {}, self.rspMatch, nil)
end

function ArenaManager:rspMatch(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onMatchInfoReceived(result.match_info)
    end
end

-- 挑战
function ArenaManager:reqChallenge()
    if DataManager.ArenaData:getMatchInfo() == nil then
		ModuleManager.ArenaManager:reqMatch()
        return
	end

    -- 判断体力
    if not DataManager.ArenaData:isEnoughTicket() then
        GFunc.showItemNotEnough(GConst.ItemConst.ITEM_ID_ARENA_TICKET)
        ModuleManager.CommerceManager:showBuyArenaTicketUI()
        return
    end

    -- 判断阵容
    if not DataManager.FormationData:formationIsFull(GConst.BattleConst.FORMATION_TYPE.ARENA_ATTACK) then
        GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_8))
        return
    end

    local reqData = {
        defInfo = DataManager.ArenaData:getMatchInfo()
    }

    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPChallengeStartReq, reqData, {}, self.rspChallenge, BIReport.ITEM_GET_TYPE.ARENA_CHALLENGE)
end

function ArenaManager:rspChallenge(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local atkFormation = {}
        local defFormation
        if result.reqData and result.reqData.defInfo then
            defFormation = GFunc.formatPlayerFormationInfo(result.reqData.defInfo)
        else
            return
        end

        for idx, id in pairs(DataManager.FormationData:getArenaAttackFormation()) do
            local hero = DataManager.HeroData:getHeroById(id)
            if hero then
                atkFormation[idx] = hero
            end
        end

        local params = {
            defInfo = result.reqData.defInfo,
            atkFormation = atkFormation,
            defFormation = defFormation
        }
        ModuleManager.BattleManager:playBattle(GConst.BattleConst.BATTLE_TYPE.ARENA, params)

        --bi上报
        LocalData:recordTodayArenaBattle()
        BIReport:postArenaConsume(DataManager.ArenaData:getGradingId(), LocalData:getTodayArenaBattleCount())
    end
end

-- 结算
function ArenaManager:reqSettlement(win, battleReport, taskProgress)
    local parmas = {
        win = win,
        season = DataManager.ArenaData:getSeason(),
        task_stat = taskProgress,
        battleReport = battleReport,
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPChallengeSettlementReq, parmas, {}, self.rspSettlement, BIReport.ITEM_GET_TYPE.ARENA_SETTLEMENT)
end

function ArenaManager:rspSettlement(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local reqData = result.reqData

        DataManager.ArenaData:onBattleResultReceived(result.score, result.settlement, result)
        DataManager.ArenaData:initGiftInfo(result.act_arena_gift)
        local checkCount = 0
        if result.settlement.win then
            checkCount = result.total_win_count
        else
            checkCount = result.total_lose_count
        end
        -- 展示结算界面
        ModuleManager.BattleManager:showArenaBattleResultUI(result.settlement, result.rewards, checkCount)
        self:checkSeasonChange()

        if result.reqData then
            local taskStat = result.reqData.task_stat
            if taskStat then
                taskStat[GConst.BattleConst.BATTLE_TASK_FIELD.KILL_BOSS] = 0 -- boss不算
                taskStat[GConst.BattleConst.BATTLE_TASK_FIELD.KILL_NORMAL_MONSTER] = 0 -- 击杀小怪数量不算
                taskStat[GConst.BattleConst.BATTLE_TASK_FIELD.PASS_WAVE] = 0 -- 通关波数不算
                ModuleManager.TaskManager:addFightTaskProgress(taskStat)
            end
        end
        ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_ARENA_CHALLENGE)
        EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ARENA_BATTLE_SETTLEMENT, result.settlement.win)

        --bi上报
        local winRate = result.total_win_count / (result.total_win_count + result.total_lose_count)
        BIReport:postArenaSettlement(DataManager.ArenaData:getGradingId(), reqData.battleReport.round, winRate, result.settlement.win)
    end
end

-- 战报
function ArenaManager:reqRecord()
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPRecordHistoryReq, {}, {}, self.rspRecord, nil)
end

function ArenaManager:rspRecord(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onRecentBattleReceived(result.history)
        EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ARENA_RECORD_SUCCESS)
    end
end

-- 排行榜
function ArenaManager:reqRank()
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPRankReq, {}, {}, self.rspRank, nil)
end

function ArenaManager:rspRank(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onRankDataReceived(result.rank, result.top100.info)
        EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ARENA_RANK_SUCCESS)
    end
end

-- 排行榜玩家编队信息
function ArenaManager:reqRankHeroes(id)
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPRankHeroesReq, {rid = id}, {}, self.rspRankHeroes, nil)
end

function ArenaManager:rspRankHeroes(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onRankFormationReceived(result.reqData.rid, result)
    end
end

-- 领取上赛季奖励
function ArenaManager:reqLastSeasonReward()
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPSeasonRewardReq, {}, {}, self.rspLastSeasonReward, BIReport.ITEM_GET_TYPE.ARENA_REWARD)
end

function ArenaManager:rspLastSeasonReward(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onLastSeasonRewardReceived()
        GFunc.showRewardBox(result.rewards)
    end
end

-- 更新赛季信息
function ArenaManager:reqArenaInfo()
    if not DataManager.ArenaData:isOpen() then
        return
    end
    self.isResetting = true
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPInfoReq, {}, {}, self.rspArenaInfo, nil)
end

function ArenaManager:rspArenaInfo(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        self.isResetting = false
        DataManager.ArenaData:init(result.arena_info)
    end
end

-- 结束匹配cd
function ArenaManager:reqOverCD(isAd)
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPOverCDReq, {ad = isAd}, {}, self.rspOverCD, BIReport.ITEM_GET_TYPE.ARENA_REMATCH_CD)
end

function ArenaManager:rspOverCD(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onOverFreeRematchCD(result.reqData.ad)
        self:reqMatch()
    end
end

-- 领取广告宝箱
function ArenaManager:reqAdBoxReward(isWin)
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPSettlementADRewardReq, {win = isWin}, {}, self.rspAdBoxReward, BIReport.ITEM_GET_TYPE.ARENA_AD_BOX_REWARD)
end

function ArenaManager:rspAdBoxReward(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        self.willShowAdBoxState = nil
        local idx = result.reqData.win and 2 or 1
        ModuleManager.ShopManager:showBoxOpenUI({type = GConst.ShopConst.BOX_REWARD_TYPE.ARENA_AD_BOX, params = idx, rewards = result.rewards})
        EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.ARENA_AD_BOX_SUCCESS)
    end
end

function ArenaManager:showGiftPopUI(showType)
    UIManager:showUI("app/ui/arena/arena_pop_gift_ui", {showType = showType})
end

-- 领取段位奖励
function ArenaManager:reqGradingReward(id)
    local getIds = {}
    table.insert(getIds, id)
    self:sendMessage(ProtoMsgType.FromMsgEnum.PVPStageRewardReq, {ids = getIds}, {}, self.rspGradingReward, BIReport.ITEM_GET_TYPE.ARENA_GRADING_REWARD)
end

function ArenaManager:rspGradingReward(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        DataManager.ArenaData:onGradingRewardReceived(result.reqData.ids)
        GFunc.showRewardBox(result.rewards)
    end
end

return ArenaManager