package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.mapper.SysRoleMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @Author scott
 * @since 2018-12-19
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysUserMapper sysUserMapper;


    @Override
    public Page<SysRole> listAllSysRole(Page<SysRole> page, SysRole role) {
        return page.setRecords(sysRoleMapper.listAllSysRole(page, role));
    }

    @Override
    public SysRole getByRoleCode(String roleCode) {
        return sysRoleMapper.getByRoleCode(roleCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(String roleid) {
        // 1.删除角色和用户关系
        sysRoleMapper.deleteRoleUserRelation(roleid);
        // 2.删除角色和权限关系
        sysRoleMapper.deleteRolePermissionRelation(roleid);
        // 3.删除角色
        this.removeById(roleid);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchRole(String[] roleIds) {
        // 1.删除角色和用户关系
        sysUserMapper.deleteBathRoleUserRelation(roleIds);
        // 2.删除角色和权限关系
        sysUserMapper.deleteBathRolePermissionRelation(roleIds);
        // 3.删除角色
        this.removeByIds(Arrays.asList(roleIds));
        return true;
    }

    @Override
    public void checkAdminRoleRejectDel(String ids) {
        LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<>();
        query.in(SysRole::getId, Arrays.asList(ids.split(SymbolConstant.COMMA)));
        query.eq(SysRole::getRoleCode, "admin");
        Long adminRoleCount = sysRoleMapper.selectCount(query);
        if (adminRoleCount > 0) {
            throw new JeecgBootException("admin角色，不允许删除！");
        }
    }
}
