package com.friday.custody.utils;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.friday.custody.dto.MsgSendDto;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Data
@Configuration
public class MailSendUtil {
    @Value("${custody.msgSend.mail.encoding}")
    private  String encoding;//UTF-8
    @Value("${custody.msgSend.mail.host}")
    private  String host;//spring.mail.host=168.61.10.118
    @Value("${custody.msgSend.mail.port}")
    private  String port;//spring.mail.port=25
    @Value("${custody.msgSend.mail.protocol}")
    private  String protocol;//smtp
    @Value("${custody.msgSend.mail.username}")
    private  String username;//taie@htzq.htsc.com.cn
    @Value("${custody.msgSend.mail.password}")
    private  String password;//htSC19880911
    @Value("${custody.msgSend.mail.address}")
    private  String address;//taie@htzq.htsc.com.cn
    private volatile AtomicReference<JavaMailSenderImpl> javaMailSender = new AtomicReference<>();
    public   Boolean sendMail(MsgSendDto msgDto) {
        while (Objects.isNull(this.getJavaMailSender().get())) {
            JavaMailSenderImpl update = new JavaMailSenderImpl();
            update.setDefaultEncoding(encoding);
            update.setHost(host);
            update.setPort(Integer.parseInt(port));
            update.setProtocol(protocol);
            update.setUsername(username);
            update.setPassword(password);
            if (this.getJavaMailSender().compareAndSet(null, update)) {
                break;
            }
        }
        try {
            MimeMessage mimeMessage = this.getJavaMailSender().get().createMimeMessage();
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, this.getJavaMailSender().get().getDefaultEncoding());
            //from
            message.setFrom(this.getAddress());
            //to
            String[] emails = msgDto.getEmailList().toArray(new String[0]);
            log.info("the emails is : {}", Arrays.toString(emails));
            message.setTo(emails);
            //subject
            String subject = msgDto.getSubject();
            message.setSubject(subject);
            //msg
            String text = msgDto.getContent();
            //bodyPart
//            Multipart multipart = getMultipart(text, null);
//            mimeMessage.setContent(multipart);
//            mimeMessage.setContent(multipart);
            mimeMessage.saveChanges();
            this.getJavaMailSender().get().send(mimeMessage);
        } catch (MessagingException e) {
            log.error("sendMail is fail :",e);
            return false;
        }
        return true;
    }


//    private static Multipart getMultipart(String text, List<BpmsMessageTaskAttachmentUploadDto> attachmentList) throws MessagingException {
//        Multipart multipart = new MimeMultipart();
//        BodyPart messageBodyPart = new MimeBodyPart();
//        messageBodyPart.setContent(text, "text/html;charset=utf-8");
//        multipart.addBodyPart(messageBodyPart);
//        ArrayList<String> unSendMailAttachment = Lists.newArrayList();
//        //多个附件
//        if (CollectionUtils.isNotEmpty(attachmentList)) {
//            for (BpmsMessageTaskAttachmentUploadDto uploadDto : attachmentList) {
//                String fileSource = uploadDto.getFilePath();
//                String fileName = uploadDto.getFileName();
//                if (StringUtils.isBlank(fileSource) || !new File(fileSource).exists()) {
//                    log.warn("对应的本地文件不存在或者文件路径为空,该邮件附件被过滤! 本地文件路径:" + fileSource);
//                    unSendMailAttachment.add(fileSource);
//                } else {
//                    MimeBodyPart mimeBodyPart = new MimeBodyPart();
//                    DataSource source = new FileDataSource(fileSource);
//                    mimeBodyPart.setDataHandler(new DataHandler(source));
//                    mimeBodyPart.setFileName(fileName);
//                    multipart.addBodyPart(mimeBodyPart);// Put parts in
//                }
//            }
//        }
////        log.info("添加邮件附件结束! 被过滤的附件文件:" + JSON.toJSONString(unSendMailAttachment));
//        return multipart;
//    }
}
