local ChapterManager = class("ChapterManager", BaseModule)

function ChapterManager:openBox(chapterId, index)
    if DataManager.ChapterData:getChapterBoxRewardGot(chapterId, index) then
        return
    end

    local parmas = {
        chapter_id = chapterId,
        wave = index,
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterBoxRewardReq, parmas, {}, self.openBoxFinish, BIReport.ITEM_GET_TYPE.CHAPTER_BOX)
end

function ChapterManager:openBoxFinish(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local reqData = result.reqData
        GFunc.showRewardBox(result.rewards)
        DataManager.ChapterData:openBox(reqData.chapter_id, reqData.wave)

        BIReport:postChapterOpenBox(reqData.chapter_id, DataManager.ChapterData:getChapterBoxNum(reqData.chapter_id, reqData.wave), result.rewards)

        ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_OPEN_CHAPTER_BOX)
    end
end

function ChapterManager:startFight(isTrail)
    if not DataManager.FormationData:formationIsFull(GConst.BattleConst.FORMATION_TYPE.STAGE) then
        GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_8))
        return
    end
    local cost = DataManager.ChapterData:getFightCost()
    local vitCostNum = 0
    if cost then
        vitCostNum = GFunc.getRewardNum(cost)
    end
    local parmas = {
        chapter_id = DataManager.ChapterData:getChapterId(),
        isTrail = isTrail,
    }
    if vitCostNum > DataManager.BagData.ItemData:getVit() then -- 体力不足
        if isTrail then -- 试玩模式下，体力不足直接进入
            self:startFightFinish({err_code = GConst.ERROR_STR.SUCCESS, reqData = parmas})
            return
        else
            GFunc.showItemNotEnough(GConst.ItemConst.ITEM_ID_VIT)
            ModuleManager.CommerceManager:showBuyVitUI()
            return
        end
    end
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterStartReq, parmas, {}, self.startFightFinish, BIReport.ITEM_GET_TYPE.CHAPTER_FIGHT_START)
end

function ChapterManager:startFightFinish(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        if not result.reqData then
            return
        end
    
        local params = {}
        if result.reqData.isTrail then
            params.atkFormation = DataManager.ChapterData:getCacheTrailAtkInfo()
            DataManager.ShopData:checkPopIntroductGift() -- 标记可弹窗
        end

        ModuleManager.BattleManager:playBattle(GConst.BattleConst.BATTLE_TYPE.STAGE, params)
        -- 上报FB AF章节
        local chapterId = DataManager.ChapterData:getChapterId()
        if result.reqData.chapter_id then
            chapterId = result.reqData.chapter_id
        end
        BIReport:postChapterEvent(chapterId)
    end
end

function ChapterManager:endFight(id, combatReport, gotMysteryBoxIndexs, taskProgress)
    local cfg = ConfigManager:getConfig("chapter")[id]
    local mystery_box_idx = {}
    if gotMysteryBoxIndexs and cfg.mystery_box then
        local indexMap = {}
        for index, wave in ipairs(cfg.mystery_box) do
            if not DataManager.ChapterData:getChapterMysteryBoxIsGot(id, index) then -- 容错一下
                indexMap[wave] = index
            end
        end
        for boardIndex, _ in pairs(gotMysteryBoxIndexs) do
            if indexMap[boardIndex] then
                table.insert(mystery_box_idx, indexMap[boardIndex])
            end
        end
    end

    local parmas = {
        win = combatReport.victory,
        chapter_id = id,
        mystery_box_idx = mystery_box_idx,
        task_stat = taskProgress,
        combatReport = combatReport,
    }

    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterSettlementReq, parmas, {}, self.endFightFinish, BIReport.ITEM_GET_TYPE.CHAPTER_FIGHT_END)
end

