package com.jy.system.service.impl;

import com.jy.system.dao.SysUserRoleDao;
import com.jy.system.model.dto.AuthUserDto;
import com.jy.system.model.entity.SysUserRole;
import com.jy.system.service.SysUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 用户角色关联 服务实现类
 * </p>
 *
 * @author
 * @since 2024-06-20
 */
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Long userId, List<Long> roleIdList) {
        List<SysUserRole> list = roleIdList.stream()
                .map(roleId -> new SysUserRole(userId, roleId))
                .collect(Collectors.toList());

        sysUserRoleDao.saveBatch(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(Long userId, List<Long> roleIdList) {
        sysUserRoleDao.removeByUserId(userId);
        add(userId, roleIdList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void authUser(AuthUserDto dto) {
        List<SysUserRole> SysUserRoleList = dto.getUserIdList().stream()
                .map(userId -> new SysUserRole(userId, dto.getRoleId()))
                .collect(Collectors.toList());

        sysUserRoleDao.saveBatch(SysUserRoleList);
    }

    @Override
    public void unAuthUser(AuthUserDto dto) {
        sysUserRoleDao.removeByRoleIdAndUserIds(dto.getRoleId(), dto.getUserIdList());
    }

}
