package com.ruoyi.common.utils.email;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class EmailUtil {

    private static final Logger log = LoggerFactory.getLogger(EmailUtil.class);

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;

    /**
     * 校验邮件参数
     */
    private void checkMail(BaseEmailEntity baseEmailEntity) {
        if (StringUtils.isEmpty(baseEmailEntity.getTo())) {
            throw new ServiceException(MessageUtils.message("email.to.empty"));
        }
        if (StringUtils.isEmpty(baseEmailEntity.getSubject())) {
            throw new ServiceException(MessageUtils.message("email.subject.empty"));
        }
        if (StringUtils.isEmpty(baseEmailEntity.getText())) {
            throw new ServiceException(MessageUtils.message("email.text.empty"));
        }
    }

    /**
     * 发送简单邮件
     */
    public void sendSimpleMail(BaseEmailEntity baseEmailEntity) {
        checkMail(baseEmailEntity);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject(baseEmailEntity.getSubject());
        message.setText(baseEmailEntity.getText());
        message.setTo(baseEmailEntity.getTo());
        mailSender.send(message);
    }

    /**
     * 发送邮件通用方法
     *
     * @param baseEmailEntity 通用邮件参数实体
     * @param iSHTML          是否解析HTML
     */
    public void sendMail(BaseEmailEntity baseEmailEntity, boolean iSHTML) {
        checkMail(baseEmailEntity);
        try {
            // 创建一个Mime消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(baseEmailEntity.getTo());
            helper.setSubject(baseEmailEntity.getSubject());
            helper.setText(baseEmailEntity.getText(), iSHTML);
            // 处理附件
            if (baseEmailEntity.getAttachments() != null && !baseEmailEntity.getAttachments().isEmpty()) {
                baseEmailEntity.getAttachments().forEach(attachment -> {
                    try {
                        File file = new File(attachment);
                        helper.addAttachment(file.getName(), file);
                    } catch (MessagingException e) {
                        log.error("邮件发送附件处理失败", e);
                    }
                });
            }
            // 处理内嵌图片
            if (baseEmailEntity.getImagePaths() != null && !baseEmailEntity.getImagePaths().isEmpty()) {
                baseEmailEntity.getImagePaths().forEach(imagePath -> {
                    try {
                        File file = new File(imagePath);
                        helper.addInline(file.getName(), file);
                    } catch (MessagingException e) {
                        log.error("邮件发送内嵌图片处理失败", e);
                    }
                });
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("邮件发送失败", e);
        }
    }

    /**
     * 发送HTML邮件
     */
    public void sendHTMLMail(BaseEmailEntity baseEmailEntity) {
        checkMail(baseEmailEntity);
        try {
            // 创建一个Mime消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(baseEmailEntity.getTo());
            helper.setSubject(baseEmailEntity.getSubject());
            // true表示带有附件或html
            helper.setText(baseEmailEntity.getText(), true);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("HTML邮件发送失败", e);
        }
    }

    /**
     * 发送带附件邮件
     */
    public void sendAttachmentsMail(BaseEmailEntity baseEmailEntity) {
        checkMail(baseEmailEntity);
        try {
            // 创建一个Mime消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(baseEmailEntity.getTo());
            helper.setSubject(baseEmailEntity.getSubject());
            helper.setText(baseEmailEntity.getText());
            if (baseEmailEntity.getAttachments() != null && !baseEmailEntity.getAttachments().isEmpty()) {
                baseEmailEntity.getAttachments().forEach(attachment -> {
                    try {
                        File file = new File(attachment);
                        helper.addAttachment(file.getName(), file);
                    } catch (MessagingException e) {
                        log.error("邮件发送附件处理失败", e);
                    }
                });
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("带附件邮件发送失败", e);
        }
    }
}
