package com.enterprise.manage.modules.system.service.impl;

import com.enterprise.manage.common.base.BaseServiceImpl;
import com.enterprise.manage.modules.system.domain.po.Menu;
import com.enterprise.manage.modules.system.mapper.MenuMapper;
import com.enterprise.manage.modules.system.service.IMenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * system menu service implementation class
 *
 * @author PeiZhi Guo
 * 2021-2-27 10:51
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> querySelectTree() {
        List<Menu> list = new ArrayList<>();
        // 添加根菜单
        Menu sysMenu = new Menu();
        sysMenu.setId(0);
        sysMenu.setTitle("顶级菜单");
        sysMenu.setChildren(children(sysMenu.getId(), baseMapper.selectTreeAll()));
        list.add(sysMenu);
        return list;
    }

    @Override
    public List<Menu> queryRolePermission(Long roleId) {
        // 查询顶层菜单
        List<Menu> topMenus = baseMapper.selectTopRolePermissions(roleId);
        // 查询所有菜单
        List<Menu> allMenus = baseMapper.selectRolePermissions(roleId);
        for (Menu menu0 : topMenus) {
            menu0.setChildren(children(menu0.getId(), allMenus));
        }
        return topMenus;
    }

    @Override
    public boolean checkMenuNameUnique(Menu menu) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", menu.getTitle());
        params.put("id", menu.getId());
        params.put("parentId", menu.getParentId());
        return baseMapper.checkMenuNameUnique(params) > 0;
    }

    @Override
    public boolean hasChildByMenuId(Integer menuId) {
        return baseMapper.selectChildSumByMenuId(menuId) > 0;
    }

    @Override
    public boolean updateEnableById(Integer id, Integer type) {
        Map<String, Object> params = new HashMap<>();
        params.put("menuId", id);
        params.put("type", type);
        return baseMapper.updateEnableById(params) > 0;
    }

    /*
     * 递归获取菜单 tree
     */
    private List<Menu> children(Integer parentId, List<Menu> menus) {
        List<Menu> list = new ArrayList<>();
        for (Menu menu : menus) {
            if (parentId.equals(menu.getParentId())) {
                menu.setChildren(children(menu.getId(), menus));
                list.add(menu);
            }
        }
        return list;
    }
}
