package com.jeeplus.finance.projectRecords.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.finance.projectRecords.domain.EngineeringTree;
import com.jeeplus.finance.projectRecords.domain.ProjectEngineeringInfo;
import com.jeeplus.finance.projectRecords.mapper.EngineeringTreeMapper;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 王强
 * @version 1.0
 * @date 2024-03-11 14:20
 */
@Service
@Transactional
public class EngineeringTreeService extends ServiceImpl<EngineeringTreeMapper, EngineeringTree> {

    public List<EngineeringTree> findList(ProjectEngineeringInfo projectEngineeringInfo) {
        // 查出所有的数据
        List<ProjectEngineeringInfo> list = baseMapper.findList(projectEngineeringInfo);

        // 转换成树形结构
        List<EngineeringTree> trees = new ArrayList<>();
        list.forEach(li -> {
            // 创建树形节点
            EngineeringTree tree = new EngineeringTree();
            tree.setValue(li.getId());
            tree.setLabel(li.getEngineeringName());
            tree.setChildren(new ArrayList<>());

            // 如果是根节点，则直接添加到树中
            if ("0".equals(li.getParentId())) {
                trees.add(tree);
            } else {
                // 查找父节点并添加到父节点的子节点列表中
                findParentAndAddChild(trees, li);
            }
        });

        return trees;
    }

    private void findParentAndAddChild(List<EngineeringTree> trees, ProjectEngineeringInfo node) {
        for (EngineeringTree tree : trees) {
            if (tree.getValue().equals(node.getParentId())) {
                tree.getChildren().add(nodeToTree(node));
                return;
            }
            // 递归查找父节点
            findParentAndAddChild(tree.getChildren(), node);
        }
    }

    private EngineeringTree nodeToTree(ProjectEngineeringInfo node) {
        EngineeringTree tree = new EngineeringTree();
        tree.setValue(node.getId());
        tree.setLabel(node.getEngineeringName());
        tree.setChildren(new ArrayList<>());
        return tree;
    }

}
