package fastweb.provider;

import com.google.common.collect.Lists;
import fastweb.domain.usertype.User;
import fastweb.respository.userType.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;
/**
 * 用于处理认证实体
 *
 * @author Gerry
 */
@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserRepository sysUserRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 身份认证
     *
     * @param authentication 认证实体
     * @return Authentication 认证成功会走JwtLoginFilter中的successfulAuthentication方法返回JWT
     * @throws AuthenticationException 认证异常（JwtLoginFilter中的unsuccessfulAuthentication方法会处理）.
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.getPrincipal() == null || authentication.getCredentials() == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        // 获取认证的用户名 & 密码
        String username = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();
        if("admin".equals(username) && ("admin").equals(password)){
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin","password" , Lists.newArrayList());
            token.setDetails(new User("1","admin","admin","1",1));
            return token;
        }else {
            User sysUser = sysUserRepository.findDistinctByAccount(username);

            if (sysUser != null) {
                // 密码不匹配直接抛出异常
                if (!passwordEncoder.matches(password, sysUser.getPassword())) {
                    String msg = "用户名或密码错误";
                    throw new BadCredentialsException(msg);
                }
                if (!sysUser.getStatus().equals(1)) {
                    String msg = "用户禁用";
                    throw new BadCredentialsException(msg);
                }
                if (sysUser.getType()==null) {
                    String msg = "用户未激活，请匹配用户角色";
                    throw new BadCredentialsException(msg);
                }
                // 获取用户权限
                List<GrantedAuthority> authorities = getGrantedAuthorities(sysUser);
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysUser.getAccount(), sysUser.getPassword(), authorities);
                token.setDetails(sysUser);
                sysUserRepository.saveAndFlush(sysUser);
                return token;
            } else {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
        }
    }

    /**
     * 获取用户权限
     *
     * @param sysUser 用户
     * @return 权限
     */
    private List<GrantedAuthority> getGrantedAuthorities(User sysUser) {

        return AuthorityUtils.createAuthorityList();
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
