package com.gci.boot.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gci.boot.modules.system.entity.SysRole;
import com.gci.boot.modules.system.entity.SysRolePermission;
import com.gci.boot.modules.system.entity.SysUserRole;
import com.gci.boot.modules.system.mapper.SysRoleMapper;
import com.gci.boot.modules.system.service.ISysRolePermissionService;
import com.gci.boot.modules.system.service.ISysRoleService;
import com.gci.boot.modules.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author chenzhiwei
 * @since 2023-08-18
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(String roleid) {
        //1.删除角色和用户关系
        sysUserRoleService.lambdaUpdate().eq(SysUserRole::getRoleId, roleid).remove();
        //2.删除角色和权限关系
        sysRolePermissionService.lambdaUpdate().eq(SysRolePermission::getRoleId, roleid).remove();
        //3.删除角色
        this.removeById(roleid);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchRole(String[] roleIds) {
        //1.删除角色和用户关系
        sysUserRoleService.lambdaUpdate().in(SysUserRole::getRoleId, roleIds).remove();
        //2.删除角色和权限关系
        sysRolePermissionService.lambdaUpdate().in(SysRolePermission::getRoleId, roleIds).remove();
        //3.删除角色
        this.removeByIds(Arrays.asList(roleIds));
        return true;
    }

    @Override
    public Set<String> getRoleCodeSetByUserId(String userId){
        return baseMapper.getRoleCodeSetByUserId(userId);
    }

    @Override
    public List<SysRole> getRoleByUserId(String userId) {
        return baseMapper.getRoleByUserId(userId);
    }
}
