package com.bonus.auth.service;

import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R;
import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.model.LoginUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author bonus
 */
@Service
public class UsernamePasswordLoginStrategy implements LoginStrategy {
    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private PasswordValidatorService passwordValidatorService;

    @Resource
    private SysPasswordService passwordService;


    /**
     * 登录方法
     *
     * @param username 用户的标识符（用户名、手机号、邮箱）
     * @param password 用户凭据（密码或验证码）
     * @return 登录结果
     */
    @Override
    public LoginUser login(String username, String password) {
        //参数校验
        passwordValidatorService.validateLoginParameters(username, password);
        // IP黑名单校验;
        passwordValidatorService.validateIpBlacklist(username);
        //通过用户名获取人员信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        passwordValidatorService.validateUserResult(username, userResult);
        //获取用户信息
        LoginUser userInfo = userResult.getData();
        SysUser user = userInfo.getSysUser();
        passwordValidatorService.validateApprovalStatus(username, user);
        // 验证用户状态
        passwordValidatorService.validateUserStatus(username, user);
        // 验证密码
        passwordService.validate(user, password, System.currentTimeMillis());
        // 处理IP校验
        passwordValidatorService.handleIpValidation(username, user);

        passwordValidatorService.processLoginBlackList(user);
        //返回信息
        return userInfo;
    }

}
