package com.bonus.zlpt.home.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.bonus.zlpt.equip.api.domain.TypeInfo;
import com.bonus.zlpt.home.mapper.MaTypeInfoMapper;
import com.bonus.zlpt.home.service.MaTypeInfoSevice;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class MaTypeInfoServiceImpl implements MaTypeInfoSevice {

    @Resource
    private MaTypeInfoMapper maTypeInfoMapper;


    @Override
    public List<Tree<Long>> getMaTypeInfoList() {
        List<TypeInfo> maTypeInfoList = maTypeInfoMapper.getMaTypeInfoList();
        List<TreeNode<Long>> collect = maTypeInfoList
                .stream().map(getNodeFunction()).collect(Collectors.toList());
        //List<TypeInfo> menuTree = buildMenuTree(maTypeInfoList);
        return TreeUtil.build(collect,0L);
    }


    /**
     * 构建菜单树
     * @param
     * @return
     */
    private List<TypeInfo> buildMenuTree(List<TypeInfo> maTypeInfoList) {
        //用于存放根菜单
        List<TypeInfo> rootMenus = new ArrayList<>();
        Map<Long, List<TypeInfo>> menuMap = new HashMap<>();

        // 将菜单按照父菜单ID分组,放在menuMap中
        for (TypeInfo maTypeInfo : maTypeInfoList) {
            Long parentId = maTypeInfo.getParentId() ;
            if (!menuMap.containsKey(parentId)) {
                menuMap.put(parentId, new ArrayList<>());
            }
            menuMap.get(parentId).add(maTypeInfo);
        }

        // 从根菜单开始，构建菜单树
        rootMenus.addAll(menuMap.getOrDefault(0, new ArrayList<>()));
        System.out.println("rootMenus:   "+rootMenus);
        for (TypeInfo maTypeInfo : maTypeInfoList) {
            buildSubMenuTree(maTypeInfo, menuMap);
        }

        return rootMenus;
    }

    /**
     * 根据父菜单节点逐级构建子树，按顺序排列
     * @param maTypeInfo
     * @param menuMap
     */
    private void buildSubMenuTree(TypeInfo maTypeInfo, Map<Long, List<TypeInfo>> menuMap) {
        //获取根菜单的子节点列表
        List<TypeInfo> children = menuMap.getOrDefault(maTypeInfo.getTypeId(), new ArrayList<>());
        //Collections.sort(children);
        maTypeInfo.setChildren(children);
        for (TypeInfo maTypeInfoChildren : children) {
            buildSubMenuTree(maTypeInfoChildren, menuMap);
        }
    }

    private Function<TypeInfo, TreeNode<Long>> getNodeFunction() {

        return typeInfo -> {
            TreeNode<Long> node = new TreeNode<>();
            node.setId(typeInfo.getTypeId());
            node.setName(typeInfo.getTypeName());
            node.setParentId(typeInfo.getParentId());
            node.setWeight(typeInfo.getSort());
            return node;
        };
    }
}
