package com.ruoyi.project.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.project.business.domain.train.TtFileDirectory;
import com.ruoyi.project.business.domain.vo.train.FileDirectoryTreeVo;
import com.ruoyi.project.business.mapper.TtFileDirectoryMapper;
import com.ruoyi.project.business.service.train.ITtFileDirectoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fangk
 * @description 针对表【tt_file_directory】的数据库操作Service实现
 * @createDate 2024-05-20 15:28:25
 */
@Slf4j
@Service
public class TtFileDirectoryServiceImpl extends ServiceImpl<TtFileDirectoryMapper, TtFileDirectory>
        implements ITtFileDirectoryService {


    @Value("${app.dataFolder}")
    private String dataFolder;

    @PostConstruct
    public void initRoot() {
        log.info("dataFolder:{}", dataFolder);
        //FileUtils
        // 查看 id 为 0 的目录，是否存在，不存在则创建
        //TtFileDirectory ttFileDirectory = getById(0);
        boolean existRoot = baseMapper.exists(Wrappers.lambdaQuery(TtFileDirectory.class).eq(TtFileDirectory::getDerectoryName, dataFolder));
        if (!existRoot) {
            log.info("资料库根目录不存在，正在创建");
            TtFileDirectory directory = TtFileDirectory.builder().id(0L).derectoryName(dataFolder).superDirectory(null).build();
            save(directory);
            //int r = baseMapper.insertRootDirectory(dataFolder);
            log.info("资料库根目录创建成功");
        }
    }

    @Override
    //public List<Tree<String>> getDirectoryTree() {
    public List<FileDirectoryTreeVo> getDirectoryTree() {
        //TtFileDirectory root = TtFileDirectory.builder().id(0L).derectoryName(dataFolder).superDirectory(null).build();
        //TtFileDirectory root = TtFileDirectory.builder().id(0L).derectoryName(dataFolder).superDirectory(-1L).build();
        //TtFileDirectory root = TtFileDirectory.builder().id(0L).derectoryName("根目录").superDirectory(null).build();
        List<TtFileDirectory> all = list();
        //all.add(root);

        //配置
        //TreeNodeConfig config = new TreeNodeConfig();
        //// 自定义属性名 都有默认值的
        ////config.setWeightKey("order");
        ////config.setIdKey("rid");
        //// 最大递归深度
        //config.setDeep(10);

        //List<FileDirectoryTreeVo> allVos = all.stream()
        //        .map(item -> BeanUtil.copyProperties(item, FileDirectoryTreeVo.class)).collect(Collectors.toList());
        List<FileDirectoryTreeVo> treeVos = getDireTree(null, all);
        //List<FileDirectoryTreeVo> treeVos = getDireTree(-1L, all);
        //List<FileDirectoryTreeVo> tree1 = getTree(all, null);
        log.info("treeVos:{}", treeVos);


        //Map<Long, List<TtFileDirectory>> collect = all.stream().collect(Collectors.groupingBy(TtFileDirectory::getSuperDirectory));

        //Map<Long, List<FileDirectoryTreeVo>> collect = all.stream()
        //        .map(item -> BeanUtil.copyProperties(item, FileDirectoryTreeVo.class))
        //        .collect(Collectors.groupingBy(FileDirectoryTreeVo::getSuperDirectory));


        //List<Tree<String>> list = TreeUtil.build(all, null, config, (node, tree) -> {
        //    tree.setId(node.getId().toString());
        //    tree.setName(node.getDerectoryName());
        //    tree.setParentId(node.getSuperDirectory() == null ? null : node.getSuperDirectory().toString());
        //    //if (0L == node.getId()) {
        //    //    tree.putExtra("text", "根目录");
        //    //} else {
        //    //    tree.putExtra("text", node.getDerectoryName());
        //    //}
        //});

        //log.info("list:{}", list);
        return treeVos;


    }

    @Override
    public String getDataFolder(Long curFolderId) {
        TtFileDirectory ttFileDirectory = getById(curFolderId);
        if (ttFileDirectory == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(ttFileDirectory.getDerectoryName());
        // TODO 不要递归查询，稍后处理
        while (ttFileDirectory.getSuperDirectory() != null) {
            ttFileDirectory = getById(ttFileDirectory.getSuperDirectory());
            // 如果以 / 结尾，不加 /
          
            //if (!sb.toString().endsWith(File.separator)) {
            //    sb.insert(0, File.separator);
            //}
            sb.insert(0, ttFileDirectory.getDerectoryName().endsWith("/") ? ttFileDirectory.getDerectoryName() : ttFileDirectory.getDerectoryName() + "/");
            //if (!ttFileDirectory.getDerectoryName().endsWith("/")) {
            //    sb.insert(0, "/");
            //}
            //sb.insert(0, ttFileDirectory.getDerectoryName() + File.separator);
        }
        return sb.toString();
    }


    private List<FileDirectoryTreeVo> getDireTree(Long parentId, List<TtFileDirectory> all) {
        List<FileDirectoryTreeVo> children = all.stream()
                .filter(node -> null == parentId ? null == node.getSuperDirectory() : parentId.equals(node.getSuperDirectory()))
                .map(item -> {
                    FileDirectoryTreeVo vo = BeanUtil.copyProperties(item, FileDirectoryTreeVo.class);
                    vo.setChildren(getDireTree(item.getId(), all));
                    vo.setText(item.getDerectoryName());
                    vo.setValue(item.getId());

                    if (dataFolder.equals(item.getDerectoryName())) {
                        vo.setOpened(true);
                    }
                    
                    return vo;
                })
                
                .collect(Collectors.toList());
        return children;
    }

}



