package com.xdap.self_development.service.impl;


import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.domain.pojo.ModelMenuDictionaryPojo;
import com.xdap.self_development.domain.view.MenuListView;
import com.xdap.self_development.service.ModelMenuPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
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;


/**
 * 模型菜单权限服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Slf4j
@Service
public class ModelMenuPermissionServiceImpl implements ModelMenuPermissionService {

    @Resource
    private BusinessDatabase businessDatabase;


    /**
     * 查询菜单列表
     * 查询所有的菜单列表信息
     *
     * @return 菜单列表视图
     */
    @Override
    public  List<MenuListView> selectMenus() {

        Map<String, MenuListView> nodeMap = new HashMap<>();
        List<MenuListView> views = new ArrayList<>();
        List<ModelMenuDictionaryPojo> permissionPojos = businessDatabase.getBusinessDatabase()
                .doQuery(ModelMenuDictionaryPojo.class);

        for (ModelMenuDictionaryPojo pojo : permissionPojos) {
            MenuListView node = new MenuListView();
            node.setId(pojo.getId());
            node.setMenu(pojo.getMenuName());
            node.setMenuDesc(pojo.getMenuDesc());
            node.setListViews(new ArrayList<>());
            nodeMap.put(pojo.getId(), node);
        }

        for (ModelMenuDictionaryPojo pojo : permissionPojos) {
            String parentId = pojo.getParentId();
            MenuListView currentNode = nodeMap.get(pojo.getId());

            if (ObjectUtils.isEmpty(parentId) || !nodeMap.containsKey(parentId)) {
                // 根节点
                views.add(currentNode);
            } else {
                // 子节点，添加到父节点
                MenuListView parentNode = nodeMap.get(parentId);
                if (parentNode.getListViews() == null) {
                    parentNode.setListViews(new ArrayList<>());
                }
                parentNode.getListViews().add(currentNode);
            }
        }

        return views;
    }
}
