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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
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 com.starry.admin.common.exception.ServiceException;
import com.starry.admin.modules.system.mapper.SysRoleDeptMapper;
import com.starry.admin.modules.system.mapper.SysRoleMapper;
import com.starry.admin.modules.system.mapper.SysRoleMenuMapper;
import com.starry.admin.modules.system.mapper.SysUserRoleMapper;
import com.starry.admin.modules.system.module.entity.*;
import com.starry.admin.modules.system.service.SysRoleMenuService;
import com.starry.admin.modules.system.service.SysRoleService;
import com.starry.admin.modules.system.service.SysUserRoleService;
import com.starry.admin.modules.system.service.SysUserService;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.constant.UserConstants;
import com.starry.common.utils.StringUtils;
import java.util.*;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-07-01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleEntity> implements SysRoleService {

    @Resource
    private SysRoleMenuService roleMenuService;
    @Resource
    private SysRoleDeptMapper roleDeptMapper;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private SysUserRoleService userRoleService;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysUserService userService;

    @Override
    public SysRoleEntity selectByRoleId(String roleId) {
        LambdaQueryWrapper<SysRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleEntity::getRoleId, roleId);
        return this.baseMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public SysRoleEntity selectByRoleKey(String roleKey) {
        LambdaQueryWrapper<SysRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleEntity::getRoleKey, roleKey);
        return this.baseMapper.selectOne(lambdaQueryWrapper);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role
     *            角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(SysRoleEntity role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRoleEntity info = baseMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role
     *            角色信息
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(SysRoleEntity role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRoleEntity info = baseMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(SysRoleEntity role) {
        // 先新增角色
        save(role);
        return insertRoleMenu(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(SysRoleEntity role) {
        // 先修改角色
        updateById(role);
        // 再删除角色菜单信息
        roleMenuService
                .remove(new LambdaQueryWrapper<SysRoleMenuEntity>().eq(SysRoleMenuEntity::getRoleId, role.getRoleId()));
        // 再新增
        return insertRoleMenu(role);
    }

    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return baseMapper.countUserRoleByRoleId(roleId);
    }

    @Override
    public boolean delete(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRoleEntity(roleId));
            checkRoleDataScope(roleId);
            SysRoleEntity role = getById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDept(roleIds);
        return removeByIds(Arrays.asList(roleIds));
    }

    @Override
    public Page<SysRoleEntity> list(String keyword, Integer pageSize, Integer pageNum) {
        Page<SysRoleEntity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysRoleEntity> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            wrapper.like(SysRoleEntity::getRoleName, keyword);
        }
        return page(page, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean authRoleMenu(SysRoleEntity role) {
        // 先删除
        roleMenuService
                .remove(new LambdaQueryWrapper<SysRoleMenuEntity>().eq(SysRoleMenuEntity::getRoleId, role.getRoleId()));
        // 在新增
        return insertRoleMenu(role);
    }

    @Override
    public Set<String> selectRolePermissionByUserId(String userId) {
        List<SysRoleEntity> list = baseMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (SysRoleEntity role : list) {
                permsSet.addAll(Arrays.asList(role.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysRoleEntity> selectRoleList(SysRoleEntity role) {
        return baseMapper.selectRoleList(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role
     *            角色对象
     */
    public boolean insertRoleMenu(SysRoleEntity role) {
        // 新增角色与菜单管理
        List<SysRoleMenuEntity> list = new ArrayList<>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenuEntity rm = new SysRoleMenuEntity();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (!list.isEmpty()) {
            return roleMenuService.saveBatch(list);
        }
        return true;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role
     *            角色信息
     */
    @Override
    public void checkRoleAllowed(SysRoleEntity role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleId
     *            角色id
     */
    @Override
    public void checkRoleDataScope(Long roleId) {
        if (!SysUserEntity.isAdmin(userService.selectUserById(SecurityUtils.getUserId()))) {
            SysRoleEntity role = new SysRoleEntity();
            role.setRoleId(roleId);
            List<SysRoleEntity> roles = this.selectRoleList(role);
            if (CollectionUtil.isEmpty(roles)) {
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    /**
     * 修改数据权限信息
     *
     * @param role
     *            角色信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int authDataScope(SysRoleEntity role) {
        // 修改角色信息
        this.updateById(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role
     *            角色对象
     */
    public int insertRoleDept(SysRoleEntity role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDeptEntity> list = new ArrayList<>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDeptEntity rd = new SysRoleDeptEntity();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (!list.isEmpty()) {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole
     *            用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRoleEntity userRole) {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId
     *            角色ID
     * @param userIds
     *            需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, String[] userIds) {
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId
     *            角色ID
     * @param userIds
     *            需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, String[] userIds) {
        // 新增用户与角色管理
        List<SysUserRoleEntity> list = new ArrayList<>();
        for (String userId : userIds) {
            SysUserRoleEntity ur = new SysUserRoleEntity();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleService.saveBatch(list) ? 1 : 0;
    }
}
