package cn.edu.whu.boot.photozip.service.impl;

import cn.edu.whu.boot.photozip.mapper.PhotoZipMapper;
import cn.edu.whu.boot.photozip.service.PhotoZipService;
import cn.edu.whu.boot.photozip.util.ZipUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.*;
import java.util.*;

@Service
public class PhotoZipServiceImpl implements PhotoZipService {

    private final PhotoZipMapper photoZipMapper;

    @Value("${photozippath}")
    private String storagePath;

    @Value("${MediaPath}")
    private String mediaPath;

    public PhotoZipServiceImpl(PhotoZipMapper photoZipMapper) {
        this.photoZipMapper = photoZipMapper;
    }

    @Override
    @Transactional
    public Path createPhotoZip(String tableName, String taskName) {
        try {
            // 设置任务状态为进行中
            photoZipMapper.insertOrUpdateZipTask(taskName, "进行中");

            // 查询照片路径
            List<String> filePaths = photoZipMapper.getMediaPathsByTask(tableName);
            if (filePaths == null || filePaths.isEmpty()) {
                throw new RuntimeException("未找到任务相关的照片路径: " + taskName);
            }

            // 提取 task_xx 目录路径
            Path fullPath = filePaths.stream()
                    .map(Paths::get)
                    .map(path -> {
                        for (Path part : path) {
                            if (part.toString().startsWith("task_")) {
                                return Paths.get(mediaPath, part.toString());
                            }
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("未找到任何 task_xx 目录"));

            System.out.println("压缩目录：" + fullPath.toString());

            // 创建临时目录
            Path tempDir = Files.createTempDirectory("zip_temp");
            Path tempTaskDir = tempDir.resolve(fullPath.getFileName());
            Files.createDirectories(tempTaskDir);

            // 查询用户映射表（user_id -> real_name）
            Map<String, String> userMap = getUserMap();

            // 遍历目录
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(fullPath)) {
                for (Path userDir : stream) {
                    String folderName = userDir.getFileName().toString();

                    if (Files.isDirectory(userDir) && folderName.startsWith("user_")) {
                        String userId = folderName.substring(5); // 提取 ID
                        String username = userMap.getOrDefault(userId, "unknown");

                        // 重命名为 user_1(张三)
                        Path newUserDir = tempTaskDir.resolve(folderName + "(" + username + ")");
                        Files.createDirectories(newUserDir);  // 创建目录

                        // 递归复制文件到新的目录
                        copyFilesRecursively(userDir, newUserDir);
                    } else {
                        // 非 user_ 开头的目录/文件直接复制
                        Files.copy(userDir, tempTaskDir.resolve(userDir.getFileName()), StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            }

            // 创建 zip 文件
            String zipFileName = taskName + "_photo.zip";
            Path zipFilePath = Paths.get(storagePath, zipFileName);
            ZipUtil.createZip(tempTaskDir.toString(), zipFilePath.toString());

            // 更新状态为已完成
            photoZipMapper.insertOrUpdateZipTask(taskName, "已完成");

            return zipFilePath;

        } catch (Exception e) {
            photoZipMapper.insertOrUpdateZipTask(taskName, "任务失败");
            throw new RuntimeException("压缩任务失败: " + e.getMessage(), e);
        }
    }

    // 递归复制文件
    private void copyFilesRecursively(Path sourceDir, Path targetDir) throws IOException {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourceDir)) {
            for (Path entry : stream) {
                if (Files.isDirectory(entry)) {
                    Path newDir = targetDir.resolve(entry.getFileName());
                    Files.createDirectories(newDir); // 创建子目录
                    copyFilesRecursively(entry, newDir); // 递归复制
                } else {
                    Files.copy(entry, targetDir.resolve(entry.getFileName()), StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }
    }

    @Override
    public Resource getZipFileResource(Path zipFilePath) {
        return new FileSystemResource(zipFilePath);
    }

    @Override
    public String getTaskStatus(String taskName) {
        String taskStatus = photoZipMapper.getZipTaskStatus(taskName);
        return taskStatus != null ? taskStatus : "未开始";
    }

    @Override
    public Map<String, String> getUserMap() {
        List<Map<String, Object>> userList = photoZipMapper.getUserMap(); // 查询 id, real_name
        Map<String, String> userMap = new HashMap<>();
        for (Map<String, Object> user : userList) {
            String userId = String.valueOf(user.get("id"));
            String userName = String.valueOf(user.get("real_name"));
            if (userId != null && userName != null) {
                userMap.put(userId, userName);
            }
        }
        return userMap;
    }
}
