package com.ssyf.module.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ssyf.module.auth.domain.entity.UserRoleRelation;
import com.ssyf.module.auth.mapper.UserRoleRelationMapper;
import com.ssyf.module.auth.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author auth
 * @since 2023-01-12
 */
@Service
public class UserRoleRelationServiceImpl extends ServiceImpl<UserRoleRelationMapper, UserRoleRelation> implements UserRoleRelationService {

    @Override
    public List<UserRoleRelation> getListByUserUids(List<String> userUids) {
        return this.list(new LambdaQueryWrapper<UserRoleRelation>().in(CollectionUtil.isNotEmpty(userUids) ,UserRoleRelation::getUserUid, userUids));
    }

    @Override
    public void removeByRoleUid(String roleUid) {
        this.remove(new LambdaQueryWrapper<UserRoleRelation>().eq(UserRoleRelation::getRoleUid, roleUid));
    }

    @Override
    public void removeByRoleUids(List<String> roleUids) {
        this.remove(new LambdaQueryWrapper<UserRoleRelation>().in(UserRoleRelation::getRoleUid ,roleUids));
    }

    @Override
    public void removeByUserUid(String userUid) {
        this.remove(new LambdaQueryWrapper<UserRoleRelation>().eq(UserRoleRelation::getUserUid, userUid));
    }

    @Override
    public void removeByUserUids(List<String> userUids) {
        this.remove(new LambdaQueryWrapper<UserRoleRelation>().in(UserRoleRelation::getUserUid ,userUids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignAndRemoveOld(String userUid, List<String> roleUids) {
        this.removeByUserUid(userUid);

        //重建关联
        if(CollectionUtil.isEmpty(roleUids)){
            return;
        }
        List<UserRoleRelation> relationList = new ArrayList<>();
        roleUids.forEach(roleUid->{
            UserRoleRelation relation = new UserRoleRelation();
            relation.setRoleUid(roleUid).setUserUid(userUid);
            relationList.add(relation);
        });
        //优化
        this.saveBatch(relationList);
    }

    @Override
    public List<UserRoleRelation> getListByRoleUid(String roleUid) {
        return this.list(new LambdaQueryWrapper<UserRoleRelation>().eq(UserRoleRelation::getRoleUid ,roleUid));
    }

}
