package cn.com.poc.common.service.impl;

import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.service.SendEmailService;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.common.utils.RandomCodeUtils;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.frame.entity.EmailSenderEntity;
import cn.com.yict.framemax.frame.service.EmailSenderService;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
public class SendEmailServiceImpl implements SendEmailService {
    @Resource
    private EmailSenderService emailSenderService;

    @Resource
    private FmxParamConfigService fmxParamConfigService;

    @Resource
    private RedisService redisService;

    @Override
    public void sendEmailCode(String emailAddress) throws Exception {
        Assert.notBlank(emailAddress);
        EmailSenderEntity entity = new EmailSenderEntity();

        String code = RandomCodeUtils.generateNumber(6);
        String projectName = fmxParamConfigService.getParam("project.name");
        String body = fmxParamConfigService.getParam("login.email.send.body");
        body = body.replaceAll("\\$\\{projectName}", projectName)
                .replaceAll("\\$\\{emailAddress}", emailAddress)
                .replaceAll("\\$\\{authCode}", code)
                .replaceAll("\\$\\{CurrDate}", DateUtils.getCurrDate());
        entity.setBody(body);
        entity.setSubject("用户邮箱校验");
        List<String> list = new LinkedList<>();
        list.add(emailAddress);
        entity.setTo(list); //接收者
        try {
            // 如果成功发送，则把验证码存入redis当中，并设置15分钟的过期时间
            emailSenderService.sendMail(entity, null);
            redisService.set(emailAddress, code, 900);
        } catch (Exception e) {
            throw new I18nMessageException("exception/verification.code.sending.failed.please.try.again");
        }
    }
}
