package com.diaoyun.zion.master.util;

import com.diaoyun.zion.master.bo.EmailTemplateBo;
import com.diaoyun.zion.master.config.DomainProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component("emailHelper")
public class EmailHelper {
    @Autowired
    private Configuration configuration;
    @Autowired
    private DomainProperties domainProperties;
    private static Logger logger = LoggerFactory.getLogger(EmailHelper.class);


    public Integer sendIdentifyEmail(String toEmail, String templateName, EmailTemplateBo emailTemplateBo) throws IOException, TemplateException, EmailException {
        /*Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        // 初始化一些配置
        cfg.setDirectoryForTemplateLoading(new File("/"));
        cfg.setDefaultEncoding(Consts.UTF_8.name());
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);*/
        Template t = configuration.getTemplate(templateName);
        Map<String,Object> model = new HashMap<>();
        model.put("identifyCode", emailTemplateBo.getIdentifyCode());
        model.put("nick", emailTemplateBo.getNick());
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
        HtmlEmail email = new HtmlEmail();//创建一个HtmlEmail实例对象
        email.setHostName(domainProperties.getProperty("email.hostName"));//邮箱的SMTP服务器，一般123邮箱的是smtp.123.com,qq邮箱为smtp.qq.com
        email.setCharset(Consts.UTF_8.name());//设置发送的字符类型
        //email.addTo("zhengfanguang@163.com");//设置收件人
        email.addTo(toEmail);//设置收件人
        email.setFrom(domainProperties.getProperty("email.from.email"), domainProperties.getProperty("email.from.name"));//发送人的邮箱为自己的，用户名可以随便填
        email.setAuthentication(domainProperties.getProperty("email.authentication.userName"), domainProperties.getProperty("email.authentication.password"));//设置发送人的邮箱和用户名和授权码(授权码是自己设置的)
        email.setSubject(domainProperties.getProperty("email.subject"));//设置发送主题
        email.setMsg(html);//设置发送内容
        String res=email.send();
        //logger.info("邮件发送结果："+res);
        return emailTemplateBo.getIdentifyCode();
    }
}
