package cc.mrbird.febs.auth.configure;

import cc.mrbird.febs.auth.service.impl.SysPasswordService;
import cc.mrbird.febs.auth.service.impl.SysRecordLogService;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.Oauth2LoginUser;
import com.ruoyi.common.core.enums.UserType;
import com.ruoyi.common.core.exception.BusinessException;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

/**
 * 使用统一认证后自定义oauth2认证逻辑：通过电话查找系统用户信息，直接将用户的密码交给oauth2完成认证
 */
@Component
@RequiredArgsConstructor
public class TargetAuthenticationProvider implements AuthenticationProvider {

    @Value("${unifiedAuth:false}")
    private boolean unifiedAuth;

    private final UserDetailsService userDetailsService;
    private final PasswordEncoder passwordEncoder;
    private final SysPasswordService passwordService;
    private final SysRecordLogService recordLogService;

    //认证方法
    @Override
    public Authentication authenticate(Authentication authentication)  {
        String presentedPassword = (String)authentication.getCredentials();
        String username = authentication.getName();
        UsernamePasswordAuthenticationToken loginToken = (UsernamePasswordAuthenticationToken) authentication;

        UserDetails userDetails = userDetailsService.loadUserByUsername(loginToken.getName());
        if (!userDetails.isAccountNonLocked()) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户已锁定");
            throw new InvalidGrantException("locked");
        }
        // 非统一认证时，用户名、输的密码和数据库校验
        else if (!unifiedAuth) {
            passwordService.validate(passwordEncoder, username, presentedPassword, userDetails.getPassword());
        }
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
    }

    private String translateUserType(String type) {
        return "当前登录账号没有权限登录" + UserType.getDesc(type);
    }

    //判断是否支持当前Token，从而决定是否需要进行认证校验
    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
