package com.goldenwater.gx.service.impl;

import com.goldenwater.gx.domain.DocDirectory;
import com.goldenwater.gx.mapper.DocDirectoryMapper;
import com.goldenwater.gx.service.IDocDirectoryService;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("docDirectoryService")
public class DocDirectoryServiceImpl implements IDocDirectoryService {

    @Resource
    private DocDirectoryMapper docDirectoryMapper;

    @Override
    public List<DocDirectory> selectDirectoryTree() {
        List<DocDirectory> allDirectories = docDirectoryMapper.selectDirectoryTree();
        return buildTree(allDirectories, 0L);
    }

    @Override
    public List<DocDirectory> selectDirectoryByParentId(Long parentId) {
        return docDirectoryMapper.selectDirectoryByParentId(parentId);
    }

    @Override
    public DocDirectory selectDirectoryById(Long id) {
        return docDirectoryMapper.selectDirectoryById(id);
    }

    @Override
    public int insertDirectory(DocDirectory directory) {
        return docDirectoryMapper.insertDirectory(directory);
    }

    @Override
    public int updateDirectory(DocDirectory directory) {
        return docDirectoryMapper.updateDirectory(directory);
    }

    @Override
    public int deleteDirectoryById(Long id) {
        return docDirectoryMapper.deleteDirectoryById(id);
    }

    private List<DocDirectory> buildTree(List<DocDirectory> directories, Long parentId) {
        Map<Long, List<DocDirectory>> map = directories.stream()
                .collect(Collectors.groupingBy(DocDirectory::getParentId));

        return buildTreeRecursive(map, parentId);
    }

    private List<DocDirectory> buildTreeRecursive(Map<Long, List<DocDirectory>> map, Long parentId) {
        List<DocDirectory> result = new ArrayList<>();
        List<DocDirectory> children = map.get(parentId);
        
        if (children != null) {
            for (DocDirectory child : children) {
                child.setChildren(buildTreeRecursive(map, child.getId()));
                result.add(child);
            }
        }
        
        return result;
    }
}
