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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.ImNetworkRoomMemberDao;
import com.yonge.cooleshow.biz.dal.dto.BasicUserInfo;
import com.yonge.cooleshow.biz.dal.entity.ImNetworkRoomMember;
import com.yonge.cooleshow.biz.dal.enums.RoleEnum;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.ImNetworkRoomMemberService;
import com.yonge.cooleshow.biz.dal.service.ImNetworkRoomMemberStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * 网络教室成员(ImNetworkRoomMember)表服务实现类
 *
 * @author zx
 * @since 2022-03-30 16:36:38
 */
@Service("imNetworkRoomMemberService")
public class ImNetworkRoomMemberServiceImpl extends ServiceImpl<ImNetworkRoomMemberDao, ImNetworkRoomMember> implements ImNetworkRoomMemberService {

    private final static Logger log = LoggerFactory.getLogger(ImNetworkRoomMemberServiceImpl.class);

    @Autowired
    private ImGroupService imGroupService;

    @Autowired
    private ImNetworkRoomMemberStatusService imNetworkRoomMemberStatusService;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ImNetworkRoomMember initRoomMember(String roomId, BasicUserInfo sysUser, RoleEnum userRole,Boolean microphone) {
        sysUser.setImUserId(imGroupService.getImUserId(sysUser.getUserId(),userRole));
        ImNetworkRoomMember roomMember = this.lambdaQuery().eq(ImNetworkRoomMember::getRoomId,roomId)
                .eq(ImNetworkRoomMember::getUserId,sysUser.getImUserId())
                .eq(ImNetworkRoomMember::getRole,userRole.getValue()).last("LIMIT 1").one();
        if(Objects.isNull(roomMember)){
            roomMember = new ImNetworkRoomMember();
            roomMember.setRoomId(roomId);
            roomMember.setCameraFlag(true);
            roomMember.setHandFlag(false);
            roomMember.setMicFlag(microphone);
            roomMember.setMusicModeFlag(false);
            roomMember.setRole(userRole.getValue());
            roomMember.setUserName(sysUser.getUsername());
            roomMember.setAvatar(sysUser.getAvatar());
            roomMember.setUserId(sysUser.getImUserId());
            roomMember.setJoinTime(new Date());
            baseMapper.insert(roomMember);
            //生成用户房间状态表
            imNetworkRoomMemberStatusService.add(roomId);
        }
        return roomMember;
    }
}

