package com.zsc.bill.framework.security;

import com.zsc.bill.exception.StateException;
import com.zsc.bill.modules.system.entity.Authority;
import com.zsc.bill.modules.system.entity.RoleAuthority;
import com.zsc.bill.modules.system.entity.User;
import com.zsc.bill.modules.system.repo.AuthorityRepository;
import com.zsc.bill.modules.system.repo.RoleAuthoritiesRepository;
import com.zsc.bill.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author harry_yao
 */
@AllArgsConstructor
@Service
public class JpaUserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepo;
    private  final AuthorityRepository authorityRepo;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepo.selectByUsername(username);
        if (!user.getEnabled()) {
            throw new StateException("用户 '" + username + "' 已被禁用！请联系管理员");
        }

        user.role.authorities=authorityRepo.selectAuthoritiesByRoleId(user.getRoleId());


//        List<GrantedAuthority> authorities = new ArrayList<>();
//        authorities=authorityList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
//        return authorities;


//                .orElseThrow(() ->
//            new UsernameNotFoundException("用户 '" + username + "' 不存在!")
//        );
//        user.getIdentities().stream().filter(identity -> identity.role.enableState == EnableState.启用)
//            .forEach(identity -> Hibernate.initialize(identity.role.roleAuthorities));
        return UserDetailsImpl.from(user);
    }
}
