local DungeonArmorManager = class("DungeonArmorManager", BaseModule)

function DungeonArmorManager:showMainUI()
    UIManager:showUI("app/ui/dungeon_armor/dungeon_armor_main_ui")
end

function DungeonArmorManager:showFightUI(chapterId)
    UIManager:showUI("app/ui/dungeon_armor/dungeon_armor_fight_ui", {chapterId = chapterId})
end

function DungeonArmorManager:showFarmUI(chapterId)
    UIManager:showUI("app/ui/dungeon_armor/dungeon_armor_farm_ui", {chapterId = chapterId})
end

function DungeonArmorManager:showStarRewardUI()
    UIManager:showUI("app/ui/dungeon_armor/dungeon_armor_star_reward_ui")
end

function DungeonArmorManager:showBattleTaskUI()
    UIManager:showUI("app/ui/dungeon_armor/dungeon_armor_task_ui")
end

function DungeonArmorManager:reqFight(chapterId)
    if not DataManager.FormationData:formationIsFull(GConst.BattleConst.FORMATION_TYPE.DUNGEON_ARMOR) then
        GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.BATTLE_DESC_8))
        return
    end

    local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
    if not armorData:canFightChapter(chapterId) then
        return
    end

    -- 判断次数
    if armorData:getRemianFarmCount(chapterId) <= 0 then
        GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.DAILY_CHALLENGE_DESC_1))
        return
    end

    -- 判断体力
    if not DataManager.DungeonData:isEnoughHp(ModuleManager.MODULE_KEY.DUNGEON_ARMOR) then
        GFunc.showItemNotEnough(GConst.ItemConst.ITEM_ID_VIT)
        ModuleManager.CommerceManager:showBuyVitUI()
        return
    end

    local heroes = {}
    local formation = DataManager.FormationData:getDungeonArmorFormation()
    for matchType, heroId in pairs(formation) do
        if heroId > 0 then
            table.insert(heroes, heroId)
        end
    end
    local parmas = {chapter_armor_id = chapterId, heroes = heroes}
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterArmorChallengeStartReq, parmas, {}, self.rspFight, BIReport.ITEM_GET_TYPE.DUNGEON_ARMOR_CHALLENGE)
end

function DungeonArmorManager:rspFight(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
        if result.reqData then
            armorData:setCurFightChapterId(result.reqData.chapter_armor_id)
            armorData:refreshFarmCount(result.reqData.chapter_armor_id, result.farm_count)
        end
        local params = {
            atkFormation = {}
        }
        local formation = DataManager.FormationData:getDungeonArmorFormation()
        for elementType, heroId in pairs(formation) do
            local heroEntity = DataManager.HeroData:getHeroById(heroId)
            if heroEntity then
                params.atkFormation[elementType] = heroEntity
            end
        end
        ModuleManager.BattleManager:playBattle(GConst.BattleConst.BATTLE_TYPE.DUNGEON_ARMOR, params, function()
            UIManager:closeAllUI()
            ModuleManager.MaincityManager:showMainCityUI()
            self:showMainUI()
        end)
        DataManager.DungeonData:setDirty()
    end
end

function DungeonArmorManager:reqEndChallenge(chapterId, combatReport, taskProgress)
    local parmas = {
        chapter_armor_id = chapterId,
        win = combatReport.victory,
        task_stat = taskProgress,
        combatReport = combatReport,
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterArmorChallengeSettlementReq, parmas, {}, self.rspEndChallenge, BIReport.ITEM_GET_TYPE.DUNGEON_ARMOR_END)
end

function DungeonArmorManager:rspEndChallenge(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
        local passId = armorData:getPassedMaxId()
        if result.reqData then
            armorData:refreshInfoOnSettlement(result.reqData.chapter_armor_id, result)
        end
        ModuleManager.BattleManager:showBattleArmorResultUI(GConst.BattleConst.BATTLE_TYPE.DUNGEON_ARMOR, result.rewards, result.reqData.combatReport)
        DataManager.DungeonData:setDirty()

        if passId ~= armorData:getPassedMaxId() then
            local data = {}
            data.dungeon_progress = DataManager.DungeonData:getDungeonBIStr()
            CS.ThinkingAnalytics.ThinkingAnalyticsAPI.UserSet(data)
        end

        if result.reqData then
            local taskStat = result.reqData.task_stat
            if taskStat then
                ModuleManager.TaskManager:addFightTaskProgress(taskStat)
            end
        end
    end
end

-- 请求扫荡副本
function DungeonArmorManager:reqSweep(chapterId, target)
    local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)

    -- 判断次数
    if armorData:getRemianFarmCount(chapterId) <= 0 then
        GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.DUNGEON_WEAPON_DESC_13))
        return
    end

    -- 判断体力
    if not DataManager.DungeonData:isEnoughHp(ModuleManager.MODULE_KEY.DUNGEON_ARMOR) then
        GFunc.showItemNotEnough(GConst.ItemConst.ITEM_ID_VIT)
        ModuleManager.CommerceManager:showBuyVitUI()
        return
    end

    if not armorData:canFarmChapter(chapterId) then
        return
    end

    local parmas = {
        chapter_armor_id = chapterId,
        target = target, -- 扫荡目标（客户端用）
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterArmorChallengeFarmReq, parmas, {}, self.rspSweep, BIReport.ITEM_GET_TYPE.DUNGEON_ARMOR_SWEEP)
end

