package cn.pluss.platform.service;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 发送电子邮件相关的功能service
 * @author nb2020
 */
@Slf4j
@Component
public class EmailService {

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

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


    public EmailService() {
        System.setProperty("mail.mime.splitlongparameters", "false");
    }

    @Setter(onMethod_ = {@Autowired})
    private JavaMailSender mailSender;

    /**
     * 发送邮件
     * @param tos       接收人邮箱数组
     * @param ccs       抄送人邮箱数组
     * @param title     邮件主题
     * @param content   邮件内容
     * @param workBook  附件excel
     */
    public void sendEmail(String[] tos, String[] ccs, String title, String content, XSSFWorkbook workBook, String workBookName) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper;

        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            mimeMessageHelper.setTo(tos);
            if (ccs != null) {
                mimeMessageHelper.setCc(ccs);
            }

            mimeMessageHelper.setFrom(nickname + "<" + username + ">");
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setText(content);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workBook.write(out);
            byte[] bookByteArr = out.toByteArray();
            InputStream in = new ByteArrayInputStream(bookByteArr);
            String newFileName =  MimeUtility.encodeWord(workBookName, "utf-8", "B");
            mimeMessageHelper.addAttachment(newFileName, new ByteArrayResource(IOUtils.toByteArray(in), "application/vnd.ms-excel;charset=UTF-8"));

        } catch (IOException | MessagingException e) {
            log.error("邮件发送失败");
            e.printStackTrace();
            return;
        }


        mailSender.send(mimeMessage);
    }
}
