package cn.reghao.autodop.dmaster.rbac.db.query;

import cn.reghao.autodop.dmaster.rbac.db.repository.RoleRepository;
import cn.reghao.autodop.dmaster.rbac.db.repository.UserRepository;
import cn.reghao.autodop.dmaster.rbac.model.po.Role;
import cn.reghao.autodop.dmaster.rbac.model.po.User;
import cn.reghao.autodop.dmaster.rbac.model.po.UserAuthority;
import cn.reghao.autodop.dmaster.rbac.model.vo.UserVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2021-07-12 15:32:26
 */
@Service
public class UserQueryImpl implements UserQuery {
    private final UserRepository userRepository;
    private final RoleRepository roleRepository;

    public UserQueryImpl(UserRepository userRepository, RoleRepository roleRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
    }

    @Override
    public User findById(int id) {
        return userRepository.getOne(id);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public Page<UserVO> getUserVOByPage(PageRequest pageRequest) {
        return userRepository.findAll(pageRequest).map(UserVO::new);
    }

    @Override
    public List<UserVO> getByMatchNickname(String nickname) {
        Specification<User> specification = (root, query, cb) -> {
            String likeQuery = String.format("%%%s%%", nickname);
            Predicate predicate = cb.like(root.get("nickname"), likeQuery);
            return cb.and(predicate);
        };
        return userRepository.findAll(specification).stream().map(UserVO::new).collect(Collectors.toList());
    }

    /**
     * 获取用户拥有的角色
     *
     * @param
     * @return
     * @date 2021-09-10 下午11:12
     */
    @Override
    public Set<Role> getUserRoles(User user) {
        Set<UserAuthority> set = user.getAuthoritiesSet();
        List<String> roles = set.stream()
                .map(UserAuthority::getAuthority)
                .collect(Collectors.toList());
        Specification<Role> spec = ((root, query, criteriaBuilder) -> root.get("title").in(roles));
        return new HashSet<>(roleRepository.findAll(spec));
    }

    @Override
    public Set<Role> getUserRoles(Integer userId) {
        User user = findById(userId);
        if (user == null) {
            return Collections.emptySet();
        }

        return getUserRoles(user);
    }
}
