package cn.com.capcloud.core.system.security;

import cn.com.capcloud.core.system.role.RoleService;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MyUserDetails implements UserDetailsService {

  @Autowired
  private UserService userService;
  @Autowired
  private RoleService roleService;
  private Map<String,UserInfo> userInfoMap=new HashMap<>();//todo 如果负载了，应该放redis

  public Map<String,UserInfo> getUserInfoMap(){
    return userInfoMap;
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserInfo userInfo=userInfoMap.get(username);
    if(userInfo!=null){
      return userInfo;
    }
    User user= userService.findByUserLoginName(username);
    if (user == null) {
      throw new UsernameNotFoundException("User '" + username + "' not found");
    }
    List<SimpleGrantedAuthority> authorities = null;
    List<Map<String,Object>> listRolesMap=roleService.getRolesIdByLoginUserName(username);
    authorities=listRolesMap.stream().map(s ->new SimpleGrantedAuthority("ROLE_"+s.get("role_id"))).filter(Objects::nonNull).collect(Collectors.toList());
    String userSystemRole="一般用户";
    userInfo = new UserInfo(user.getUserLoginName(),user.getUserPassword().replace("{bcrypt}",""), authorities,user.getId(),user.getUserName(),userSystemRole,user.getOrgId(),user.getOrgName(), user.getIsConfirm());
    userInfoMap.put(username,userInfo);
    return userInfo;
  }

}
