package cn.quantgroup.customer.util;
import cn.quantgroup.customer.rest.param.mail.SendMailParam;
import javax.mail.internet.MimeUtility;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import java.io.Serializable;

/**
 * Date : 2017/9/28
 * Created with suntao
 */
public class MailUtil implements Serializable {

    private static final long serialVersionUID = -1L;

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

    /**
     * 发送一个简单邮件
     *
     * @param param
     */
    public static void sendSampleMail(SendMailParam param) throws Exception {
        if (!isSampleParamValidation(param)) {
            return;
        }
        JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
        //SimpleMailMessages实现了MimeMessageHelper，为普通邮件模板，支持文本。
        SimpleMailMessage smm = new SimpleMailMessage();
        // 设定邮件参数
        smm.setFrom(param.getSender());
        smm.setTo(param.getReceiver());
        if (ArrayUtils.isNotEmpty(param.getCopier())) {
            smm.setCc(param.getCopier());
        }
        smm.setSubject(param.getSubject());
        smm.setText(param.getContentText());
        // 发送邮件
        try {
            mailSender.send(smm);
        } catch (MailException e) {
            logger.error("[MailUtilSendMail] 邮件发送失败。", e);
            throw new Exception(e);
        }
    }

    /**
     * 发送一个支持html的邮件
     *
     * @param param Sender，Subject，Receiver，ContentText必选，Copier选填
     */
    public static void sendHtmlMail(SendMailParam param) {
        if (!isSampleParamValidation(param)) {
            return;
        }
        JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
        MimeMessage mimeMessage;
        try {
            mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(param.getSender());
            helper.setSubject(param.getSubject());
            helper.setTo(param.getReceiver());
            if (ArrayUtils.isNotEmpty(param.getCopier())) {
                helper.setCc(param.getCopier());
            }
            helper.setText(param.getContentText(), Boolean.TRUE);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            logger.error("[MailUtilSendMail] 邮件发送失败。", e);
            throw new RuntimeException(e);
        }

    }

    /**
     * 发送一个支持html 和 附件 的邮件
     *
     * @param param Sender，Subject，Receiver，ContentText，AttachmentFileName，Attachment必选，Copier选填
     */
    public static void sendHtmlAndAttachmentMail(SendMailParam param) {
        if (!isAttachmentParamValidation(param)) {
            return;
        }
        JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
        MimeMessage mimeMessage;
        try {
            mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(param.getSender());
            helper.setSubject(param.getSubject());
            helper.setTo(param.getReceiver());
            if (ArrayUtils.isNotEmpty(param.getCopier())) {
                helper.setCc(param.getCopier());
            }
            helper.setText(param.getContentText(), Boolean.TRUE);
            helper.addAttachment(MimeUtility.encodeWord(param.getAttachmentFileName()), new ByteArrayResource(IOUtils.toByteArray(param.getInputStreamSource().getInputStream())));
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            logger.error("[MailUtilSendMail] 邮件发送失败。", e);
            throw new RuntimeException(e);
        }

    }

    /**
     * 验证简单邮件参数
     *
     * @param param
     * @return true：参数正确；false：参数有误
     */
    private static boolean isSampleParamValidation(SendMailParam param) {
        if (param == null) {
            logger.error("[MailUtilSendMail] 邮件发送失败, 发送参数为空");
            return false;
        }
        if (StringUtils.isAnyBlank(param.getSender(), param.getSubject(), param.getContentText()) || ArrayUtils.isEmpty(param.getReceiver())) {
            logger.error("[MailUtilSendMail] 邮件发送失败, 请检查参数");
            return false;
        }
        return true;
    }

    /**
     * 验证附件邮件参数
     *
     * @param param
     * @return true：参数正确；false：参数有误
     */
    private static boolean isAttachmentParamValidation(SendMailParam param) {
        if (param == null) {
            logger.error("[MailUtilSendMail] 邮件发送失败, 发送参数为空");
            return false;
        }
        if (StringUtils.isAnyBlank(param.getSender(), param.getSubject(), param.getContentText(),
                param.getAttachmentFileName()) || ArrayUtils.isEmpty(param.getReceiver()) || param.getInputStreamSource() == null) {
            logger.error("[MailUtilSendMail] 邮件发送失败, 请检查参数");
            return false;
        }
        return true;
    }

}
