package com.njcn.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njcn.user.mapper.UserRoleMapper;
import com.njcn.user.pojo.po.Role;
import com.njcn.user.pojo.po.UserRole;
import com.njcn.user.service.IUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2021-12-13
 */
@Service
@AllArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    private final UserRoleMapper userRoleMapper;

    @Override
    public List<UserRole> getUserRoleByUserId(String id) {
        return this.lambdaQuery().eq(UserRole::getUserId, id).list();
    }

    @Override
    public boolean addUserRole(String id, List<String> roles) {
        boolean result = false;
        if (!CollectionUtil.isEmpty(roles)){
            UserRole userRole = new UserRole();
            userRole.setUserId(id);
            roles.forEach(pojo->{
                userRole.setRoleId(pojo);
                this.save(userRole);
            });
            result = true;
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean updateUserRole(String id, List<String> roles) {
        //删除原有关系
        List<String> userRoleList= this.lambdaQuery().eq(UserRole::getUserId, id).list().stream().map(UserRole::getRoleId).collect(Collectors.toList());
        LambdaQueryWrapper<UserRole> lambdaQuery = Wrappers.lambdaQuery();
        if (!CollectionUtils.isEmpty(userRoleList)){
            lambdaQuery.eq(UserRole::getUserId, id).in(UserRole::getRoleId,userRoleList);
            userRoleMapper.delete(lambdaQuery);
        }
        //新增关系
        roles.forEach(role->{
            UserRole userRole = new UserRole();
            userRole.setUserId(id);
            userRole.setRoleId(role);
            this.save(userRole);
        });
        return true;
    }

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