package com.jeeplus.common;

import com.jeeplus.common.constant.CommonConstants;
import com.jeeplus.common.constant.ErrorConstants;
import com.jeeplus.sys.feign.ITenantApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private IUserApi userApi;
    @Autowired
    private ITenantApi tenantApi;

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        String tenantId = tenantApi.getCurrentTenantId ( );

        // 通过用户名从数据库获取用户信息
        UserDTO userDTO = userApi.getByLoginName ( username, tenantId );

        // 用户不存在
        if ( userDTO == null ) {
            throw new AccountExpiredException ( ErrorConstants.LOGIN_ERROR_NOTFOUND );
        }

        // 用户禁止登录
        if ( CommonConstants.NO.equals ( userDTO.getLoginFlag ( ) ) ) {
            throw new AccountExpiredException ( ErrorConstants.LOGIN_ERROR_FORBIDDEN );
        }

        // 权限集合
        List <GrantedAuthority> authorities = new ArrayList <> ( );

        return new User (
                userDTO.getLoginName ( ),
                userDTO.getPassword ( ),
                authorities
        );
    }
}



