package com.ruoyi.framework.web.service;


import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author 赵佳鹏
 * @Description u代表userename p代表password
 */
@Component
public class SysUserUPAuthProvider implements AuthenticationProvider {
    private static final Logger log = LoggerFactory.getLogger(SysUserUPAuthProvider.class);

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private SysPermissionService permissionService;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SysUserUPAuth authToken = (SysUserUPAuth) authentication;
        String username = ((SysUserUPAuth) authentication).getUsername();
        String tenantId = ((SysUserUPAuth) authentication).getTenantId();
        if(StringUtils.isEmpty(tenantId)){
            tenantId = "00000000";
        }
        SysUser sysUser = sysUserService.selectUserByUserNameAndTenantId(username,tenantId);
        if (StringUtils.isNull(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        boolean matches = bCryptPasswordEncoder.matches(authToken.getPassword(), sysUser.getPassword());
        if (!matches) {
            log.info("登陆失败：用户" + ((SysUserUPAuth) authentication).getUsername() + "密码错误!");
            throw new BadCredentialsException("登录失败: 用户密码错误");
        }
        authToken.setDetails(createLoginUser(sysUser));
        authToken.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(authToken);
        return authToken;
    }

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

    public LoginUser createLoginUser(SysUser user) {
        //PC端半个小时过期时间
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
