package com.bonus.common.security.service;

import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.VerificationCodeUtils;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.config.VerificationCodeConfig;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.bonus.common.core.utils.VerificationCodeUtils.CodeType.NUMERIC;

/**
 * @author bonus
 */
@Service
public class EmailService {
    @Resource
    private VerificationCodeConfig verificationCodeConfig;
    @Resource
    private RedisService redisService;
   @Resource
    private JavaMailSender mailSender;

    /**
     * 发送简单邮件
     *
     * @param to 接收者邮箱地址
     */
    public String sendSimpleEmail(String to) {
        String code = VerificationCodeUtils.generateVerificationCode(NUMERIC);
        String str = verificationCodeConfig.getContent().replace("<code>", code);
        str = str.replace("<time>", verificationCodeConfig.getTime().toString());
        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人邮箱地址
        message.setFrom("2642480752@qq.com");
        // 收件人邮箱地址
        message.setTo(to);
        // 邮件主题
        message.setSubject(verificationCodeConfig.getTitle());
        // 邮件内容
        message.setText(str);
        // 发送邮件
        mailSender.send(message);
        String uuid = StringUtils.randomUUID();
        String verifyKey = CacheConstants.VERIFICATION_CODE + uuid;
        redisService.setCacheObject(verifyKey, code, verificationCodeConfig.getTime(), TimeUnit.MINUTES);
        return uuid;
    }
}
