package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisCache redisCache;

    /**
     * 发送注册邮箱验证码
     *
     * @param email 邮箱
     * @param uuid 唯一标识
     * @param subject 邮件主题
     */
    public void sendEmailCode(String email, String uuid, String subject) {
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        String verifyKey = CacheConstants.EMAIL_CODE_KEY + email + ":" + StringUtils.nvl(uuid, "");
        redisCache.setCacheObject(verifyKey, code, 5, TimeUnit.MINUTES);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("adamlawen@qq.com");
        message.setTo(email);
        message.setSubject(subject);
        message.setText("您的验证码是：" + code + "，5分钟内有效。");
        mailSender.send(message);
    }

    /**
     * 校验验证码
     *
     * @param email 邮箱
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateEmailCode(String email, String code, String uuid)
    {
        String verifyKey = CacheConstants.EMAIL_CODE_KEY + email + ":" + StringUtils.nvl(uuid, "");
        String emailCode = redisCache.getCacheObject(verifyKey);
        if (emailCode == null)
        {
            throw new ServiceException("验证码已失效，请重新获取验证码");
        }
        if (!code.equalsIgnoreCase(emailCode))
        {
            throw new ServiceException("验证码不正确");
        }
        redisCache.deleteObject(verifyKey);
    }
}

