package com.storlead.sales.controller.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.storlead.framework.common.util.encryptor.AccessKeyEncryptor;
import com.storlead.framework.common.result.Result;
import com.storlead.message.enums.MessageTypeEnum;
import com.storlead.message.service.impl.MessageService;
import com.storlead.sales.pojo.dto.task.TaskTestDTO;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.service.customer.MessageAssembleService;
import com.storlead.mail.connection.MailConnection;
import com.storlead.mail.connection.client.MailConnectionUtil;
import com.storlead.mail.connection.config.MailProperties;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.SmtpPopSettingsService;
import com.storlead.sales.service.task.TaskService;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.pop3.POP3Folder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.search.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-09-29 18:27
 */
@Api(tags = "测试: 测试模块")
@Log4j2
@RestController
@RequestMapping("/sys/test")
@Data
public class TestApiController {

    @Resource
    private MessageAssembleService messageAssembleService;
    @Resource
    private TaskService taskService;
    @Resource
    private MessageService messageService;
    @Resource
    private EmailsService emailsService;
    @Resource
    private SmtpPopSettingsService smtpPopSettingsService;
    @ApiOperation("getTest")
    @PostMapping("getTest")
    public Result getTest(@RequestBody TaskTestDTO dto) {
        Set<Long> toUser = new HashSet<>();
        toUser.add(408l);
        TaskEntity t = taskService.getById(dto.getId());
        Map<String, Object> beanMap = BeanUtil.beanToMap(t);
        if (Objects.nonNull(t.getResourceTypeId())) {
            beanMap.put("id",t.getResourceTypeId());
        }
        beanMap.put("callbackUrl",getRouteUrl(t.getResourceType()));
//        messageAssembleService.sendCustomerEventMessages(dto.getId(), "ADD_CUSTOMER",toUser);
        messageService.autoMatchEventSendMessage(beanMap,"80","DISPATCH_TASK",toUser,t.getRemindMode().split(","));
        return Result.ok();
    }

