local DungeonWeaponManager = class("DungeonWeaponManager", BaseModule)

function DungeonWeaponManager:showMainUI()
    UIManager:showUI("app/ui/dungeon_weapon/dungeon_weapon_main_ui")
end

function DungeonWeaponManager:showIntroductionUI(chapterId)
    local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)
    local passInfo = weaponData:getCachePassInfo(chapterId)
    if not passInfo then
        self:reqPassInfo(chapterId)
    end
    UIManager:showUI("app/ui/dungeon_weapon/dungeon_weapon_introduction_ui", {chapterId = chapterId})
end

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

    local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)
    if weaponData:canFarmChapter(chapterId) then
        if not DataManager.DungeonData:isEnoughHp(ModuleManager.MODULE_KEY.DUNGEON_WEAPON) then
            GFunc.showItemNotEnough(GConst.ItemConst.ITEM_ID_VIT)
            ModuleManager.CommerceManager:showBuyVitUI()
            return
        end
    end

    if not weaponData:canFightChapter(chapterId) then
        return
    end

    local heroes = {}
    local formation = DataManager.FormationData:getDungeonWeaponFormation()
    for matchType, heroId in pairs(formation) do
        if heroId > 0 then
            table.insert(heroes, heroId)
        end
    end
    local parmas = {chapter_weapon_id = chapterId, heroes = heroes}
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterWeaponChallengeStartReq, parmas, {}, self.rsqFight, BIReport.ITEM_GET_TYPE.DUNGEON_WEAPON_CHALLENGE)
end

function DungeonWeaponManager:rsqFight(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)
        weaponData:setCurFightChapterId(result.reqData.chapter_weapon_id)
        local params = {
            atkFormation = {}
        }
        local formation = DataManager.FormationData:getDungeonWeaponFormation()
        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_WEAPON, params, function()
            UIManager:closeAllUI()
            ModuleManager.MaincityManager:showMainCityUI()
            self:showMainUI()
        end)

        DataManager.DungeonData:setDirty()
    end
end

function DungeonWeaponManager:reqEndChallenge(chapterId, combatReport, taskProgress)
    local parmas = {
        chapter_weapon_id = chapterId,
        win = combatReport.victory,
        task_stat = taskProgress,
        combatReport = combatReport,
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterWeaponChallengeSettlementReq, parmas, {}, self.rspEndChallenge, BIReport.ITEM_GET_TYPE.DUNGEON_WEAPON_END)
end

function DungeonWeaponManager:rspEndChallenge(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)
        local passId = weaponData:getPassedMaxId()
        weaponData:refreshInfoOnSettlement(result.reqData.chapter_weapon_id, result)

        local firstRewardsIdx = #result.first_rewards
        local rewardCount = #result.rewards
        if firstRewardsIdx > rewardCount then
            firstRewardsIdx = rewardCount
        end
        local rewards = {}
        for i = firstRewardsIdx + 1, rewardCount do
            table.insert(rewards, result.rewards[i])
        end
        local newRewards = {}
        GFunc.mergeRewards2(rewards, newRewards)
        local resultRewards = {}
        for i = 1, firstRewardsIdx do
            table.insert(resultRewards, result.rewards[i])
        end
        for _, reward in ipairs(newRewards) do
            table.insert(resultRewards, reward)
        end
        ModuleManager.BattleManager:showBattleResultUI(GConst.BattleConst.BATTLE_TYPE.DUNGEON_WEAPON, resultRewards, result.reqData.combatReport, nil, firstRewardsIdx, true)
        DataManager.DungeonData:setDirty()

        if passId ~= weaponData: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 DungeonWeaponManager:reqSweep(chapterId, target)
    local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)

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

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

    if not weaponData:canFarmChapter(chapterId) then
        return
    end

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

-- 响应扫荡副本
function DungeonWeaponManager:rspSweep(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)
        weaponData:refreshInfoOnFarm(result)

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

function DungeonWeaponManager:reqPassInfo(chapterId)
    local parmas = {
        chapter_weapon_id = chapterId,
    }
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChapterWeaponLatestPlayerInfoReq, parmas, {}, self.rspPassInfo)
end

function DungeonWeaponManager:rspPassInfo(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
        local weaponData = DataManager.DungeonData:getDungeonDataByType(ModuleManager.MODULE_KEY.DUNGEON_WEAPON)
        weaponData:doCachePassInfo(result.reqData.chapter_weapon_id, result.players)
    end
end

function DungeonWeaponManager: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.ChapterWeaponChallengeHeroesReq, params, {}, self.rspFormation)
end

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

return DungeonWeaponManager