-- 响应扫荡副本
function DungeonArmorManager:rspSweep(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
        local remainCount = 0
        if result.reqData then
            armorData:refreshInfoOnFarm(result.reqData.chapter_armor_id, result)
            remainCount = armorData:getRemianFarmCount(result.reqData.chapter_armor_id)
        end

        -- 合并奖励
        local newRewards = {}
        GFunc.mergeRewards2(result.rewards, newRewards)
        ModuleManager.CommonManager:showMopUpUI(ModuleManager.MODULE_KEY.DUNGEON_ARMOR, newRewards, remainCount, function()
            if result.reqData then
                self:reqSweep(result.reqData.chapter_armor_id, result.reqData.target)
            end
        end, nil, result.reqData.target)
        DataManager.DungeonData:setDirty()
    end
end

function DungeonArmorManager:reqStarReward(starId)
    local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
    if armorData:getStarRewardGot(starId) then
        return
    end

    local parmas = {
        id = starId,
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterArmorStarRewardReq, parmas, {}, self.respStarReward, BIReport.ITEM_GET_TYPE.DUNGEON_ARMOR_STAR_REWARD)
end

function DungeonArmorManager:respStarReward(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        GFunc.showRewardBox(result.rewards)
        local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
        if result.reqData then
            armorData:setStarReward(result.reqData.id)
        end
        DataManager.DungeonData:setDirty()
    end
end

-- 领取基金奖励
function DungeonArmorManager:reqFundReward(id)
    local parmas = {
        id = id,-- id为1是广告奖励
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterArmorFundRewardReq, parmas, {}, self.respFundReward, BIReport.ITEM_GET_TYPE.DUNGEON_ARMOR_FUND_REWARD)
end

function DungeonArmorManager:respFundReward(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        GFunc.showRewardBox(result.rewards)
        local armorData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_ARMOR)
        if result.reqData then
            armorData:onGetFundRewardSuccess(result.reqData.id)
        end
        DataManager.DungeonData:setDirty()
    end
end

function DungeonArmorManager:reqFormation(formation)
    local heroes = {}
    for matchType, heroId in pairs(formation) do
        if heroId and heroId > 0 then
            table.insert(heroes, heroId)
        end
    end
    local params = {
        heroes = heroes
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterArmorChallengeHeroesReq, params, {}, self.rspFormation)
end

function DungeonArmorManager:rspFormation(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.FORMATION_CHANGE, {type = GConst.BattleConst.FORMATION_TYPE.DUNGEON_ARMOR})
    end
end

return DungeonArmorManager