package com.ozs.da.utils.mail;

import com.ozs.da.entity.mail.ErrorJobInfo;
import com.ozs.da.entity.mail.MailBean;
import com.ozs.da.service.job.impl.TriggerJob;
import com.ozs.da.utils.CommonConfUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author 许明
 * on 2019/5/9.
 * @version 2.0.0
 */
public class MailUtil {

    private static final Logger logger = LogManager.getLogger(MailUtil.class);

    private final static String MAIL_USER = CommonConfUtil.getConf("mail.user");
    private final static String MAIL_PASS = CommonConfUtil.getConf("mail.pwd");
    private final static String MAIL_SERVER = CommonConfUtil.getConf("mail.server");
//    private final static String MAIL_TO = CommonConfUtil.getConf("mail.to");

    public static void sendErrorTaskInfo(String taskId) throws Exception{
        MailBean mb = new MailBean();
        mb.setHost(MAIL_SERVER); // 设置SMTP主机(163)，若用126，则设为：smtp.126.com
        mb.setUsername(MAIL_USER); // 设置发件人邮箱的用户名
        mb.setPassword(MAIL_PASS); // 设置发件人邮箱的密码，需将*号改成正确的密码
        mb.setFrom(MAIL_USER); // 设置发件人的邮箱
        String mailTo = TriggerJob.getSendMailsConfig();
        mb.setTo(mailTo); // 设置收件人的邮箱

        ErrorJobInfo errorJobInfo = TriggerJob.getErrorJobInfoById(taskId);
        mb.setSubject("数据中心调度【" + errorJobInfo.getTaskName() + "】任务错误信息"); // 设置邮件的主题
        mb.setContent("数据中心调度【taskId=" + errorJobInfo.getTaskId() + "】【taskName=" + errorJobInfo.getTaskName() + "】任务出错，请检查！"
                + System.lineSeparator() + "具体信息如下："
                + System.lineSeparator() + errorJobInfo.getErrorDesc()); // 设置邮件的正文

        logger.info("正在发送邮件...收件人为：[" + mailTo + "]");
        // 发送邮件
        if (SendMailUtil.sendMail(mb)) {
            logger.info("发送成功！");
            TriggerJob.updateSendedStatusById(errorJobInfo.getId(), "1");
        } else {
            logger.error("发送失败！");
        }
    }
}
