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.common.security.service.EmailService;
import com.bonus.common.security.service.SmsService;
import com.bonus.config.SystemConfig;
import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.model.LoginUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author bonus
 */
@Service
public class RegisterVerificationCodeSender implements VerificationCodeStrategy {

    private static final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    @Resource
    private EmailService emailService;
    @Resource
    private SmsService smsService;
    @Resource
    private SystemConfig systemConfig;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 发送验证码到邮箱或手机
     *
     * @param contactInfo 可以是邮箱地址或手机号码
     * @return 验证码发送的结果
     */
    @Override
    public void sendVerificationCode(String contactInfo) {
        if (isEmail(contactInfo)) {
            if (!systemConfig.getRegistersConfig().isEmailRegisters()) {
                throw new ServiceException("请输入正确的联系方式");
            }
            R<LoginUser> userResult = remoteUserService.getUserInfoByEmail(contactInfo , SecurityConstants.INNER);
            if (userResult.getData() != null) {
                throw new ServiceException("联系方式已经注册账号");
            }
            emailService.sendSimpleEmail(contactInfo);
        } else if (isPhone(contactInfo)) {
            if (!systemConfig.getRegistersConfig().isPhoneRegisters()) {
                throw new ServiceException("请输入正确的联系方式");
            }
            R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(contactInfo, SecurityConstants.INNER);
            if (userResult.getData() != null) {
                throw new ServiceException("联系方式已经注册账号");
            }
            smsService.sendSimplePhone(contactInfo);
        } else {
            throw new ServiceException("请输入正确的联系方式");
        }
    }

    /**
     * 检查是否是邮箱
     *
     * @param contactInfo 输入信息
     * @return 是否为邮箱
     */
    private boolean isEmail(String contactInfo) {
        return contactInfo.matches(EMAIL_REGEX);
    }

    /**
     * 检查是否是手机号
     *
     * @param contactInfo 输入信息
     * @return 是否为手机号
     */
    private boolean isPhone(String contactInfo) {
        return contactInfo.matches(PHONE_REGEX);
    }
}

