package com.storlead.mail.controller;//package com.storlead.sales.mail;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.storlead.framework.common.util.DateUtils;
//import com.storlead.framework.common.util.encryptor.AccessKeyEncryptor;
//import com.storlead.framework.util.LoginUserUtil;
//import com.storlead.framework.common.result.Result;
//import com.storlead.mail.connection.MailConnection;
//import com.storlead.mail.connection.client.MailConnectionUtil;
//import com.storlead.mail.connection.config.MailProperties;
//import com.storlead.mail.entity.EmailsEntity;
//import com.storlead.mail.entity.MailAttachmentEntity;
//import com.storlead.mail.entity.SmtpPopSettingsEntity;
//import com.storlead.mail.pojo.MailDTO;
//import com.storlead.mail.pojo.SendMailDTO;
//import com.storlead.mail.properties.MailFileProperties;
//import com.storlead.mail.service.EmailsService;
//import com.storlead.mail.service.MailAttachmentService;
//import com.storlead.mail.service.SmtpPopSettingsService;
//import com.sun.mail.imap.IMAPFolder;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiResponse;
//import io.swagger.annotations.ApiResponses;
//import lombok.extern.log4j.Log4j2;
////import org.springframework.mail.javamail.JavaMailSender;
//import org.springframework.mail.javamail.MimeMessageHelper;
//import org.springframework.util.CollectionUtils;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.annotation.Resource;
//import javax.mail.*;
//import javax.mail.internet.InternetAddress;
//import javax.mail.internet.MimeMessage;
//import javax.mail.internet.MimeUtility;
//import javax.mail.search.ComparisonTerm;
//import javax.mail.search.ReceivedDateTerm;
//import javax.mail.search.SearchTerm;
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.text.SimpleDateFormat;
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * @program: sp-sales-platform
// * @description:
// * @author: chenkq
// * @create: 2024-05-29 16:02
// */
//@RestController
//@RequestMapping("/mail")
//@Api(tags = "邮件: 邮件管理")
//public class SmtpPopMailApiController {
//
////    @Resource
////    private JavaMailSender mailSender;
//
//    @Resource
//    private EmailsService emailsService;
//
//    @Resource
//    private MailFileProperties mailFileProperties;
//
//    @Resource
//    private MailAttachmentService mailAttachmentService;
//
//    @Resource
//    private SmtpPopSettingsService smtpPopSettingsService;
//
//
//    @PostMapping(value = "/pageList")
//    @ApiOperation(value = "获取邮件" )
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
//    })
//    public Result<?> pageList(com.storlead.common.object.Page dto) {
//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
//
//        if (Objects.isNull(currentUserId) && Objects.nonNull(smtpPop)) {
//            return Result.result(null);
//        }
//        Page<EmailsEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());
//        LambdaQueryWrapper<EmailsEntity> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(EmailsEntity::getOwnerBy,currentUserId);
//        queryWrapper.eq(EmailsEntity::getFrom,smtpPop.getEmailAddress());
//        IPage<EmailsEntity> pageList = emailsService.page(page,queryWrapper);
//        return Result.result(pageList);
//    }
//
//    @PostMapping(value = "/sendMail")
//    @ApiOperation(value = "发送邮件" )
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
//    })
//    public Result<?> sendMail(SendMailDTO dto) {
//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
//        AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
//        String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
//        smtpPop.setEmailPassword(pass);
//        if (Objects.isNull(currentUserId) && Objects.nonNull(smtpPop)) {
//            return Result.result(null);
//        }
//        try {
//           Session session = getSendEmailsSession(smtpPop);
//            try {
//
//                InternetAddress [] froms = new InternetAddress[dto.getRecipientls().size()];
//                for (int i = 0; i < dto.getRecipientls().size(); i++) {
//                    froms[i] = new InternetAddress(dto.getRecipientls().get(i));
//                }
//                if (CollectionUtils.isEmpty(dto.getFiles())) {
//                    Message message = new MimeMessage(session);
//                    message.setFrom(new InternetAddress(smtpPop.getEmailAddress()));
//                    message.setRecipients(Message.RecipientType.TO, froms);
//                    message.setSubject(dto.getSubject());
//                    message.setText(dto.getContent());
//                    Transport.send(message);
//                } else {
////                    MimeMessage message = mailSender.createMimeMessage();
////                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
////                    helper.setFrom(new InternetAddress(smtpPop.getEmailAddress()));
////                    helper.setTo(froms);
////                    helper.setSubject(dto.getSubject());
////                    helper.setText(dto.getContent());
////                    List<MultipartFile> files = dto.getFiles();
////                    for (MultipartFile multipartFile : files) {
////                        File file = multipartFile.getResource().getFile();
////                        helper.addAttachment(file.getName(), file);
////                    }
//                }
//            }catch (Exception e) {
//                log.error("getSendEmailsSession -error",e);
//            }
//            return Result.ok();
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("send sendMail -error",e);
//        }
//        return Result.ok();
//    }
//
//
//    @PostMapping(value = "/receiveMail")
//    @ApiOperation(value = "接收邮件" )
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
//    })
//    public Result<?> receiveMail(MailDTO dto) {
//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
//        if (Objects.isNull(currentUserId) && Objects.nonNull(smtpPop)) {
//            return Result.error("请先设置邮箱账号！");
//        }
//
//        AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
//        String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
//        smtpPop.setEmailPassword(pass);
//        receiveEmails(smtpPop, "INBOX");
////        receiveEmails(smtpPop, "Sent Items");
////        receiveEmails(smtpPop, "Drafts");
////        receiveEmails(smtpPop, "Trash");
//        return Result.ok();
//    }
//
//
//    @PostMapping(value = "/receiveMail1")
//    @ApiOperation(value = "接收邮件" )
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "", response = SmtpPopSettingsEntity.class)
//    })
//    public Result<?> receiveMail1(MailDTO dto) {
//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
//        if (Objects.isNull(currentUserId) && Objects.nonNull(smtpPop)) {
//            return Result.error("请先设置邮箱账号！");
//        }
//        return Result.ok();
//    }
//
//    private void receiveEmails(SmtpPopSettingsEntity smtpPop, String folderName) {
//        MailProperties properties = new MailProperties(smtpPop);
//        MailConnection mailConnection = MailConnectionUtil.receiveEmailsConnection(properties);
//        if (Objects.isNull(mailConnection)) {
//            return;
//        }
//        List<EmailsEntity> entities = new ArrayList<>();
//
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("smtp_pop_id",smtpPop.getId());
//        queryWrapper.eq("folder",folderName);
//        queryWrapper.select("max(recipient_date) as recipientDate");
//        Map<String, Date> qv = emailsService.getMap(queryWrapper);
//
//        QueryWrapper queryMsgIdWp = new QueryWrapper<>();
//        queryMsgIdWp.select("msg_uid");
//        queryMsgIdWp.eq("folder",folderName);
//        queryMsgIdWp.eq("smtp_pop_id",smtpPop.getId());
//        queryMsgIdWp.last("order by msg_uid desc limit 100");
//
//        List<String> dis = emailsService.listObjs(queryMsgIdWp);
//        List<Long> msgUids = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(dis)) {
//            msgUids = dis.stream().map(Long::valueOf).collect(Collectors.toList());
//        }
//        try {
//            Store store = mailConnection.getStore();
//            Folder inbox = store.getFolder(folderName);
//            inbox.open(Folder.READ_WRITE);
//            Date beginDate = null;
//            if (!CollectionUtils.isEmpty(qv) && Objects.nonNull(qv.get("recipientDate"))) {
//                beginDate = qv.get("recipientDate");
//            }
//            if (beginDate == null) {
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                String dateStr = "2024-03-28"; // 替换为你需要的日期
//                beginDate = dateFormat.parse(dateStr);
//            }
//
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Date date = dateFormat.parse("2024-05-28");
//
//            SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GT, date);
//            Message[] messages = inbox.search(searchTerm);
//            for (Message message : messages) {
//                Long mesId = getMessageId(message,inbox);
//                if (!CollectionUtils.isEmpty(msgUids) && msgUids.contains(mesId)) {
//                    continue;
//                }
//                msgUids.add(mesId);
//                EmailsEntity entity = convertMessageToEmailVo(message,smtpPop);
//                entity.setSmtpPopId(smtpPop.getId());
//                entity.setMsgUid(mesId);
//                entity.setFolder(folderName);
//                entities.add(entity);
//                emailsService.save(entity);
//
//                String downloadDir = mailFileProperties.getPath().getPath()+File.separator+smtpPop.getEmailAddress()+File.separator;
//                downloadAttachmentFromMessage(message,downloadDir,entity.getId());
//            }
//            inbox.close(false);
//            mailConnection.close();
//        }catch (Exception e) {
//            log.error("receiveEmails - error =",e);
//            mailConnection.close();
//        }
//
//    }
//
//    private Session getSendEmailsSession(SmtpPopSettingsEntity smtpPop) {
//
//        Properties properties = new Properties();
//        properties.put("mail.smtp.host", smtpPop.getSmtpServer());
//        properties.put("mail.smtp.port", smtpPop.getSmtpPort());
//        properties.put("mail.smtp.auth", "true");
//        properties.put("mail.user", smtpPop.getEmailAddress());
//        properties.put("mail.smtp.starttls.enable",smtpPop.getUseTls());
//        properties.put("mail.smtp.ssl.enable", smtpPop.getUseSsl());
//
//        Session session = Session.getInstance(properties, new Authenticator() {
//            protected PasswordAuthentication getPasswordAuthentication() {
//                return new PasswordAuthentication(smtpPop.getEmailAddress(), smtpPop.getEmailPassword());
//            }
//        });
//        return session;
//    }
//
//        private static Long getMessageId(Message message, Folder folder) throws MessagingException {
//        if (folder instanceof IMAPFolder) {
//            IMAPFolder imapFolder = (IMAPFolder) folder;
//            return  imapFolder.getUID(message);
//        } else {
//            return null;
//        }
//    }
//
//
//    private EmailsEntity convertMessageToEmailVo(Message message,SmtpPopSettingsEntity smtpPop) throws MessagingException, IOException {
//
//        EmailsEntity entity = new EmailsEntity();
//        String subject =  MimeUtility.decodeText(message.getSubject());
//        entity.setSubject(subject);
//
//        Map<String,String>  fromMap = decodeAndPrintAddresses(message.getFrom());
//        entity.setFrom(mapKeyToString(fromMap));
//        entity.setFromName(mapValueToString(fromMap));
//
//        Map<String,String>  toMap = decodeAndPrintAddresses(message.getRecipients(Message.RecipientType.TO));
//        entity.setRecipient(mapKeyToString(toMap));
//        entity.setRecipientName(mapValueToString(toMap));
//
//        if (Objects.nonNull(message.getSentDate())) {
//            entity.setSentDate(message.getSentDate());
//        }
//
//        if (Objects.nonNull(message.getReceivedDate())) {
//            entity.setRecipientDate(message.getReceivedDate());
//        }
//        boolean isSeen = message.isSet(Flags.Flag.SEEN);
//        entity.setIsRead(isSeen);
//
////      Map<String,String>  ccMap = decodeAndPrintAddresses(message.getRecipients(Message.RecipientType.CC));
////      Map<String,String>  bccMap = decodeAndPrintAddresses(message.getRecipients(Message.RecipientType.BCC));
//        Object content = message.getContent();
//        if (content instanceof String) {
//            entity.setContent(message.getContent().toString());
//        } else if (content instanceof Multipart) {
//            Multipart multipart = (Multipart) content;
//            String str = parseMultipart(multipart);
//            entity.setContent(str);
//        }
//        return entity;
//    }
//
//    private String parseMultipart(Multipart multipart) {
//        try {
//            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());
//                }
//            }
//            return stringBuilder.toString();
//        }catch (Exception e) {
//            return "";
//        }
//    }
//
//    private void downloadAttachmentFromMessage(Message message, String downloadDir, long emailId) {
//        try {
//            Object content = message.getContent();
//            if (content instanceof Multipart) {
//                Multipart multipart = (Multipart) content;
//                for (int i = 0; i < multipart.getCount(); i++) {
//                    BodyPart bodyPart = multipart.getBodyPart(i);
//                    if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
//                        saveAttachment(bodyPart, downloadDir, emailId);
//                    }
//                }
//            }
//        }catch (Exception e) {
//            log.error("downloadAttachmentFromMessage -- error = ",e);
//        }
//    }
//
//    private void saveAttachment(BodyPart bodyPart,  String downloadDir, long emailId) throws MessagingException, IOException {
//        String fileName = bodyPart.getFileName();
//        fileName = MimeUtility.decodeText(fileName);
//        String path = DateUtils.date2Str(new Date(), DateUtils.date_yyyy_mm);
//        // 如果不存在这创建路径
//        downloadDir = downloadDir + File.separator + path;
//        if (!new File(downloadDir).exists()) {
//            new File(downloadDir).mkdirs();
//        }
//        File file = new File(downloadDir +  File.separator +fileName);
//        try (FileOutputStream output = new FileOutputStream(file)) {
//            bodyPart.getInputStream().transferTo(output);
//        }
//        System.out.println("Saved attachment: " + file.getAbsolutePath());
//        saveAttachmentToDatabase(file, emailId);
//    }
//
//    private void saveAttachmentToDatabase(File file, long emailId) {
//
//        String fileName = file.getName();
//        MailAttachmentEntity attachment = new MailAttachmentEntity();
//        attachment.setEmailId(emailId);
//        attachment.setFileName(fileName);
//        attachment.setFilePath(file.getAbsolutePath());
//        attachment.setFilePath(file.getAbsolutePath());
//
//        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
//        attachment.setFileExt(fileExtension);
//        attachment.setFileSize(file.length());
//        mailAttachmentService.save(attachment);
//    }
//
//    private static String formatDate(Date date) {
//        if (date == null) return "N/A";
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        return sdf.format(date);
//    }
//
//    private static String decodeAddresses(Address [] addresses) throws MessagingException {
//        try {
//            if (addresses == null) return "[]";
//            String[] decodedAddresses = new String[addresses.length];
//            for (int i = 0; i < addresses.length; i++) {
//                decodedAddresses[i] = MimeUtility.decodeText(addresses[i].toString());
//            }
//            return Arrays.toString(decodedAddresses);
//        }catch (Exception e) {
//            return "";
//        }
//    }
//
//    private static Map<String,String> decodeAndPrintAddresses(Address[] addresses) throws MessagingException, IOException {
//
//        Map<String,String> map = new HashMap<>();
//        if (addresses == null) return new HashMap<>();
//        StringBuilder decodedAddresses = new StringBuilder();
//        for (Address address : addresses) {
//            InternetAddress internetAddress = (InternetAddress) address;
//            String personal = internetAddress.getPersonal();
//            String email = internetAddress.getAddress();
//            if (personal != null) {
//                personal = MimeUtility.decodeText(personal);
//            }
//            map.put(email,(personal != null ? personal : "N/A"));
////            decodedAddresses.append("[Name: ").append(personal != null ? personal : "N/A").append(", Email: ").append(email).append("] ");
//        }
//        return map;
//    }
//
//    private static String mapKeyToString(Map<String,String> map) {
//        if (map == null) return "";
//        return map.entrySet().stream()
//                .map(entry -> entry.getKey())
//                .collect(Collectors.joining(","));
//    }
//
//    private static String mapValueToString(Map<String,String> map) {
//        if (map == null) return "";
//        return map.entrySet().stream()
//                .map(entry -> entry.getValue())
//                .collect(Collectors.joining(","));
//    }
//}
