package com.jeequan.jeepay.bizcommons.manage.email;

import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.DBEmailConfig;
import com.jeequan.jeepay.service.impl.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
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;
import java.util.Properties;

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

    @Autowired
    private SysConfigService sysConfigService;

    public JavaMailSender mailSender;

    public DBEmailConfig getInstance(){
        DBEmailConfig emailConfig = sysConfigService.getEmailConfig();
        if(emailConfig == null){
            throw new BizException("未开启邮箱配置");
        }
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(emailConfig.getEmailHost());
        javaMailSender.setDefaultEncoding("utf-8");
        javaMailSender.setPort(emailConfig.getEmailPort());
        javaMailSender.setUsername(emailConfig.getEmailAccountNo());
        javaMailSender.setPassword(emailConfig.getEmailPassword());
        Properties props = System.getProperties();
        props.put("mail.smtp.host", emailConfig.getEmailHost());
        props.put("mail.username", emailConfig.getEmailAccountNo());
        props.put("mail.password", emailConfig.getEmailPassword());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.port", emailConfig.getEmailPort());
        props.put("mail.smtp.socketFactory.port", emailConfig.getEmailPort());
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(props.getProperty("mail.username"), props.getProperty("mail.password"));
            }
        });
        javaMailSender.setSession(session);
        mailSender = javaMailSender;
        return emailConfig;
    }


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

    /**
     * 发送邮件
     * @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) {

        DBEmailConfig config = getInstance();

        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(config.getEmailName() + "<" + config.getEmailAccountNo() + ">");
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setText(content);
            if(workBook != null){
                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);
    }
}