function ChapterManager:endFightFinish(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        if not result.reqData then
            return
        end

        local reqData = result.reqData
        local maxChapter = DataManager.ChapterData:getNewChapterId()
        local rewards = {}
        local newRewards = {}
        local mysteryBoxIdx = result.mystery
        for i, reward in ipairs(result.rewards) do
            if i <= mysteryBoxIdx then
                table.insert(newRewards, reward)
            else
                table.insert(rewards, reward)
            end
        end

        if rewards then
            local mergeRewards = {}
            GFunc.mergeRewards2(rewards, mergeRewards, true)
            for _, unit in ipairs(mergeRewards) do
                table.insert(newRewards, unit)
            end
        end

        ModuleManager.BattleManager:showBattleResultUI(GConst.BattleConst.BATTLE_TYPE.STAGE, newRewards, reqData.combatReport, mysteryBoxIdx, nil, true)
        DataManager.ChapterData:fightChapter(reqData.chapter_id, result.max_chapter_id, result.max_wave, reqData.mystery_box_idx)
        -- 处理金猪,要在章节更新之后
        DataManager.GoldPigData:addGoldPigCount()

        local newMaxChapter = DataManager.ChapterData:getNewChapterId()
        if maxChapter ~= newMaxChapter then
            local data = {}
            data.max_chapter = DataManager.ChapterData:getMaxChapterId()
            CS.ThinkingAnalytics.ThinkingAnalyticsAPI.UserSet(data)
            -- 标记可弹出新手礼包
            if maxChapter == 1 then
		        DataManager.ShopData:markPopUpGiftForBeginnerGift()
            end
            -- 新章节通关，尝试解锁新功能
            DataManager:tryOpenModules()
            -- 更新每日挑战数据
            ModuleManager.DailyChallengeManager:onResetState()
            -- 更新竞技场数据
            ModuleManager.ArenaManager:reqArenaInfo()
            -- 更新副本活动
            DataManager.DungeonData:setDirty()
            -- 章节通关 标记可弹出章节礼包
            DataManager.ShopData:markPopUpGiftForActChapterStore(maxChapter)
            ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_PASS_CHAPTER)
            -- 章节通关 检查是否要弹出英雄解锁界面
            DataManager.HeroData:checkIfCanShowHeroUnlock(maxChapter)
            -- 章节通关 检查是否要弹出功能解锁界面
            DataManager.PlayerData:checkIfCanShowModuleUnlock(maxChapter)
            -- 评价弹窗
            self:tryShowEvaluationPopup(maxChapter)
        end

        -- 试玩
        local fightChapterId = result.reqData.chapter_id or 0
        if not reqData.win and DataManager.ShopData:getIntroductGiftTriggerTime() > 0 then -- 入门礼包触发过后, 触发试玩
            if fightChapterId >= GConst.HeroConst.TRIAL_HERO_MIN_CHAPTER and fightChapterId <= GConst.HeroConst.TRIAL_HERO_MAX_CHAPTER then
                DataManager.ChapterData:cacheTrailHeroIdAndChapterId(GConst.HeroConst.TRIAL_HERO_ID, fightChapterId)
            else
                DataManager.ChapterData:cacheTrailHeroIdAndChapterId()
            end
        else
            DataManager.ChapterData:cacheTrailHeroIdAndChapterId()
        end

        -- 第二章战斗结算,触发成长礼包
        if result.reqData.chapter_id == GConst.ShopConst.INTRODUCTORY_GIFT_TRIGGER_CHAPTER_ID then
            DataManager.ShopData:onTriggerIntroductGift()
        end

        if not reqData.win then
            DataManager.ShopData:markPopLastChapterActGift()
            if DataManager.ChapterData:getChapterFightCount(fightChapterId) == 1 then -- 首次失败上报
                BIReport:postFirstDayGradeFailEvent(fightChapterId)
            end
        end

        ModuleManager.TaskManager:addFightTaskProgress(reqData.task_stat)
    end
end

function ChapterManager:tryShowEvaluationPopup(chapter)
    if chapter ~= 4 then -- 改为第四章
        return
    end
    UIManager:showUI("app/ui/game_setting/rate_ui")
end

function ChapterManager:showHeroTrialUI(heroId, chapterId)
    local heroEntity = DataManager.HeroData:getHeroById(heroId)
    if not heroEntity or heroEntity:isActived() then -- 配置表没有或者已激活则不弹
        return
    end
    UIManager:showUI("app/ui/main_city/hero_trial_ui", {heroId = heroId, chapterId = chapterId})
end

return ChapterManager