package com.bonus.sgzb.base.service.impl;

import com.bonus.sgzb.base.domain.BmUnitPerson;
import com.bonus.sgzb.base.mapper.DeptMapper;
import com.bonus.sgzb.base.service.DeptService;
import com.bonus.sgzb.system.api.domain.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<SysDept> getDeptList() {

        List<SysDept> deptList = deptMapper.getDeptList();

        List<SysDept> menuTree = buildMenuTree(deptList);
        return menuTree;
    }

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

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

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

        return rootMenus;
    }

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