package com.njcn.gather.user.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.user.user.mapper.SysUserRoleMapper;
import com.njcn.gather.user.user.pojo.po.SysRole;
import com.njcn.gather.user.user.pojo.po.SysUserRole;
import com.njcn.gather.user.user.service.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author caozehui
 * @date 2024-11-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Override
    public List<SysRole> listRoleByUserId(String userId) {
        return this.baseMapper.getRoleListByUserId(userId);
    }

    @Override
    @Transactional
    public boolean addUserRole(String userId, List<String> roleIds) {
        List<SysUserRole> userRoles = new ArrayList<>();
        if (!CollectionUtil.isEmpty(roleIds)) {
            roleIds.forEach(id -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(id);
                userRoles.add(userRole);
            });
        }
        return this.saveBatch(userRoles);
    }

    @Override
    @Transactional
    public boolean updateUserRole(String userId, List<String> roleIds) {
        //删除原有关系
        this.deleteUserRoleByUserIds(Collections.singletonList(userId));
        //新增关系
        List<SysUserRole> userROles = new ArrayList<>();
        roleIds.forEach(role -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(role);
            userROles.add(userRole);
        });
        return this.saveBatch(userROles);
    }

    @Override
    @Transactional
    public boolean deleteUserRoleByUserIds(List<String> userIds) {
        LambdaQueryWrapper<SysUserRole> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.in(SysUserRole::getUserId, userIds);
        return this.remove(lambdaQuery);
    }

    @Override
    @Transactional
    public boolean deleteUserRoleByRoleIds(List<String> roleIds) {
        LambdaQueryWrapper<SysUserRole> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.in(SysUserRole::getRoleId, roleIds);
        return this.remove(lambdaQuery);
    }
}
