package com.jeeplus.gateway.service;

import com.google.common.collect.Lists;
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.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import reactor.core.publisher.Mono;

import java.util.Collection;

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

    @Override
    public Mono <UserDetails> findByUsername(String username) {
        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 );
        }


        UserDetails result = new UserDetails ( ) {
            @Override
            public Collection <? extends GrantedAuthority> getAuthorities() {
                return Lists.newArrayList ( );
            }

            @Override
            public String getPassword() {
                return userDTO.getPassword ( );
            }

            @Override
            public String getUsername() {
                return userDTO.getLoginName ( );
            }

            @Override
            public boolean isAccountNonExpired() {
                return false;
            }

            @Override
            public boolean isAccountNonLocked() {
                return false;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return false;
            }

            @Override
            public boolean isEnabled() {
                return false;
            }
        };
        return Mono.just ( User.withUserDetails ( result ).build ( ) );
    }

}

