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 PhoneOtpLoginStrategy implements LoginStrategy {
    @Resource
    private SystemConfig systemConfig;

    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private PasswordValidatorService passwordValidatorService;


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

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