package com.springboot.auth.authorization.oauth2;

import com.springboot.auth.authorization.entity.Company;
import com.springboot.auth.authorization.entity.User;
import com.springboot.auth.authorization.oauth2.authority.CustomGrantedAuthority;
import com.springboot.auth.authorization.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String payload) {

        User user = userService.getUserByUsernameOrMobile(payload);
        log.info("load user by username :{}", user.toString());

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(), //加了密的密码
                user.getState() == 1, //账号是否可用
                user.getState() == 1, //账号未过期
                true, //密码未过期
                user.getState() == 1, //账户未锁定
                this.obtainGrantedCompany(user));
    }

    /**
     * 获得登录者所有的公司信息
     *
     * @return
     */
    protected Set<CustomGrantedAuthority> obtainGrantedCompany(User user) {
        List<Company> companies = userService.getUserAllCompany(user.getId());
        return companies.stream().map(companyUser -> new CustomGrantedAuthority(companyUser.getCompanyId(), companyUser.getIsDefault() == 1)).collect(Collectors.toSet());
    }
}
