package com.bonus.auth.service;

import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.config.SystemConfig;
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 EmailOtpLoginStrategy implements LoginStrategy {
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private PasswordValidatorService passwordValidatorService;

    @Override
    public LoginUser login(String email, String otp) {
        if (!systemConfig.getLoginConfig().isPhoneCode()) {
            throw new ServiceException("用户不存在/密码错误");
        }
        passwordValidatorService.checkPhoneCaptcha(email, otp);
        R<LoginUser> userResult = remoteUserService.getUserInfoByEmail(email, SecurityConstants.INNER);
        //验证用户是否存在
        passwordValidatorService.validateUserResult(email, userResult);
        LoginUser userInfo = userResult.getData();
        SysUser user = userInfo.getSysUser();
        passwordValidatorService.validateApprovalStatus(email, user);
        // 验证用户状态
        passwordValidatorService.validateUserStatus(email, user);
        passwordValidatorService.processLoginBlackList(user);
        //返回信息
        return userInfo;
    }
}
