package com.red.circle.other.app.command.room.query;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.common.business.enums.SVIPLevelEnum;
import com.red.circle.live.inner.endpoint.LiveMicClient;
import com.red.circle.other.app.common.room.RoomVoiceProfileCommon;
import com.red.circle.other.app.dto.clientobject.room.RoomVoiceProfileCO;
import com.red.circle.other.app.service.game.GameLudoService;
import com.red.circle.other.app.service.room.RocketStatusCacheService;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.domain.gateway.user.ability.UserSVipGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.domain.rocket.RocketStatus;
import com.red.circle.other.infra.database.cache.service.user.RegionRoomCacheService;
import com.red.circle.other.infra.database.mongo.entity.live.ActiveVoiceRoom;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfileManager;
import com.red.circle.other.infra.database.mongo.entity.live.RoomUserBlacklist;
import com.red.circle.other.infra.database.mongo.service.live.ActiveVoiceRoomService;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.infra.database.mongo.service.live.RoomUserBlacklistService;
import com.red.circle.other.infra.database.rds.entity.sys.SysCountryCode;
import com.red.circle.other.infra.database.rds.service.sys.SysCountryCodeService;
import com.red.circle.other.infra.database.rds.service.user.device.LatestMobileDeviceService;
import com.red.circle.other.inner.model.cmd.live.AppActiveVoiceRoomQryCmd;
import com.red.circle.other.inner.model.dto.live.ActiveVoiceRoomCO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 发现房间集合.
 *
 * @author pengliang on 2021/2/21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RoomVoiceDiscoverQryExe {

  private final UserSVipGateway userSVipGateway;
  private final UserRegionGateway userRegionGateway;
  private final RoomVoiceProfileCommon roomVoiceProfileCommon;
  private final ActiveVoiceRoomService activeVoiceRoomService;
  private final RoomUserBlacklistService roomUserBlacklistService;
  private final LatestMobileDeviceService latestMobileDeviceService;
  private final RoomProfileManagerService roomProfileManagerService;
  private final RegionRoomCacheService regionRoomCacheService;
  private final LiveMicClient liveMicClient;
  private final RedisTemplate<String, Object> redisTemplate;
  private final RocketStatusCacheService rocketStatusCacheService;
  private final GameLudoService gameLudoService;
  private final UserProfileGateway userProfileGateway;
  
  private static final String EMPTY_ROOM_CACHE_KEY = "empty_room_cache:*";
  
  // 区域隔离常量 - 与ActiveVoiceRoomServiceImpl保持一致
  private static final Set<String> TR_REGIONS = Set.of("TR");
  private static final Set<String> SA_REGIONS = Set.of("BD","SA", "IN", "PK");
  private static final Set<String> AR_REGIONS = Set.of("AE", "AR", "BH", "DJ", "DZ", "EG", "EY", "ER", "IL", "IQ", "JO", "KM", "KW", "LB", "LY", "MA", "MR", "OM", "PS", "QA", "SD", "SO", "SS", "SY", "TD", "TN", "YE");
  private static final Set<String> OTHER_REGIONS = Set.of("OTHER", "PH", "ID", "GH", "IR", "AF", "NG", "DE", "MYS", "TM", "AZ", "NP");

  public List<RoomVoiceProfileCO> execute(AppExtCommand cmd) {
    String region = cmd.isAllRegion() ? "ALL" : userRegionGateway.getRegionCode(cmd.requiredReqUserId());
    UserProfile userProfile = userProfileGateway.getByUserId(cmd.requiredReqUserId());

    String key = cmd.requireReqSysOrigin() + region;
    String regionsRoom = regionRoomCacheService.getRegionsRoom(key);
    if (Objects.nonNull(regionsRoom)) {
      List<RoomVoiceProfileCO> roomList = JSON.parseArray(regionsRoom, RoomVoiceProfileCO.class);
      if (CollectionUtils.isEmpty(roomList)) {
        return CollectionUtils.newArrayList();
      }
      List<RoomVoiceProfileCO> availableRooms = roomVoiceProfileCommon
          .filterAvailableRoomProfiles(roomList);
      if (availableRooms.size() != roomList.size()) {
        regionRoomCacheService.remove(key);
      }
      return availableRooms;
    }

    String userCountryCode = userProfile != null ? userProfile.getCountryCode() : null;
    List<ActiveVoiceRoom> activeVoiceRooms = activeVoiceRoomService.listDiscover(cmd.requireReqSysOrigin(), cmd.isAllRegion(), region, userCountryCode, 50);

    // 查询没人的房间缓存，加入进去
    List<ActiveVoiceRoom> emptyRooms = getEmptyRoomsFromCache();
    if (CollectionUtils.isNotEmpty(emptyRooms)) {
      List<ActiveVoiceRoom> matchedEmptyRooms = filterEmptyRoomsByRegion(emptyRooms, cmd.requireReqSysOrigin(), cmd.isAllRegion(), region, userCountryCode);
      if (CollectionUtils.isNotEmpty(matchedEmptyRooms)) {
        List<ActiveVoiceRoom> allRooms = new ArrayList<>(activeVoiceRooms);
        Set<Long> existingRoomIds = activeVoiceRooms.stream()
            .map(ActiveVoiceRoom::getId)
            .collect(Collectors.toSet());
        matchedEmptyRooms.stream()
            .filter(room -> !existingRoomIds.contains(room.getId()))
            .forEach(allRooms::add);
        activeVoiceRooms = allRooms;
      }
    }
    List<RoomVoiceProfileCO> roomList = roomVoiceProfileCommon.toListRoomVoiceProfileCO(activeVoiceRooms);

    if (CollectionUtils.isEmpty(roomList)) {
      return CollectionUtils.newArrayList();
    }
    Map<Long, SVIPLevelEnum> svipLevelEnumMap = userSVipGateway.checkSVipIdentity(
        roomList.stream().map(RoomVoiceProfileCO::getUserId).collect(
            Collectors.toSet()));
    roomList = roomList.stream()
            .peek(room -> {
              room.setUserSVipLevel(svipLevelEnumMap.get(room.getUserId()));
            })
            .toList();

      // 填充火箭状态
      fillRocketStatus(roomList);
      // 填充游戏图标
      fillGameIcon(roomList);

    return roomList;
  }

  private void fillGameIcon(List<RoomVoiceProfileCO> roomList) {
    if (CollectionUtils.isEmpty(roomList)) {
      return;
    }
    List<Long> roomIds = roomList.stream().map(RoomVoiceProfileCO::getId).toList();
    Map<Long, String> coverMap = gameLudoService.listGameCoverByRoomIds(roomIds);
    roomList.forEach(room -> room.setRoomGameIcon(coverMap.get(room.getId())));
  }

    /**
     * 填充房间的火箭状态信息
     *
     * @param roomList 房间列表
     */
    private void fillRocketStatus(List<RoomVoiceProfileCO> roomList) {
        if (CollectionUtils.isEmpty(roomList)) {
            return;
        }

        List<Long> roomIds = roomList.stream().map(RoomVoiceProfileCO::getId).toList();
        Map<Long, RocketStatus> rocketStatusMap = rocketStatusCacheService.batchGetRocketStatus(roomIds);

        roomList.forEach(room -> {
            RocketStatus rocketStatus = rocketStatusMap.get(room.getId());
            if (rocketStatus != null) {
                room.setRocketLevel(rocketStatus.getLevel().getLevel());
                room.setRocketEnergy(rocketStatus.getCurrentEnergy());
            } else {
                // 没有火箭状态时设置默认值
                room.setRocketLevel(0);
                room.setRocketEnergy(0L);
            }
        });
    }


  /**
   * 筛选有人房间，删除没人房间
   *
   * @param roomList
   * @return
   */
  private List<Long> formatRoomList(List<ActiveVoiceRoom> roomList) {
    List<Long> notUserRooms = new ArrayList<>();
    //只显示有人活跃用户，获取在线人数大于0的房间
    roomList.forEach(item -> {
      if (item.getFixedWeights() == 0) {
        Long roomUser = liveMicClient.getLiveRoomUserSize(item.getId()).getBody();
        if (roomUser == 0) {
          notUserRooms.add(item.getId());
        }
      }
    });
    if (!notUserRooms.isEmpty()) {
      activeVoiceRoomService.removeByIds(notUserRooms);
      return notUserRooms;
    }
    return CollectionUtils.newArrayList();
  }

  public static void main(String[] args) {
    String regionsRoom = "[{\"countryCode\":\"IA\",\"countryName\":\"Indonesia_II\",\"event\":\"AVAILABLE\",\"extValues\":{\"existsPassword\":false,\"memberQuantity\":\"1\",\"roomSetting\":{\"adminLockSeat\":true,\"allowMusic\":true,\"joinGolds\":20,\"maxAdmin\":6,\"maxMember\":1000,\"mikeSize\":10,\"openKtvMode\":false,\"password\":\"\",\"roomSpecialMikeType\":\"\",\"showHeartbeat\":true,\"takeMicRole\":\"ALL\",\"touristMike\":true,\"touristMsg\":true}},\"hotRoom\":false,\"id\":1838887943867809794,\"layoutKey\":\"\",\"roomAccount\":\"45798\",\"roomBadgeIcons\":[],\"roomCover\":\"https://dev.file.momooline.com/yolo/avatar/e5fc30ea-67d0-4d59-ab4a-68bd6d8c26f1.jpg\",\"roomDesc\":\"Welcome everyone! Let's chat and have fun together.\",\"roomGameIcon\":\"\",\"roomName\":\"印尼2邀请用户选1\",\"sysOrigin\":\"YOLO\",\"userId\":1838886627921707009,\"userProfile\":{\"account\":\"45798\",\"accountStatus\":\"NORMAL\",\"accountStatusName\":\"正常\",\"actualAccount\":\"45798\",\"actualAccountStatus\":\"NORMAL\",\"age\":29,\"bornDay\":1,\"bornMonth\":1,\"bornYear\":1995,\"countryCode\":\"IA\",\"countryId\":1231833301707141123,\"countryName\":\"Indonesia_II\",\"createTime\":1727259712000,\"del\":false,\"freezingTime\":1727173312000,\"id\":1838886627921707009,\"originSys\":\"YOLO\",\"sysOriginChild\":\"YOLO\",\"useProps\":[{\"expireTime\":1727493105000,\"propsResources\":{\"amount\":1000.00,\"code\":\"frame-7\",\"cover\":\"https://dev.file.momooline.com/svga_cover/manager-bbe91ecd-2927-4c0f-836a-8ff04c30635f.png\",\"expand\":\"\",\"id\":1719632957716381698,\"name\":\"花仙之芯\",\"sourceUrl\":\"https://dev.file.momooline.com/svgasource/manager-88a87ec4-40f4-4539-8dd1-02611891986a.svga\",\"type\":\"AVATAR_FRAME\"},\"userId\":1838886627921707009}],\"userAvatar\":\"https://dev.file.momooline.com/yolo/avatar/e5fc30ea-67d0-4d59-ab4a-68bd6d8c26f1.jpg\",\"userNickname\":\"印尼2邀请用户选1\",\"userSex\":1,\"wearBadge\":[]},\"userSVipLevel\":\"NONE\"},{\"countryCode\":\"IA\",\"countryName\":\"Indonesia_II\",\"event\":\"AVAILABLE\",\"extValues\":{\"existsPassword\":false,\"memberQuantity\":\"1\",\"roomSetting\":{\"adminLockSeat\":true,\"allowMusic\":true,\"joinGolds\":20,\"maxAdmin\":6,\"maxMember\":1000,\"mikeSize\":10,\"openKtvMode\":false,\"password\":\"\",\"roomSpecialMikeType\":\"\",\"showHeartbeat\":true,\"takeMicRole\":\"ALL\",\"touristMike\":true,\"touristMsg\":true}},\"hotRoom\":false,\"id\":1839143181329285121,\"layoutKey\":\"\",\"roomAccount\":\"45807\",\"roomBadgeIcons\":[],\"roomCover\":\"https://dev.file.momooline.com/yolo/avatar/0b957522-41b6-4d39-9772-10d22ed43584.jpg\",\"roomDesc\":\"Welcome everyone! Let's chat and have fun together.\",\"roomGameIcon\":\"\",\"roomName\":\"cvgm\",\"sysOrigin\":\"YOLO\",\"userId\":1839126188841058305,\"userProfile\":{\"account\":\"45807\",\"accountStatus\":\"NORMAL\",\"accountStatusName\":\"正常\",\"actualAccount\":\"45807\",\"actualAccountStatus\":\"NORMAL\",\"age\":29,\"bornDay\":1,\"bornMonth\":1,\"bornYear\":1995,\"countryCode\":\"IA\",\"countryId\":1231833301707141123,\"countryName\":\"Indonesia_II\",\"createTime\":1727316827000,\"del\":false,\"freezingTime\":1727230427000,\"id\":1839126188841058305,\"originSys\":\"YOLO\",\"sysOriginChild\":\"YOLO\",\"useProps\":[],\"userAvatar\":\"https://dev.file.momooline.com/yolo/avatar/0b957522-41b6-4d39-9772-10d22ed43584.jpg\",\"userNickname\":\"cvgm\",\"userSex\":1,\"wearBadge\":[]},\"userSVipLevel\":\"NONE\"},{\"countryCode\":\"IA\",\"countryName\":\"Indonesia_II\",\"event\":\"AVAILABLE\",\"extValues\":{\"existsPassword\":false,\"memberQuantity\":\"1\",\"roomSetting\":{\"adminLockSeat\":true,\"allowMusic\":true,\"joinGolds\":20,\"maxAdmin\":6,\"maxMember\":1000,\"mikeSize\":10,\"openKtvMode\":false,\"password\":\"\",\"roomSpecialMikeType\":\"\",\"showHeartbeat\":true,\"takeMicRole\":\"ALL\",\"touristMike\":true,\"touristMsg\":true}},\"hotRoom\":false,\"id\":1839145363576954881,\"layoutKey\":\"\",\"roomAccount\":\"45815\",\"roomBadgeIcons\":[],\"roomCover\":\"https://dev.file.momooline.com/yolo/avatar/ad43b964-bef8-4e7e-8beb-2ed41a0996fa.jpg\",\"roomDesc\":\"Welcome everyone! Let's chat and have fun together.\",\"roomGameIcon\":\"\",\"roomName\":\"ghhhh\",\"sysOrigin\":\"YOLO\",\"userId\":1839145323047395330,\"userProfile\":{\"account\":\"45815\",\"accountStatus\":\"NORMAL\",\"accountStatusName\":\"正常\",\"actualAccount\":\"45815\",\"actualAccountStatus\":\"NORMAL\",\"age\":29,\"bornDay\":1,\"bornMonth\":1,\"bornYear\":1995,\"countryCode\":\"IA\",\"countryId\":1231833301707141123,\"countryName\":\"Indonesia_II\",\"createTime\":1727321390000,\"del\":false,\"freezingTime\":1727234989000,\"id\":1839145323047395330,\"originSys\":\"YOLO\",\"sysOriginChild\":\"YOLO\",\"useProps\":[],\"userAvatar\":\"https://dev.file.momooline.com/yolo/avatar/ad43b964-bef8-4e7e-8beb-2ed41a0996fa.jpg\",\"userNickname\":\"ghhhh\",\"userSex\":1,\"wearBadge\":[]},\"userSVipLevel\":\"NONE\"}]";

    System.out.println(JSON.parseArray(regionsRoom, RoomVoiceProfileCO.class));
    List<RoomVoiceProfileCO> roomList = JSON.parseArray(regionsRoom, RoomVoiceProfileCO.class);
    System.out.println(roomList);
  }

  /**
   * 获取没数据的时候提取数据
   *
   * @param cmd
   * @param langeCodes
   * @return
   */
  private List<RoomVoiceProfileCO> getHomeData(AppExtCommand cmd, String langeCodes) {
    AppActiveVoiceRoomQryCmd appActiveVoiceRoomQryCmd =  new AppActiveVoiceRoomQryCmd();
    appActiveVoiceRoomQryCmd.setSysOrigin(cmd.getReqSysOrigin().getOrigin());
    appActiveVoiceRoomQryCmd.setCountryCode("OTHER");
    appActiveVoiceRoomQryCmd.setLimit(100);
    appActiveVoiceRoomQryCmd.setOrderByStrategy(AppActiveVoiceRoomQryCmd.OrderByStrategy.APP_DISCOVERY);
    //获取500个在线活跃房间
    List<ActiveVoiceRoom> roomList = activeVoiceRoomService.listExcludeCountry(appActiveVoiceRoomQryCmd);
    //排除阿拉伯和土耳其
    roomList.removeIf(room -> {
      String regionCode = userRegionGateway.getRegionCode(room.getUserId());
      return Objects.equals(regionCode, "TR") || Objects.equals(regionCode, "AR");
    });
    Set<Long> roomIds = roomList.stream().filter(roomId-> roomId.getOnlineQuantity()>=2).map(ActiveVoiceRoom::getId).collect(Collectors.toSet());
    roomIds= removeBlackAndLockRoom(cmd.requiredReqUserId(), roomIds);
    Set<Long> finalRoomIds = roomIds;
    roomList = roomList.stream()
            .filter(room -> finalRoomIds.contains(room.getId()))
            .collect(Collectors.toList());
    int langeCodesLimit = langeCodes.equals(Locale.ENGLISH.getLanguage()) ? 60 : 30;
    int englishLimit = 30;
    List<ActiveVoiceRoom> langeCodesList = new ArrayList<>(getRoomListLaneCodes(roomList, langeCodes, langeCodesLimit, cmd.requiredReqUserId()));
    if (!langeCodes.equals(Locale.ENGLISH.getLanguage())) {
      langeCodesList.addAll(getRoomListLaneCodes(roomList, Locale.ENGLISH.getLanguage(), englishLimit, cmd.requiredReqUserId()));
    }
    roomList.removeAll(langeCodesList);
    if(roomList.size()>30){
      langeCodesList.addAll(roomList.subList(0, 30));
    }else {
      langeCodesList.addAll(roomList);
    }
    return roomVoiceProfileCommon
            .toListRoomVoiceProfileCO(langeCodesList);
  }


  private List<ActiveVoiceRoom> getRoomListLaneCodes(List<ActiveVoiceRoom> roomList, String langeCodes, Integer limit, Long userId) {
    Set<Long> roomUserIds = roomList.stream()
            .filter(room -> Objects.equals(langeCodes, latestMobileDeviceService.getLatestLanguage(room.getUserId())))
            .map(ActiveVoiceRoom::getId)
            .collect(Collectors.toSet());
    List<ActiveVoiceRoom> filteredRooms = roomList.stream()
            .filter(room -> roomUserIds.contains(room.getId()))
            .collect(Collectors.toList());
    if (filteredRooms.size() <= limit) {
      return filteredRooms;
    } else {
      return filteredRooms.subList(0, limit);
    }
  }

  private List<ActiveVoiceRoom> filterEmptyRoomsByRegion(List<ActiveVoiceRoom> emptyRooms, String sysOrigin, boolean isAllRegion, String region, String userCountryCode) {
    return emptyRooms.stream()
            .filter(room -> Objects.equals(sysOrigin, room.getSysOrigin()) &&
                    (isAllRegion || shouldShowRoom(region, room.getRegion())) &&
                    (!SA_REGIONS.contains(region) || userCountryCode == null || userCountryCode.equals(room.getCountryCode())))
            .collect(Collectors.toList());
  }


  /**
   * 判断是否应该显示该房间
   */
  private boolean shouldShowRoom(String userRegion, String roomRegion) {
    // 获取用户所属区域组
    Set<String> userRegionGroup = getRegionGroup(userRegion);
    Set<String> roomRegionGroup = getRegionGroup(roomRegion);

    // 如果用户在特殊区域组，只显示同组房间
    if (userRegionGroup != null) {
      return userRegionGroup.contains(roomRegion);
    }

    // 如果用户不在特殊区域组，排除所有特殊区域组房间
    return roomRegionGroup == null;
  }

  /**
   * 获取区域所属的特殊区域组（如果不属于任何特殊组则返回null）
   */
  private Set<String> getRegionGroup(String region) {
    if (SA_REGIONS.contains(region)) {
      return SA_REGIONS;
    }
    if (AR_REGIONS.contains(region)) {
      return AR_REGIONS;
    }
    if (OTHER_REGIONS.contains(region)) {
      return OTHER_REGIONS;
    }
    if (TR_REGIONS.contains(region)) {
      return TR_REGIONS;
    }
    return null;
  }


  /**
   * 获取需要排除的区域列表
   */
  private List<String> getRegions(String region) {
    List<String> excludeRegions = new ArrayList<>();
    
    if (SA_REGIONS.contains(region)) {
      excludeRegions.addAll(AR_REGIONS);
      excludeRegions.addAll(OTHER_REGIONS);
    } else if (AR_REGIONS.contains(region)) {
      excludeRegions.addAll(SA_REGIONS);
      excludeRegions.addAll(OTHER_REGIONS);
    } else if (OTHER_REGIONS.contains(region)) {
      excludeRegions.addAll(SA_REGIONS);
      excludeRegions.addAll(AR_REGIONS);
    } else {
      excludeRegions.addAll(SA_REGIONS);
      excludeRegions.addAll(AR_REGIONS);
      excludeRegions.addAll(OTHER_REGIONS);
    }
    
    return excludeRegions;
  }
  
  /**
   * 获取特殊区域组列表
   */
  private List<String> getSpecialRegions(String region) {
    if (SA_REGIONS.contains(region)) {
      return new ArrayList<>(SA_REGIONS);
    }
    
    if (AR_REGIONS.contains(region)) {
      return new ArrayList<>(AR_REGIONS);
    }
    
    if (OTHER_REGIONS.contains(region)) {
      return new ArrayList<>(OTHER_REGIONS);
    }
    
    return new ArrayList<>();
  }

  /**
   * 从缓存中获取没人的房间
   *
   * @return
   */
  private List<ActiveVoiceRoom> getEmptyRoomsFromCache() {
    try {
      Set<String> keys = redisTemplate.keys(EMPTY_ROOM_CACHE_KEY);
      if (CollectionUtils.isEmpty(keys)) {
        return new ArrayList<>();
      }
      
      List<ActiveVoiceRoom> emptyRooms = new ArrayList<>();
      for (String key : keys) {
        String cachedRoom = (String) redisTemplate.opsForValue().get(key);
        if (cachedRoom != null) {
          try {
            // 将缓存对象转换为ActiveVoiceRoomCO，再转换为ActiveVoiceRoom
            ActiveVoiceRoomCO roomCO = JSON.parseObject(cachedRoom, ActiveVoiceRoomCO.class);
            if (roomCO != null) {
              ActiveVoiceRoom room = convertToActiveVoiceRoom(roomCO);
              if (room != null) {
                emptyRooms.add(room);
              }
            }
          } catch (Exception e) {
            log.warn("转换缓存房间对象失败, key: {}", key, e);
          }
        }
      }
      return emptyRooms;
    } catch (Exception e) {
      log.error("获取空房间缓存失败", e);
      return new ArrayList<>();
    }
  }

  /**
   * 将ActiveVoiceRoomCO转换为ActiveVoiceRoom
   *
   * @param roomCO
   * @return
   */
  private ActiveVoiceRoom convertToActiveVoiceRoom(ActiveVoiceRoomCO roomCO) {
    try {
      ActiveVoiceRoom room = new ActiveVoiceRoom();
      BeanUtils.copyProperties(roomCO, room);
      // 设置在线人数为0，因为这是没人的房间
      room.setOnlineQuantity(0L);
      // 设置默认权重（如果未设置的话）
      if (room.getWeights() == null) {
        room.setWeights(0);
      }
      if (room.getFixedWeights() == null) {
        room.setFixedWeights(0);
      }
      return room;
    } catch (Exception e) {
      log.error("转换ActiveVoiceRoomCO失败", e);
      return null;
    }
  }

  /**
   * 去除拉黑和被上锁的的房间
   *
   * @param roomIds
   * @return
   */
  private Set<Long> removeBlackAndLockRoom(Long userId, Set<Long> roomIds) {
    if (CollectionUtils.isEmpty(roomIds)) {
      return Sets.newHashSet();
    }
    //过滤黑名单房间
    List<RoomUserBlacklist> roomUserBlacklists = roomUserBlacklistService.getBlackRoom(
            userId, roomIds);
    Set<Long> blacklistedSet = roomUserBlacklists.stream()
            .map(RoomUserBlacklist::getRoomId).collect(Collectors.toSet());
    roomIds.removeIf(blacklistedSet::contains);
    //过滤被上锁的房间
    List<RoomProfileManager> roomProfileManagerList = roomProfileManagerService.listByRoomIds(roomIds);
    roomProfileManagerList.removeIf(roomId -> !roomId.getSetting().getPassword().isEmpty());
    return roomProfileManagerList.stream()
            .map(RoomProfileManager::getId)
            .collect(Collectors.toSet());
  }


}
