package com.njzscloud.dispose.sys.user.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.dispose.sys.role.pojo.entity.RoleEntity;
import com.njzscloud.dispose.sys.role.pojo.result.RoleDetailResult;
import com.njzscloud.dispose.sys.role.service.RoleService;
import com.njzscloud.dispose.sys.user.mapper.SysUserRoleMapper;
import com.njzscloud.dispose.sys.user.pojo.entity.SysUserRoleEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>用户-角色关系表</p>
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserRoleService extends ServiceImpl<SysUserRoleMapper, SysUserRoleEntity> implements IService<SysUserRoleEntity> {
    private final RoleService roleService;

    /**
     * 删除用户角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void delByUserIds(List<Long> userIdList) {
        this.remove(Wrappers.<SysUserRoleEntity>lambdaQuery().in(SysUserRoleEntity::getUserId, userIdList));
    }

    /**
     * 获取用户拥有的角色
     */
    public List<RoleDetailResult> listRole(Long userId) {
        return baseMapper.listRole(Wrappers.<SysUserRoleEntity>query().eq("a.user_id", userId));
    }

    /**
     * 绑定用户角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void bindUserRole(Long userId, Set<Long> roleIds) {
        if (CollUtil.isEmpty(roleIds)) return;

        List<RoleEntity> sysRoleEntities = roleService.listByIds(roleIds);
        Assert.isTrue(sysRoleEntities.size() == roleIds.size(), () -> Exceptions.exception("角色不存在"));

        this.remove(Wrappers.<SysUserRoleEntity>lambdaQuery().eq(SysUserRoleEntity::getUserId, userId));

        this.saveBatch(roleIds.stream().map(roleId -> new SysUserRoleEntity().setRoleId(roleId).setUserId(userId)).collect(Collectors.toList()));
    }

}
