package com.njcn.product.event.transientes.job;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: cdf
 * @CreateTime: 2025-10-16
 * @Description: 定时同步暂降数据包
 */
@Component
@EnableScheduling
@RequiredArgsConstructor
public class ScheduledEvent  implements SchedulingConfigurer {

//    @Value("${}")
    private final String cronStr = "0 0 */2 * * ?";

    // 源文件夹路径
    private final String sourceFolderPath = "D:\\";
    // 压缩文件输出路径
    private final String zipOutputPath = "./output_zips";
    // 最终存放压缩文件的目录
    private final String finalDestination = "./archive";



    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                () -> dataToFile(),
                triggerContext -> {
                    CronTrigger trigger = new CronTrigger(cronStr);
                    return trigger.nextExecutionTime(triggerContext);
                }
        );
    }

    public void dataToFile() {
        try {
        // 1. 创建临时文件夹并写入测试文件
        String folderName = "data_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        Path sourceDir = Paths.get(sourceFolderPath, folderName);
        Files.createDirectories(sourceDir);

        // 模拟生成文件（例如：log.txt）
        Path testFile = sourceDir.resolve("log.txt");
        Files.write(testFile, "This is a test log file.".getBytes(), StandardOpenOption.CREATE);

        // 2. 压缩文件夹
        Path zipOutputDir = Paths.get(zipOutputPath);
        Files.createDirectories(zipOutputDir);
        Path zipFile = zipOutputDir.resolve(folderName + ".zip");

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile.toFile()))) {
            Files.walk(sourceDir)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        String zipEntryName = sourceDir.relativize(path).toString();
                        try {
                            zos.putNextEntry(new ZipEntry(zipEntryName));
                            Files.copy(path, zos);
                            zos.closeEntry();
                        } catch (IOException e) {
                            throw new RuntimeException("Failed to add file to zip: " + path, e);
                        }
                    });
        }

        // 3. 移动压缩文件到最终目录
        Path finalDir = Paths.get(finalDestination);
        Files.createDirectories(finalDir);
        Path targetPath = finalDir.resolve(zipFile.getFileName());
        Files.move(zipFile, targetPath, StandardCopyOption.REPLACE_EXISTING);

        // 4. 删除临时文件夹（可选）
        deleteDirectory(sourceDir.toFile());

        System.out.println("Task completed: " + targetPath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 递归删除目录
     */
    private void deleteDirectory(File directory) {
        File[] allContents = directory.listFiles();
        if (allContents != null) {
            for (File file : allContents) {
                deleteDirectory(file);
            }
        }
        directory.delete();
    }
}
