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

import javax.annotation.Resource;

/**
 * 验证码发送服务
 * 可发送到邮箱或手机
 *
 * @author bonus
 */
@Service
public class LoginVerificationCodeSender 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 RemoteUserService remoteUserService;

    /**
     * 发送验证码到邮箱或手机
     *
     * @param contactInfo 可以是邮箱地址或手机号码
     * @return 验证码发送的结果
     */
    @Override
    public void sendVerificationCode(String contactInfo) {
        if (isEmail(contactInfo)) {
            emailService.sendSimpleEmail(contactInfo);
        } else if (isPhone(contactInfo)) {
            smsService.sendSimplePhone(contactInfo);
        } else {
            handleUsernameLogin(contactInfo);
        }
    }

    /**
     * 检查是否是邮箱
     *
     * @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);
    }

    /**
     * 处理用户名登录逻辑
     *
     * @param username 用户名
     * @return 验证码发送的结果
     */
    private void handleUsernameLogin(String username) {
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        if (userResult == null || userResult.getData() == null || R.FAIL == userResult.getCode()) {
            throw new ServiceException("用户名/密码错误");
        }
        LoginUser user = userResult.getData();
        // 如果用户是管理员，则发送手机验证码
        if (user.getRoles().contains("admin")) {
            if (StringUtils.isEmpty(user.getSysUser().getPhonenumber())) {
                throw new ServiceException("此账号未绑定手机号,请先绑定手机号");
            }
            smsService.sendSimplePhone(user.getSysUser().getPhonenumber());
        } else {
            throw new ServiceException("不支持的登录方式");
        }
    }
}