    @PostMapping(value = "/receive_mail")
    @ApiOperation(value = "接收邮件" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> receiveMail(Integer id) {
        Long currentUserId = 211L;
        // Long currentUserId = 452L;
        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
        if (Objects.isNull(currentUserId) || Objects.isNull(smtpPop)) {
            return Result.error("请先设置邮箱账号！");
        }
        AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
        String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
        smtpPop.setEmailPassword(pass);

        MailProperties properties = new MailProperties(smtpPop);
        MailConnection mailConnection = MailConnectionUtil.receiveEmailsConnection(properties);
        if (Objects.isNull(mailConnection)) {
            return Result.ok();
        }
        try {
            Store store = mailConnection.getStore();
//            Folder inbox = store.getFolder("INBOX");
            Folder inbox = store.getFolder("Sent Items");
            inbox.open(Folder.READ_WRITE);

            String mesId = "<1C9E8D2B2609EB49+2024102818153183534990@renice.co>";
            Message [] messages = inbox.getMessages();
            List<Message> messagesls = Arrays.asList(messages);
           Optional<Message> optional =  messagesls.stream().filter(e -> {
                try {
                    return e.getHeader("Message-ID")[0].equals(mesId);
                } catch (MessagingException ex) {
                   return false;
                }
            }).findFirst();

           if (optional.isPresent()) {
               Message message = optional.get();
               EmailsEntity entity = emailsService.convertMessageToEmailVo(message,false);
               entity.setSmtpPopId(smtpPop.getId());
               entity.setFolder("INBOX");
               emailsService.saveOrUpdate(entity);
           }
//            for (Message message : messages) {
//                String messageId = message.getHeader("Message-ID")[0];
//                if (mesId.equals(messageId)) {
//                    messageVar = message;
//                    break;
//                }
//            }

        }catch (Exception e) {
            log.error("test receiveMail -- error",e);
        }
        return Result.ok();
    }

    @PostMapping(value = "/receive_mail_test")
    @ApiOperation(value = "接收邮件" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> receiveMail() throws MessagingException {
//        Long currentUserId = 408L;
//        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
//        if (Objects.isNull(currentUserId) || Objects.isNull(smtpPop)) {
//            return Result.error("请先设置邮箱账号！");
//        }
//        AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
//        String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
//        smtpPop.setEmailPassword(pass);
//
//        MailProperties properties = new MailProperties(smtpPop);
//        MailConnection mailConnection = MailConnectionUtil.receiveEmailsConnection(properties);
//        if (Objects.isNull(mailConnection)) {
//            return Result.error("链接失败");
//        }
//        Folder inbox = mailConnection.getFolder("INBOX");
//        if (Objects.isNull(inbox)) {
//            return Result.error("获取文件夹失败");
//        }
//        IMAPFolder folder = (IMAPFolder)inbox;
//        inbox.open(Folder.READ_WRITE);
//
////        Folder sentItems = mailConnection.getFolder("Sent Items");
//        Message [] messages = folder.getMessages();
//        SearchTerm searchTerm = new HeaderTerm("Message-ID","<tencent_573CB96038E4DCF91E167FA6@qq.com>");
//        SearchTerm searchTerm1 = new MessageIDTerm("<tencent_573CB96038E4DCF91E167FA6@qq.com>");
//        Message [] messages0 = folder.search(searchTerm);
//        Message [] messages1 = folder.search(searchTerm1);
//
//        for (Message message : messages) {
//            long uid = folder.getUID(message);
//            String msguid = message.getHeader("Message-ID")[0];
//            if (message.match(searchTerm1)) {
//                log.error("找到了 :"+msguid);
//            }
//            log.error("Message-UID = :"+uid);
//            log.error("Message-subject = :"+message.getSubject());
//            log.error("Message-ID = :"+msguid);
//        }

        List<EmailsEntity> taskEntities =  emailsService.getDelayDeleteMail();
        if (CollectionUtil.isNotEmpty(taskEntities)) {
            Map<Long,List<EmailsEntity>> attachmentsMap = taskEntities.stream().collect(Collectors.groupingBy(EmailsEntity::getSmtpPopId));
            for (Map.Entry<Long, List<EmailsEntity>> entry : attachmentsMap.entrySet()) {
                SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getById(entry.getKey());
                List<EmailsEntity>  entryls = entry.getValue();
                if (!CollectionUtils.isEmpty(entryls)) {
                    AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
                    String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
                    smtpPop.setEmailPassword(pass);
                    MailProperties properties1 = new MailProperties(smtpPop);
                    Properties properties = new Properties();
                    properties.put("mail.imap.host", properties1.getHost());
                    properties.put("mail.imap.port", properties1.getPort());
                    properties.put("mail.imap.starttls.enable", "true");
                    properties.put("mail.imap.ssl.trust", "*");
                    properties.put("mail.imap.ssl.enable", "true");

                    Authenticator auth = new Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(properties1.getEmailAddress(), properties1.getEmailPassword());
                        }
                    };
                    Session session = Session.getInstance(properties,auth);
                    List<EmailsEntity> inEntryls = entryls.stream().filter(e ->e.getFolder().equals("INBOX")).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(inEntryls)) {
                        expungeMailData(inEntryls,properties1,session,"INBOX");
                    }
                    List<EmailsEntity> outEntryls = entryls.stream().filter(e ->e.getFolder().equals("SENT")).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(outEntryls)) {
                        expungeMailData(outEntryls,properties1,session,"SENT");
                    }
                }
            }
        }

        return Result.ok();
    }

    public void expungeMailData(List<EmailsEntity> entryls,MailProperties properties1,Session session,String folder) {
        try {
            // 连接 IMAP 服务器
            Store store = session.getStore(properties1.getProtocol().toLowerCase());
            store.connect(properties1.getEmailAddress(), properties1.getEmailPassword());
            // 打开 INBOX 目录（可写模式）
            if ("SENT".equals(folder)) {
                folder = "Sent Items";
            }
            IMAPFolder inbox = (IMAPFolder)store.getFolder(folder);
            inbox.open(Folder.READ_WRITE);
            int totalDeleted = 0;
            List<Long> deleteIds = new ArrayList<>();
            List<Long> nullIds = new ArrayList<>();
            // 遍历 Message-ID 进行搜索并彻底删除
            for (EmailsEntity entity : entryls) {
                Message message = inbox.getMessageByUID(Long.parseLong(entity.getMsgUid()));
                if (Objects.nonNull(message)) {
                    message.setFlag(Flags.Flag.DELETED, true);
                    totalDeleted++;
                    System.out.println(" - 彻底删除邮件: " + message.getSubject());
                    deleteIds.add(entity.getId());
                } else {
                    nullIds.add(entity.getId());
                }
            }
            if (!CollectionUtils.isEmpty(nullIds)) {
                LambdaUpdateWrapper<EmailsEntity> nullUp = new LambdaUpdateWrapper<>();
                nullUp.set(EmailsEntity::getDeleteTag,2);
                nullUp.in(EmailsEntity::getId,nullIds);
                emailsService.update(nullUp);
            }
            // 确保邮件彻底删除
            if (totalDeleted > 0) {
                inbox.expunge();
                if (!CollectionUtils.isEmpty(nullIds)) {
                    LambdaUpdateWrapper<EmailsEntity> deleteUp = new LambdaUpdateWrapper<>();
                    deleteUp.set(EmailsEntity::getDeleteTag,1);
                    deleteUp.in(EmailsEntity::getId,deleteIds);
                    emailsService.update(deleteUp);
                }
                log.error("已彻底删除 " + totalDeleted + " 封邮件！");
            }
            // 关闭连接
            inbox.close(true);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping(value = "/receive_mail_pop_test")
    @ApiOperation(value = "接收邮件" )
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
    })
    public Result<?> receiveMailPOP3() throws MessagingException {
        Long currentUserId = 408L;
        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
        if (Objects.isNull(currentUserId) || Objects.isNull(smtpPop)) {
            return Result.error("请先设置邮箱账号！");
        }
        AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
        String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
        smtpPop.setEmailPassword(pass);

        MailProperties properties = new MailProperties(smtpPop);
        MailConnection mailConnection = MailConnectionUtil.receiveEmailsConnection(properties);
        if (Objects.isNull(mailConnection)) {
            return Result.error("链接失败");
        }
        Folder inbox = mailConnection.getFolder("INBOX");
        if (Objects.isNull(inbox)) {
            return Result.error("获取文件夹失败");
        }
        POP3Folder folder = (POP3Folder)inbox;
        inbox.open(Folder.READ_WRITE);

//        Folder sentItems = mailConnection.getFolder("Sent Items");
        Message [] messages = folder.getMessages();

        List<String> messageIds = Arrays.asList(
                "<1234567890@example.com>",
                "<abcdef123456@example.com>",
                "<uniqueid098765@example.com>"
        );

        SearchTerm searchTerm = new HeaderTerm("Message-ID","<tencent_573CB96038E4DCF91E167FA6@qq.com>");
        SearchTerm searchTerm1 = new MessageIDTerm("<tencent_573CB96038E4DCF91E167FA6@qq.com>");
        Message [] messages0 = folder.search(searchTerm);
        Message [] messages1 = folder.search(searchTerm1);
        for (Message message : messages) {
            String uid = folder.getUID(message);
            String msguid = message.getHeader("Message-ID")[0];
            if (message.match(searchTerm1)) {
                log.error("找到了 :"+msguid);
            }
            log.error("Message-UID = :"+uid);
            log.error("Message-subject = :"+message.getSubject());
            log.error("Message-ID = :"+msguid);
        }

        return Result.ok();
    }

    public String getRouteUrl(String resourceType) {
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)) {
            return  "/customer/customerDetail?id=${id}$";
        } else if (MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            return  "/clue/detail?id=${id}$";
        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            return  "/liaison/detail?id=${id}$";
        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            return  "/business_opportunity/detail?id=${id}$&type=detail&from=allBusiness";
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            return  "/order/detail?id=${id}$";
        }
        return "";
    }
}
