package com.storlead.mail;

import com.sun.mail.imap.DefaultFolder;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import lombok.extern.log4j.Log4j2;

import javax.mail.*;
import javax.mail.search.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-05-24 14:42
 */
@Log4j2
public class QQEmailReceiver {


    private static final String UID_FILE_PATH = "uids.txt"; // 存储UID的文件路径

    public static void main(String[] args) {
        String host = "imap.exmail.qq.com"; // QQ邮箱IMAP服务器地址
        String port = "993"; // QQ邮箱IMAP服务器端口
        String userName = "chenkaiqiang@lcjs43.wecom.work"; // 你的QQ邮箱地址
        String password = "-Chenkq1992"; // 你的QQ邮箱授权码
        //
        // pnkxmvlldlrmidif
        Properties properties = new Properties();
        properties.put("mail.imap.host", host);
        properties.put("mail.imap.port", port);
        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(userName, password);
            }
        };

        Session session = Session.getInstance(properties,auth);
        try {
            IMAPStore store =  (IMAPStore) session.getStore("imap");
            store.connect();
//            Folder inbox = store.getFolder("Sent Items");
            IMAPFolder inbox = (IMAPFolder) store.getFolder("INBOX");
//            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);
            long lastUID = -1;
            // 加载已处理的UID
//            if (lastUID == -1) {
//                // 首次获取所有邮件
//                 dateStr = "2001-05-28";
//            } else {
//                 dateStr = "2024-05-28"; // 替换为你需要的日期
//            }
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Date date = dateFormat.parse(dateStr);
//            SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GT, date);
            //<tencent_49C3E81C77FD0CAB1F16CA6F@qq.com>
//            SearchTerm searchTerm = new HeaderTerm("Message-ID","<tencent_49C3E81C77FD0CAB1F16CA6F@qq.com>");

            SearchTerm searchTerm = new HeaderTerm("Message-ID","<tencent_573CB96038E4DCF91E167FA6@qq.com>");
            SearchTerm searchTerm1 = new MessageIDTerm("<tencent_573CB96038E4DCF91E167FA6@qq.com>");
            long start = System.currentTimeMillis();

            Message [] megs = inbox.getMessages();
            Message [] messages0 = inbox.search(searchTerm);
            Message [] messages1 = inbox.search(searchTerm,megs);
            Message [] messages2 = inbox.search(searchTerm1,megs);
            System.out.println("----耗时"+(System.currentTimeMillis() - start));
            long maxUID = lastUID;
            for (Message message : megs) {
                long uid = inbox.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);
            }
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Set<Long> loadProcessedUIDs() {
        Set<Long> uids = new HashSet<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(UID_FILE_PATH))) {
            String line;
            while ((line = reader.readLine()) != null) {
                uids.add(Long.parseLong(line));
            }
        } catch (IOException e) {
            // 文件不存在或读取错误时返回空集合
        }
        return uids;
    }

    // 保存已处理的UID
    private static void saveProcessedUIDs(Set<Long> uids) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(UID_FILE_PATH))) {
            for (Long uid : uids) {
                writer.write(uid.toString());
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void saveAttachment(BodyPart bodyPart) throws Exception {
        String fileName = bodyPart.getFileName();
        int size = bodyPart.getSize();
        InputStream is = bodyPart.getInputStream();
//        File file = new File("attachments/" + fileName); // 存储附件的文件夹路径
//        try (FileOutputStream fos = new FileOutputStream(file)) {
//            byte[] buffer = new byte[4096];
//            int bytesRead;
//            while ((bytesRead = is.read(buffer)) != -1) {
//                fos.write(buffer, 0, bytesRead);
//            }
//        }
        System.out.println("Saved attachment: " + fileName);
    }


    private static String parseMultipart(Multipart multipart) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (bodyPart.isMimeType("text/plain")) {
                stringBuilder.append(bodyPart.getContent());
            } else if (bodyPart.isMimeType("text/html")) {
                stringBuilder.append(bodyPart.getContent());
            } else if (bodyPart.isMimeType("multipart/alternative")) {
                parseMultipart((Multipart) bodyPart.getContent());
            } else if (bodyPart.isMimeType("multipart/*")) {
                parseMultipart((Multipart) bodyPart.getContent());
            }else if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                saveAttachment(bodyPart);
            }
        }
        return stringBuilder.toString();
    }
}
