package com.seer.teach.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.user.entity.AuthorityEntity;
import com.seer.teach.user.entity.RoleAuthorityEntity;
import com.seer.teach.user.entity.UserRoleEntity;
import com.seer.teach.user.mapper.AuthorityMapper;
import com.seer.teach.user.service.IAuthorityService;
import com.seer.teach.user.service.IRoleAuthorityService;
import com.seer.teach.user.service.IRoleService;
import com.seer.teach.user.service.IUserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class IAuthorityServiceImpl extends ServiceImpl<AuthorityMapper, AuthorityEntity> implements IAuthorityService {

    private final IUserRoleService userRoleService;

    private final IRoleAuthorityService roleAuthorityService;

    private final IRoleService roleService;

    @Override
    public List<AuthorityEntity> getPermissionsByUserId(Integer userId) {

        List<UserRoleEntity> data = userRoleService.list(new LambdaQueryWrapper<UserRoleEntity>().eq(UserRoleEntity::getUserId, userId));
        Set<Integer> roleIds = data.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toSet());
        if(CollectionUtil.isEmpty(roleIds)){
            return Collections.emptyList();
        }

        List<RoleAuthorityEntity> roleAuthorityEntities = roleAuthorityService.list(new LambdaQueryWrapper<>(RoleAuthorityEntity.class).in(RoleAuthorityEntity::getRoleId, roleIds));
        if(CollectionUtil.isEmpty(roleAuthorityEntities)){
            return Collections.emptyList();
        }
        Set<Integer> authorityIds = roleAuthorityEntities.stream().map(RoleAuthorityEntity::getAuthorityId).collect(Collectors.toSet());
        List<AuthorityEntity> authorityEntities = list(new LambdaQueryWrapper<>(AuthorityEntity.class).in(AuthorityEntity::getId, authorityIds));
        if(CollectionUtils.isEmpty(authorityEntities)){
            return Collections.emptyList();
        }
        return authorityEntities;
    }

    @Override
    public List<AuthorityEntity> getListByIdsAndModule(Collection<Integer> ids, String module) {
        if(CollectionUtil.isEmpty(ids)){
            return Collections.emptyList();
        }
        return super.list(new LambdaQueryWrapper<>(AuthorityEntity.class).in(AuthorityEntity::getId, ids).eq(AuthorityEntity::getModule, module));
    }


}