package com.changfa.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changfa.enums.StatusEnum;
import com.changfa.entity.TRole;
import com.changfa.exception.BuzEx;
import com.changfa.mapper.TRoleMapper;
import com.changfa.mapper.TRoleMenuMapper;
import com.changfa.mapper.TUserRoleMapper;
import com.changfa.service.ITRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wwz
 * @since 2022-06-24
 */
@Service
public class TRoleServiceImpl extends ServiceImpl<TRoleMapper, TRole> implements ITRoleService {

    @Autowired
    private TRoleMenuMapper roleMenuMapper;
    @Autowired
    private TUserRoleMapper userRoleMapper;
    @Override
    public TRole selectRoleByUserId(Integer userId) {
        return this.baseMapper.selectRoleByUserId(userId);
    }

    @Override
    @Transactional
    public boolean deleteRoleById(Integer roleId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id",roleId);
        // 查询如果角色被分配。抛出提示
        if(userRoleMapper.selectCount(queryWrapper) > 0){
            throw new BuzEx(StatusEnum.ROLE_NOT_FREE);
        }
        // 删除角色
        if(this.baseMapper.deleteById(roleId) > 0){
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("role_id",roleId);
            // 删除角色菜单信息
            roleMenuMapper.delete(queryWrapper);
            return true;
        };
        return false;
    }

    @Override
    public Page<Map<String,Object>> listPage(Wrapper wrapper, Page page) {
        page.setRecords(this.baseMapper.selectRoleList(wrapper,page));
        return page;
    }
}
