package com.storlead.mail.util;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.storlead.framework.common.util.SpringContextUtils;
import com.storlead.mail.pojo.entity.ClientSentEmailsEntity;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.enums.SendStatus;
import com.storlead.mail.service.ClientSentEmailsService;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.SmtpPopSettingsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-08-28 10:01
 */
@Log4j2
@Component
public class EmailSenderWithThreadLocal {
    @Resource
    private EmailsService emailsService;
    @Resource
    private ClientSentEmailsService sentEmailsService;
    @Resource
    private SmtpPopSettingsService popSettingsService;



    public void asynSendMailMessage(Transport transport, Message message, EmailsEntity email) {
        try {
            transport.addTransportListener(new TransportListener() {
                @Override
                public void messageDelivered(TransportEvent e) {
                    onEmailSentSuccess(email);
                }

                @Override
                public void messageNotDelivered(TransportEvent e) {
                    onEmailSentFailure(email);
                }

                @Override
                public void messagePartiallyDelivered(TransportEvent e) {
                    onEmailSentPartialSuccess(email);
                }
            });
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }catch (Exception e) {
            log.error("error-------------",e);
            e.printStackTrace();
        }
    }

    public CompletableFuture<SendStatus> sendMailMessage(Transport transport, Message message, EmailsEntity email) {
        CompletableFuture<SendStatus> future = new CompletableFuture<SendStatus>();

        TransportListener listener = new TransportListener() {
            @Override
            public void messageDelivered(TransportEvent e) {
                onEmailSentSuccess(email);
                future.complete(SendStatus.SUCCESS);
            }

            @Override
            public void messageNotDelivered(TransportEvent e) {
                onEmailSentFailure(email);
                future.complete(SendStatus.FAILED);
            }

            @Override
            public void messagePartiallyDelivered(TransportEvent e) {
                onEmailSentPartialSuccess(email);
                future.complete(SendStatus.PARTIAL_SUCCESS);
            }
        };

        try {
            transport.addTransportListener(listener); // 注意：应使用addTransportListener而不是addTransportListener（可能原代码有拼写错误）
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (SendFailedException e1) {
            log.error("邮件发送过程中发生异常", e1);
            future.complete(SendStatus.SERVER_EXCEPTION_550);
        } catch (AuthenticationFailedException e) {
            future.complete(SendStatus.SERVER_LOGIN_FAIL);
        } catch (MessagingException e) {
            log.error("邮件发送过程中发生异常", e);
            future.complete(SendStatus.SERVER_LOGIN_FAIL);
//            if (e.getMessage().contains("")) {
//                future.complete(SendStatus.PARTIAL_SUCCESS);
//            } else if (e.getMessage().contains("")) {
//                future.complete(SendStatus.PARTIAL_SUCCESS);
//            } else {
//            }
        }
        return future;
    }

    private void onEmailSentSuccess(EmailsEntity entity)  {
        try {
            try {
                Object myClassInstance = SpringContextUtils.getBean("customerServiceImpl");
                Class<?> clazz = myClassInstance.getClass();
                Set<String> mailAddress = new HashSet<>();
                if (StrUtil.isNotBlank(entity.getRecipient())) {
                    List<String> recipientls = Arrays.asList(entity.getRecipient().split(","));
                    mailAddress.addAll(recipientls);
                }
                if (StrUtil.isNotBlank(entity.getRecipientCc())) {
                    List<String> recipientccls = Arrays.asList(entity.getRecipientCc().split(","));
                    mailAddress.addAll(recipientccls);
                }
                if (!CollectionUtils.isEmpty(mailAddress)) {
                    LocalDateTime sentDate = (Objects.isNull(entity.getSentDate())) ? LocalDateTime.now() : entity.getSentDate().toInstant()
                            .atZone(ZoneId.systemDefault()) // 使用系统默认时区
                            .toLocalDateTime();
                    Method method = clazz.getMethod("updateFollowUpTimeByEmail",Set.class, LocalDateTime.class);
                    method.invoke(myClassInstance,mailAddress,sentDate);
                }
            } catch (Exception e) {
                log.error("updateFollowUpTimeByEmail --e",e);
            }

            emailsService.removeById(entity.getId());
            // 保存发送日志
            saveLog(entity);
        }catch (Exception e1) {
            log.error("onEmailSentSuccess------------",e1);
        }
    }

    private void onEmailSentFailure(EmailsEntity entity) {
        if (Objects.isNull(emailsService)) {
            return;
        }
        LambdaUpdateWrapper<EmailsEntity> update = new LambdaUpdateWrapper<>();
        update.set(EmailsEntity::getStatus,Integer.valueOf(2));
        update.eq(EmailsEntity::getId,entity.getId());
        emailsService.update(update);
    }

    private void onEmailSentPartialSuccess(EmailsEntity entity) {
        try {
            try {
                Object myClassInstance = SpringContextUtils.getBean("customerMailBingMarkServiceImpl");
                Class<?> clazz = myClassInstance.getClass();
                Set<String> mailAddress = new HashSet<>();
                if (StrUtil.isNotBlank(entity.getRecipient())) {
                    List<String> recipientls = Arrays.asList(entity.getRecipient().split(","));
                    mailAddress.addAll(recipientls);
                }
                if (StrUtil.isNotBlank(entity.getRecipientCc())) {
                    List<String> recipientccls = Arrays.asList(entity.getRecipientCc().split(","));
                    mailAddress.addAll(recipientccls);
                }
                LocalDateTime sentDate = (Objects.isNull(entity.getSentDate())) ? LocalDateTime.now() : entity.getSentDate().toInstant()
                        .atZone(ZoneId.systemDefault()) // 使用系统默认时区
                        .toLocalDateTime();

                if (!CollectionUtils.isEmpty(mailAddress)) {
                    Method method = clazz.getMethod("updateFollowUpTimeByEmail",Set.class, LocalDateTime.class);
                    method.invoke(myClassInstance,mailAddress,sentDate);
                }
            } catch (Exception e) {
                log.error("updateFollowUpTimeByEmail --e",e);
            }
            emailsService.removeById(entity.getId());
            // 保存客户端的发送日志
            saveLog(entity);
        }catch (Exception e1) {
            log.error("onEmailSentSuccess------------",e1);
        }
    }

    private void saveLog(EmailsEntity entity) {
        try {
            ClientSentEmailsEntity sentEmailsEntity = new ClientSentEmailsEntity();
            BeanUtils.copyProperties(entity,sentEmailsEntity);
            sentEmailsService.save(sentEmailsEntity);
        }catch (Exception e) {
            log.error("saveLog-----ClientSentEmails-------",e);
        }
    }
}
