package com.chushang.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chushang.system.entity.po.SysUserRole;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author author
 * @since 2022-08-18
 */
public interface ISysUserRoleService extends IService<SysUserRole> {

    @Transactional
    default void saveOrUpdate(Long userId, Long[] roleIdList){
        //先删除用户与角色关系
        this.remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
        if(roleIdList == null || roleIdList.length == 0){
            return ;
        }
        this.saveBatch(Arrays.stream(roleIdList).map(s -> {
            SysUserRole sysUserRoleEntity = new SysUserRole();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(s);
            return sysUserRoleEntity;
        }).collect(Collectors.toList()));
    }
    @Transactional
    default void saveOrUpdate(Long[] userIdList, Long roleId){
        //先删除用户与角色关系
        this.remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId));
        if(userIdList == null || userIdList.length == 0){
            return ;
        }
        this.saveBatch(Arrays.stream(userIdList).map(userId -> {
            SysUserRole sysUserRoleEntity = new SysUserRole();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);
            return sysUserRoleEntity;
        }).collect(Collectors.toList()));
    }

    default void deleteUserRoleByUserId(Integer userId){
        remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
    }

    default long countUserRoleByRoleId(Long roleId){
        return count(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId));
    }

    default void removeByUserIdAndRoleId(Collection<Integer> userIds, Integer roleId){
        remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId)
                .in(SysUserRole::getUserId, userIds));
    }
}
