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

import com.bonus.zlpt.common.core.domain.equip.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;

@Service
public class MaTypeInfoServiceImpl implements MaTypeInfoSevice {

    @Resource
    private MaTypeInfoMapper maTypeInfoMapper;


    @Override
    public List<TypeInfo> getMaTypeInfoList() {
        List<TypeInfo> maTypeInfoList = maTypeInfoMapper.getMaTypeInfoList();

        List<TypeInfo> menuTree = buildMenuTree(maTypeInfoList);
        return menuTree;
    }


    /**
     * 构建菜单树
     * @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() != ' ' ? maTypeInfo.getParentId() : 0;
            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 : rootMenus) {
            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);
        }
    }
}
