package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.LiveRoomDao;
import com.yonge.cooleshow.biz.dal.dto.CheckCourseTimeDto;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.CourseScheduleEnum;
import com.yonge.cooleshow.biz.dal.enums.RoomTypeEnum;
import com.yonge.cooleshow.biz.dal.service.CourseGroupService;
import com.yonge.cooleshow.biz.dal.service.CourseScheduleService;
import com.yonge.cooleshow.biz.dal.service.LiveRoomService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.support.IMHelper;
import com.yonge.cooleshow.biz.dal.support.WrapperUtil;
import com.yonge.cooleshow.biz.dal.vo.RoomVo;
import com.yonge.cooleshow.common.exception.BizException;
import com.yonge.toolset.utils.date.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

import static com.yonge.cooleshow.biz.dal.constant.LiveRoomConstant.*;
import static com.yonge.cooleshow.common.constant.SysConfigConstant.DESTROY_EXPIRED_LIVE_ROOM_MINUTE;
import static com.yonge.cooleshow.common.constant.SysConfigConstant.PRE_CREATE_LIVE_ROOM_MINUTE;

/**
 * 直播房间与课程的关系表表(LiveRoom)表服务实现类
 *
 * @author hgw
 * @since 2022-03-18 15:41:17
 */
@Service("liveRoomService")
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomDao, LiveRoom> implements LiveRoomService {
    private final static Logger log = LoggerFactory.getLogger(LiveRoomServiceImpl.class);

    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private IMHelper imHelper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CourseGroupService courseGroupService;
    @Autowired
    private CourseScheduleService courseScheduleService;
    @Autowired
    private SysConfigService sysConfigService;

    //生成房间UID
    public static BiFunction<Long, RoomTypeEnum, String> GenRoomUid = (userId, en) -> String.join("-", COOLESHOW, en.getCode(), userId.toString(), new Date().getTime() + "");

    @Override
    public LiveRoomDao getDao() {
        return this.baseMapper;
    }

    /**
     * 根据房间uid查询房间信息
     *
     * @param roomUid 房间uid
     */
    @Override
    public RoomVo queryRoomInfo(String roomUid) {
        LiveRoom liveRoom = this.getOne(Wrappers.<LiveRoom>lambdaQuery()
                .eq(LiveRoom::getRoomUid, roomUid));
        if (liveRoom == null) {
            throw new BizException("房间不存在");
        }
        RoomVo roomVo = new RoomVo();
        BeanUtils.copyProperties(liveRoom, roomVo);
        roomVo.setSpeakerName(getSysUser(liveRoom.getSpeakerId()).getRealName());
        roomVo.setLikeNum(getLike(roomUid));
        roomVo.setLookNum(getLooker(roomUid));
        return roomVo;
    }

    /**
     * 定时任务创建直播间
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createCourseLiveRoom() {
        Date now = new Date();
        //查询房间提前创建的时间
        String preCreateRoomMinute = sysConfigService.findConfigValue(PRE_CREATE_LIVE_ROOM_MINUTE);
        if (StringUtils.isEmpty(preCreateRoomMinute)) {
            log.info("roomDestroy>>>> 未查询到配置：{}", PRE_CREATE_LIVE_ROOM_MINUTE);
            return;
        }
        Date endTime = DateUtil.addMinutes(now, Integer.parseInt(preCreateRoomMinute));
        //查询课时表生成直播间
        List<CourseSchedule> courseScheduleList = courseScheduleService.list(Wrappers.<CourseSchedule>lambdaQuery()
                .eq(CourseSchedule::getType, CourseScheduleEnum.LIVE.getCode())
                .eq(CourseSchedule::getLock, 0)
                .ge(CourseSchedule::getStartTime, now)
                .le(CourseSchedule::getStartTime, endTime));
        if (CollectionUtils.isEmpty(courseScheduleList)) {
            return;
        }
        //获取课程组名称
        Map<Long, String> titleMap = new HashMap<>();
        //获取课程组介绍
        Map<Long, String> remarkMap = new HashMap<>();
        courseScheduleList.stream()
                .map(CourseSchedule::getCourseGroupId)
                .distinct()
                .map(courseGroupService::getById)
                .filter(Objects::nonNull)
                .forEach(courseGroup -> {
                    titleMap.put(courseGroup.getId(), courseGroup.getName());
                    remarkMap.put(courseGroup.getId(), courseGroup.getCourseIntroduce());
                });
        //生成课程对应的房间
        RoomTypeEnum en = RoomTypeEnum.LIVE;
        courseScheduleList.forEach(c -> {
            LiveRoom room = new LiveRoom();
            room.setCourseGroupId(c.getCourseGroupId());
            room.setCourseId(c.getId());
            room.setRoomUid(GenRoomUid.apply(c.getTeacherId(), en));
            room.setRoomTitle(titleMap.get(c.getCourseGroupId()));
            room.setLiveRemark(remarkMap.get(c.getCourseGroupId()));
            room.setSpeakerId(c.getTeacherId());
            room.setLiveStartTime(c.getStartTime());
            room.setLiveEndTime(c.getEndTime());
            room.setLiveState(0);
            room.setRoomState(0);
            room.setType(en.getCode());
            room.setCreatedBy(-2L);
            room.setCreatedTime(now);
            this.save(room);
            //去融云创建房间及创建房间缓存信息
            createLiveRoomInfo(room);
        });
    }

    /**
     * 创建临时房间-直播间
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createTempLiveRoom(Map<String, Object> param) {
        //查询主讲人信息
        SysUser sysUser = getSysUser();
        Date now = new Date();
        //当前时间有课程则不能开启直播
        checkTempLive(sysUser.getId());
        String roomTitle = WrapperUtil.toStr(param, "roomTitle", "房间标题不能为空!");
        String liveRemark = WrapperUtil.toStr(param, "liveRemark", "直播间描述不能为空!");

        Long id = sysUser.getId();
        RoomTypeEnum en = RoomTypeEnum.TEMP;
        String roomUid = GenRoomUid.apply(id, en);
        LiveRoom room = new LiveRoom();
        room.setCourseGroupId(-1L);
        room.setCourseId(-1L);
        room.setRoomUid(roomUid);
        room.setRoomTitle(roomTitle);
        room.setLiveRemark(liveRemark);
        room.setSpeakerId(id);
        room.setLiveStartTime(now);
        room.setLiveState(0);
        room.setRoomState(0);
        room.setCreatedBy(id);
        room.setCreatedTime(now);
        room.setType(en.getCode());
        this.save(room);
        log.info("createTempLiveRoom>>>>>>room:{}", room.getRoomUid());
        //去融云创建房间及创建房间缓存信息
        createLiveRoomInfo(room, sysUser);
        return roomUid;
    }

    /**
     * 校验开启临时直播间是否会有课程冲突
     */
    @SuppressWarnings("unchecked")
    private void checkTempLive(Long teacherId) {
        //查询当前未锁的最近的一节课
        CourseSchedule course = courseScheduleService.getOne(Wrappers.<CourseSchedule>lambdaQuery()
                .eq(CourseSchedule::getTeacherId, teacherId)
                .eq(CourseSchedule::getLock, 0)
                .orderByDesc(CourseSchedule::getStartTime));
        if (Objects.isNull(course)) {
            return;
        }
        Date now = new Date();
        Boolean check = WrapperUtil.inInterSection(now, now, course.getStartTime(), course.getEndTime(), false);
        if (check) {
            //如果当前时间和课程时间有交集则不能开启临时直播
            throw new BizException("当前有陪练课无法开启直播");
        }
    }

    /**
     * 去融云创建房间及创建房间缓存信息-直播间
     */
    private void createLiveRoomInfo(LiveRoom room) {
        //查询主讲人信息
        SysUser sysUser = getSysUser(room.getSpeakerId());
        createLiveRoomInfo(room, sysUser);
    }

    private void createLiveRoomInfo(LiveRoom room, SysUser sysUser) {
        try {
            //生成主讲人信息
            createRoomInfoCache(room, sysUser);
            //去融云创建房间
            createLiveRoom(room.getRoomUid(), room.getRoomTitle());
        } catch (Exception e) {
            throw new BizException("创建直播间失败!", e.getCause());
        }
    }

    //生成主讲人信息
    private void createRoomInfoCache(LiveRoom room, SysUser sysUser) {
        RoomInfoCache roomCache = new RoomInfoCache();
        roomCache.setSpeakerId(sysUser.getId());
        roomCache.setSpeakerName(sysUser.getRealName());
        roomCache.setSpeakerPic(sysUser.getAvatar());
        roomCache.setSpeakerState(1);
        roomCache.setRoomUid(room.getRoomUid());
        roomCache.setLiveStartTime(room.getLiveStartTime());
        roomCache.setLiveEndTime(room.getLiveEndTime());
        roomCache.setCreateRoomTime(new Date());
        String configValue = sysConfigService.findConfigValue(PRE_CREATE_LIVE_ROOM_MINUTE);
        roomCache.setExpiredMinute(Integer.parseInt(configValue));
        roomCache.setRoomType(room.getType());

        //写入房间信息
        redissonClient.getBucket(LIVE_ROOM_INFO.replace(ROOM_UID, room.getRoomUid()))
                .set(roomCache, 2L, TimeUnit.DAYS);
        //生成0点赞
        redissonClient.getBucket(LIVE_ROOM_LIKE.replace(ROOM_UID, room.getRoomUid()))
                .set(0, 2L, TimeUnit.DAYS);
        //生成房间人员列表数据
        redissonClient.getMap(LIVE_ROOM_TOTAL_USER_LIST.replace(ROOM_UID, room.getRoomUid()))
                .expire(2L, TimeUnit.DAYS);
    }

    /**
     * 创建房间-聊天室
     *
     * @param roomId   房间Uid
     * @param roomName 房间名称
     */
    private void createLiveRoom(String roomId, String roomName) {
        IMApiResultInfo resultInfo;
        try {
            resultInfo = imHelper.createChatRoom(roomId, roomName);
        } catch (Exception e) {
            throw new BizException("创建聊天室失败!" + e.getMessage());
        }
        if (!resultInfo.isSuccess()) {
            throw new BizException("创建聊天室失败!" + resultInfo.getErrorMessage());
        }
        log.info("create chatRoom success: {}", roomId);
    }

    /**
     * 定时任务-清理过期的房间
     */
    public void destroyExpiredLiveRoom() {
        //查询房间过期时间
        String expiredMinuteStr = sysConfigService.findConfigValue(DESTROY_EXPIRED_LIVE_ROOM_MINUTE);
        if (StringUtils.isEmpty(expiredMinuteStr)) {
            log.info("roomDestroy>>>> 未查询到配置：{}", DESTROY_EXPIRED_LIVE_ROOM_MINUTE);
            return;
        }
        Date now = new Date();
        //查询已经开始并且没有删除及销毁的直播间
        List<LiveRoom> list = this.list(Wrappers.<LiveRoom>lambdaQuery()
                .eq(LiveRoom::getRoomState, 0)
                .eq(LiveRoom::getLiveState, 1)
                .eq(LiveRoom::getType, RoomTypeEnum.LIVE.getCode())
                .le(LiveRoom::getLiveEndTime, now));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.forEach(room -> {
            Date expiredDate = DateUtil.addMinutes(room.getLiveEndTime(), Integer.parseInt(expiredMinuteStr));
            //当前时间 大于（结束播时间 + 设置的过期分钟数）
            if (now.getTime() >= expiredDate.getTime()) {
                //删除房间
                destroyLiveRoom(room.getRoomUid());
            }
        });
    }

    /**
     * 销毁房间-聊天室
     *
     * @param roomId 房间Uid
     */
    private void destroyLiveRoom(String roomId) {
        //删除服务器房间
        List<String> deleteRoomIds = new ArrayList<String>() {{
            add(roomId);
        }};
        IMApiResultInfo resultInfo;
        try {
            resultInfo = imHelper.deleteChrm(deleteRoomIds);
        } catch (Exception e) {
            throw new BizException("关闭聊天室失败!" + e.getMessage());
        }
        if (!resultInfo.isSuccess()) {
            throw new BizException("关闭聊天室失败!" + resultInfo.getErrorMessage());
        }
        log.info("destroyLiveRoom success: {}", roomId);
    }


    /**
     * <p>主讲人处理进入和退出房间数据
     * <p>观看者只处理退出房间数据
     *
     * @param userState 用户状态数据
     */
    public void opsRoom(List<ImUserStateSync> userState) {
        if (CollectionUtils.isEmpty(userState)) {
            return;
        }
        userState.forEach(user -> {
            log.info("opsRoom>>>> {}", JSONObject.toJSONString(user));
            if (StringUtils.isBlank(user.getStatus())) {
                return;
            }
            Date now = new Date();
            //获取当前用户状态变更的时间
            long userStateTime = Optional.ofNullable(user.getTime()).orElse(now.getTime());
            String userIdStr = user.getUserid();
            RBucket<Long> userStateTimeCache = redissonClient.getBucket(LIVE_TEACHER_LAST_TIME.replace(USER_ID, userIdStr));
            if (userStateTimeCache.isExists()) {
                //缓存的时间比当前传入时间大则放弃这条数据
                long cacheTime = userStateTimeCache.get();
                if (cacheTime > userStateTime) {
                    return;
                }
            }
            //将最新的时间写入缓存
            userStateTimeCache.set(userStateTime, 5L, TimeUnit.MINUTES);
            //直播间号
            String roomUid;
            //根据用户id获取用户当前房间号
            RBucket<String> roomUidCache = redissonClient.getBucket(LIVE_USER_ROOM.replace(USER_ID, userIdStr));
            if (!roomUidCache.isExists()) {
                return;
            }
            roomUid = roomUidCache.get();
            //根据房间号获取房间信息
            RBucket<RoomInfoCache> roomInfoCache = redissonClient.getBucket(LIVE_ROOM_INFO.replace(ROOM_UID, roomUid));
            if (!roomInfoCache.isExists()) {
                return;
            }
            RoomInfoCache roomInfo = roomInfoCache.get();
            //主讲人
            if (roomInfo.getSpeakerId().toString().equals(userIdStr)) {
                //主讲人进入房间
                if (user.getStatus().equals("0")) {
                    roomInfo.setSpeakerState(0);
                    roomInfo.setJoinRoomTime(now);
                    log.info("opsRoom>>>> join roomInfo {}", JSONObject.toJSONString(roomInfo));
                    roomInfoCache.set(roomInfo);
                    return;
                }
                roomInfo.setSpeakerState(1);
                roomInfo.setExitRoomTime(now);
                log.info("opsRoom>>>> exit roomInfo {}", JSONObject.toJSONString(roomInfo));
                roomInfoCache.set(roomInfo);
                return;
            }
            //观看者只接受退出消息 status=0 是进入房间
            if (user.getStatus().equals("0")) {
                return;
            }
            //观看者
            Long userId = Long.valueOf(userIdStr);
            //从房间累计用户信息中查询该用户的信息
            RMap<Long, RoomUserInfoCache> roomTotalUser = redissonClient.getMap(LIVE_ROOM_TOTAL_USER_LIST.replace(ROOM_UID, roomUid));
            //该房间未查询到用户数据则不处理
            if (!roomTotalUser.isExists() && !roomTotalUser.containsKey(userId)) {
                return;
            }
            //查询到用户数据
            RoomUserInfoCache userInfo = roomTotalUser.get(userId);
            //用户突然离线 - 那么融云会发送用户离线消息-此刻就发送退出房间消息给主讲人
            if (user.getStatus().equals("1")) {
                ImRoomMessage message = new ImRoomMessage();
                message.setFromUserId(userId.toString());
                message.setContent(userId.toString());
                message.setToChatroomId(roomUid);
                message.setObjectName(ImRoomMessage.RC_CHATROOM_LEAVE);
                try {
                    publishRoomMessage(message);
                } catch (Exception e) {
                    log.error("opsRoom>>>>  looker leave error {}", e.getMessage());
                    log.error("opsRoom>>>>  looker leave error sendMessage {} : userInfo : {}", message, JSONObject.toJSONString(userInfo));
                }
                log.info("opsRoom>>>> looker leave userInfo : {}", JSONObject.toJSONString(userInfo));
            }
            //记录退出时间 并写入缓存
            userInfo.setLastOutTime(now);
            userInfo.setState(1);
            roomTotalUser.fastPut(userId, userInfo);
            log.info("opsRoom>>>> looker userInfo: {}", JSONObject.toJSONString(userInfo));
        });

    }

    /**
     * 同步点赞数量
     *
     * @param roomUid 房间uid
     * @param likeNum 点赞数
     */
    @Override
    public void syncLike(String roomUid, Integer likeNum) {
        redissonClient.getBucket(LIVE_ROOM_LIKE.replace(ROOM_UID, roomUid)).set(likeNum);
    }

    /**
     * 进入房间
     *
     * @param roomUid 房间uid
     * @param userId  用户id 主讲人或者用户的id
     */
    public RoomInfoCache joinRoom(String roomUid, Long userId) {
        //校验房间是否存在
        RBucket<RoomInfoCache> roomInfoCache = redissonClient.getBucket(LIVE_ROOM_INFO.replace(ROOM_UID, roomUid));
        if (!roomInfoCache.isExists()) {
            throw new BizException("直播还未开始!");
        }
        RoomInfoCache roomInfo = roomInfoCache.get();
        roomInfo.setLikeNum(getLike(roomUid));
        roomInfo.setLookNum(getLooker(roomUid));

        //记录当前用户对应的房间uid
        redissonClient.getBucket(LIVE_USER_ROOM.replace(USER_ID, userId.toString())).set(roomUid, 2L, TimeUnit.DAYS);

        Date now = new Date();
        //进入房间的是主讲人
        if (roomInfo.getSpeakerId().equals(userId)) {
            roomInfo.setSpeakerState(0);
            roomInfo.setJoinRoomTime(now);
            roomInfoCache.set(roomInfo);
            return roomInfo;
        }

        //房间累计用户信息-指只要进入到该房间的用户都要记录
        RMap<Long, RoomUserInfoCache> roomTotalUser = redissonClient.getMap(LIVE_ROOM_TOTAL_USER_LIST.replace(ROOM_UID, roomUid));
        //判断是否第一次进房间
        RoomUserInfoCache userInfo;
        if (roomTotalUser.containsKey(userId)) {
            //多次进入更新动态进入时间
            userInfo = roomTotalUser.get(userId);
        } else {
            //第一次进该房间 写入用户首次进入时间
            SysUser sysUser = getSysUser(userId);
            userInfo = new RoomUserInfoCache();
            userInfo.setUserId(sysUser.getId());
            userInfo.setUserName(sysUser.getRealName());
            userInfo.setFirstJoinTime(now);
        }
        userInfo.setState(0);//0:在房间 1:不在房间
        userInfo.setDynamicJoinTime(now);
        roomTotalUser.fastPut(userId, userInfo);
        log.info("joinRoom>>>> userInfo: {}", JSONObject.toJSONString(userInfo));
        return roomInfo;
    }

    /**
     * 发送消息
     *
     * @param message
     */
    @Override
    public void publishRoomMessage(ImRoomMessage message) {
        String msgStr = JSONObject.toJSONString(message);
        log.info("publishRoomMessage message : {}", msgStr);
        IMApiResultInfo resultInfo;
        try {
            resultInfo = imHelper.publishRoomMessage(message.getFromUserId(), message.getToChatroomId(), message);
        } catch (Exception e) {
            throw new BizException("消息发送失败" + e.getMessage());
        }
        if (!resultInfo.isSuccess()) {
            throw new BizException("消息发送失败!" + resultInfo.getErrorMessage());
        }
        log.info("publishRoomMessage success: {}", msgStr);
    }

    private SysUser getSysUser(Long userId) {
        return Optional.ofNullable(userId)
                .map(sysUserFeignService::queryUserById)
                .orElseThrow(() -> new BizException("用户不存在"));
    }

    private SysUser getSysUser() {
        return Optional.ofNullable(sysUserFeignService.queryUserInfo())
                .orElseThrow(() -> new BizException("用户不存在"));
    }

    /**
     * 查询在观看直播的用户信息
     *
     * @param roomUid 直播间uid
     */
    @Override
    public List<RoomUserInfoCache> queryRoomUserInfo(String roomUid) {
        List<RoomUserInfoCache> roomUserInfoVos = queryTotalRoomUserInfo(roomUid);
        return queryRoomUserInfo(roomUserInfoVos);
    }

    private List<RoomUserInfoCache> queryRoomUserInfo(List<RoomUserInfoCache> totalUserInfo) {
        return totalUserInfo.stream()
                .filter(o -> Objects.nonNull(o.getState()) && o.getState() == 0)
                .collect(Collectors.toList());
    }

    private List<RoomUserInfoCache> queryTotalRoomUserInfo(String roomUid) {
        RMap<Long, RoomUserInfoCache> roomTotalUser = redissonClient.getMap(LIVE_ROOM_TOTAL_USER_LIST.replace(ROOM_UID, roomUid));
        return roomTotalUser.values().stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    /**
     * 获取房间点赞数
     *
     * @param roomUid 房间UId
     * @return 点赞数
     */
    private int getLike(String roomUid) {
        //点赞数
        Object like = redissonClient.getBucket(LIVE_ROOM_LIKE.replace(ROOM_UID, roomUid)).get();
        if (Objects.isNull(like)) {
            return 0;
        }
        return (int) like;
    }

    /**
     * 获取房间当前观看人数
     *
     * @param roomUid 房间uid
     * @return 当前观看人数
     */
    private int getLooker(String roomUid) {
        List<RoomUserInfoCache> roomUserInfoCaches = queryRoomUserInfo(roomUid);
        if (CollectionUtils.isEmpty(roomUserInfoCaches)) {
            return 0;
        }
        return roomUserInfoCaches.size();
    }

    /**
     * 方便测试观察房间数据的方法
     */
    public Map<String, Object> test(String roomUid) {
        //result
        Map<String, Object> result = new HashMap<>();
        //{"day":"01","month":"05","year":"2022","singleCourseMinutes":60,"teacherId":4}
//        Map<String, Object> param = new HashMap<>();
//        param.put("day", "01");
//        param.put("month", "04");
//        param.put("year", "2022");
//        param.put("singleCourseMinutes", 60);
//        param.put("teacherId", "4");
//        param.put("studentId", 143);
//        List<CourseCalendarEntity> courseTimeEntities = courseScheduleService.createPracticeCourseCalender(param);
//        List<CourseCalendarEntity> courseTimeEntities = courseScheduleService.createLiveCourseCalendar(param);
//        result.put("自动生成课时", courseTimeEntities);

        //获取房间信息
        RBucket<RoomInfoCache> speakerCache = redissonClient.getBucket(LIVE_ROOM_INFO.replace(ROOM_UID, roomUid));
        if (speakerCache.isExists()) {
            result.put("房间信息信息", speakerCache.get());
        } else {
            result.put("房间信息", "房间信息不存在");
        }

        //点赞数
        Object like = redissonClient.getBucket(LIVE_ROOM_LIKE.replace(ROOM_UID, roomUid)).get();
        if (Objects.isNull(like)) {
            like = 0;
        }
        result.put("点赞数", like);

        int totalLook = 0;
        int look = 0;
        List<RoomUserInfoCache> inRoomUserInfo;

        //累计总观看的用户数量
        List<RoomUserInfoCache> totalUserInfo = queryTotalRoomUserInfo(roomUid);
        if (CollectionUtils.isNotEmpty(totalUserInfo)) {
            //正在房间观看的用户数据
            inRoomUserInfo = queryRoomUserInfo(totalUserInfo);
            if (CollectionUtils.isNotEmpty(inRoomUserInfo)) {
                look = inRoomUserInfo.size();
                result.put("正在观看的人员信息", inRoomUserInfo);
            } else {
                result.put("正在观看的人员信息", "没有正在观看的人员数据");
            }
            totalLook = totalUserInfo.size();
            result.put("总人员数据", totalUserInfo);
        } else {
            result.put("总人员数据", "没有人员数据");
        }

        result.put("总观看人数", totalLook);
        result.put("实时观看数", look);
        return result;
    }

    @Override
    public LiveRoom getliveingRoomBySpeakerId(Long speakerId) {
        return baseMapper.getliveingRoomBySpeakerId(speakerId);
    }
}

