package com.youlai.boot.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.util.SystemUtil;
import com.youlai.boot.system.model.entity.DirectoryNode;
import com.youlai.boot.system.model.entity.DirectoryTree;
import com.youlai.boot.system.model.entity.FolderNode;
import com.youlai.boot.system.model.form.DirForm;
import com.youlai.boot.system.service.ConfigService;
import com.youlai.boot.system.service.FolderNodeService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class FolderNodeServiceImpl implements FolderNodeService {


    private static final Logger log = LoggerFactory.getLogger(FolderNodeServiceImpl.class);

    private final ConfigService configService;


    private final RedisTemplate<String, Object> redisTemplate;


    @Override
    public List<Record> getRecordListByFolderName(String folderName, String type) {
        return List.of();
    }

    @Override
    public List<DirectoryNode> getLeafDirNode() {
        String rootPath = configService.getSystemConfig(SystemConstants.UPLOAD_PATH).toString();
        File rootDir = new File(rootPath);
        List<File> leafFolders = DirectoryTree.getLeafFolders(rootDir);

        return leafFolders.stream().map(file -> {
            DirectoryNode directoryNode = new DirectoryNode();
            directoryNode.setLabel(file.getName());
            directoryNode.setAbsolutePath(file.getAbsolutePath());
            return directoryNode;
        }).toList();
    }




    @Override
    public DirectoryNode getFolderNode(String pageType) {
        DirectoryNode directoryNode;
        directoryNode = (DirectoryNode) redisTemplate.opsForHash().get(RedisConstants.FOLDER_PREFIX, pageType);
        if (directoryNode == null) {
            String path = configService.getSystemConfig(pageType).toString();
            File rootDir = new File(path);
            directoryNode = DirectoryTree.getDirectoryNode(rootDir);// -1表示根目录没有父目录
            redisTemplate.opsForHash().put(RedisConstants.FOLDER_PREFIX, pageType, directoryNode);
        }
//        directoryNode = DirectoryTree.directoryMap.get(pageType);
//        if (directoryNode == null) {
//            String path = configService.getSystemConfig(pageType).toString();
//            File rootDir = new File(path);
//            directoryNode = DirectoryTree.buildDirectoryTree(rootDir, -1);// -1表示根目录没有父目录
//            DirectoryTree.directoryMap.put(pageType, directoryNode);
//            return directoryNode;
//        }
        return directoryNode;
    }

    private @NotNull DirectoryNode refreshDir(String pageType) {
        String path = configService.getSystemConfig(pageType).toString();
        File rootDir = new File(path);
        DirectoryNode directoryNode = DirectoryTree.getDirectoryNode(rootDir);// -1表示根目录没有父目录
        redisTemplate.opsForHash().put(RedisConstants.FOLDER_PREFIX, pageType, directoryNode);
        return directoryNode;
    }


    @Override
    public void mkDir(DirForm dirForm) {

        String path = getPath(dirForm);
        Path newDirectoryPath = Paths.get(path, dirForm.getDirName());

        try {
            // 尝试创建目录
            if(SystemUtil.containsChinese(dirForm.getNewDirName())) throw new BusinessException("暂不支持中文路径符号");

            Files.createDirectory(newDirectoryPath);
            refreshDir(dirForm.getPageType());
        } catch (FileAlreadyExistsException e) {
            // 处理目录已存在的情况
            throw new RuntimeException("文件夹创建失败，已存在同名文件夹！ " + newDirectoryPath);
        } catch (IOException e) {
            // 处理其他IO异常
            log.error(e.getMessage(), e);
        }
    }
    @Override
    public String getPath(DirForm dirForm) {

        String pageType = dirForm.getPageType();

        DirectoryNode rootNode = getFolderNode(pageType);

        DirectoryNode curNode = DirectoryTree.findNodeById(rootNode, dirForm.getDirId());

        log.info("curNode is ....{}",JSON.toJSONString(curNode));

        List<String> pathToRoot = DirectoryTree.getPathToRoot(rootNode, curNode);

        log.info("pathToRoot is ....{}",JSON.toJSONString(pathToRoot));

        StringBuilder path = new StringBuilder();

        //        假如直接 pathPrefix+path 这里引用了两次 菜单目录 与 菜单下的根目录，所以 i=1 例如 D:\temp\front\pac\pac\5.0前端包\新的\新的\123

        for (int i = 1; i < pathToRoot.size(); i++) {
            path.append(File.separator).append(pathToRoot.get(i));
        }
        log.info("path is ....{}",JSON.toJSONString(path));

        String pathPrefix = configService.getSystemConfig(pageType).toString();

        log.info("pathPrefix is ....{}",JSON.toJSONString(pathPrefix));

        return pathPrefix + path;
    }

    @Override
    public void rmDir(DirForm dirForm) {
        try {
            Path path = Paths.get(getPath(dirForm));
            Files.deleteIfExists(path);
            refreshDir(dirForm.getPageType());

        } catch (java.nio.file.DirectoryNotEmptyException e) {
            throw new RuntimeException("无法直接删除！" + e.getMessage() + " 目录不为空！");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("文件删除失败！" + e.getMessage());


        }


//
//    public static FolderNode buildFolderTree(String rootDirPath) {
//        File rootDir = new File(rootDirPath);
//        if (!rootDir.isDirectory()) {
//            throw new IllegalArgumentException("The provided path is not a directory.");
//        }
//        return traverseDirectory(rootDir);
//    }
//    private static int currentId = 1; // 用于生成唯一的文件夹ID
//    private static Map<String, FolderNode> folderMap = new HashMap<>();
//    private static int traverseDirectory(File dir, int parentId) {
//        String dirName = dir.getName();
//        FolderNode currentNode = new FolderNode(dirName, currentId, parentId,null);
//        folderMap.put(dirName, currentNode);
//
//        File[] files = dir.listFiles();
//        if (files != null) {
//            for (File file : files) {
//                if (file.isDirectory()) {
//                    currentId++;
//                    int childId = traverseDirectory(file, currentId - 1);
//                    currentNode.addChild(folderMap.get(file.getName()));
//                }
//            }
//        }
//
//        return currentId - 1; // 返回当前节点的ID
//    }


    }

    @Override
    public void renameDir(DirForm dirForm) {

        String path = getPath(dirForm);

        Path sourcePath = Paths.get(path);
        Path targetPath = sourcePath.getParent().resolve(dirForm.getNewDirName());
        try {

            if(SystemUtil.containsChinese(dirForm.getNewDirName())) throw new BusinessException("暂不支持中文路径符号");

            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            refreshDir(dirForm.getPageType());
        }catch (AccessDeniedException e){
            log.error(e.getMessage(), e);
            throw new RuntimeException("文件重命名失败,系统权限不足！" + e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage(), e);
            throw new RuntimeException("文件重命名失败！" + e.getMessage());
        }

    }
}
