package cn.datax.service.email.utils;

import cn.datax.service.email.api.entity.EmailEntity;
import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class EmailUtil {

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

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

    @Autowired
    private JavaMailSender mailSender;

    public void sendEmail(EmailEntity mailEntity) throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        InternetAddress from = null;
        String alias = null;
        try {
            alias = MimeUtility.encodeText(fromNick);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            from = new InternetAddress(alias + " <" + fromAddress + ">");
        } catch (AddressException e) {
            e.printStackTrace();
        }
        helper.setFrom(from);
        helper.setSubject(mailEntity.getSubject());
        helper.setText(mailEntity.getText(),true);
        List<String> tos = mailEntity.getTos();
        helper.setTo((String[])tos.toArray(new String[tos.size()]));
        List<String> ccs = mailEntity.getCcs();
        if(CollUtil.isNotEmpty(ccs)){
            helper.setCc((String[])ccs.toArray(new String[ccs.size()]));
        }
        List<String> bccs = mailEntity.getBccs();
        if(CollUtil.isNotEmpty(bccs)){
            helper.setBcc((String[])bccs.toArray(new String[bccs.size()]));
        }
        List<File> files = mailEntity.getFiles();
        if(CollUtil.isNotEmpty(files)){
            for (int i = 0; i < files.size(); i++) {
                File file = files.get(i);
                helper.addAttachment(file.getName(), file);
            }
        }
        mailSender.send(mimeMessage);
    }
}
