package com.starry.admin.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starry.admin.modules.system.mapper.SysUserRoleMapper;
import com.starry.admin.modules.system.module.entity.SysUserRoleEntity;
import com.starry.admin.modules.system.service.SysUserRoleService;
import com.starry.admin.modules.system.service.SysUserService;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-07-08
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRoleEntity>
        implements
            SysUserRoleService {

    @Resource
    private SysUserService userService;

    @Override
    public void delUserRole(String userId, Long roleId) {
        LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRoleEntity::getUserId, userId);
        queryWrapper.eq(SysUserRoleEntity::getRoleId, roleId);
        this.remove(queryWrapper);
        // 强制退出指定用户
        userService.logoutUser(userId);
    }

    @Override
    public void addUserRole(String userId, Long roleId) {
        LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRoleEntity::getUserId, userId);
        queryWrapper.eq(SysUserRoleEntity::getRoleId, roleId);
        SysUserRoleEntity userRole = this.baseMapper.selectOne(queryWrapper);
        if (userRole == null) {
            userRole = new SysUserRoleEntity();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            this.baseMapper.insert(userRole);
        } else {
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            this.baseMapper.updateById(userRole);
        }
    }
}
