package com.springboot.cloud.sysadmin.organization.service.impl;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2021-01-05          FXY        Created
 **********************************************
 */


import com.springboot.cloud.sysadmin.organization.entity.po.application.ApplicationPopedom;
import com.springboot.cloud.sysadmin.organization.entity.vo.Menu;
import com.springboot.cloud.sysadmin.organization.service.CompanyService;
import com.springboot.cloud.sysadmin.organization.service.MenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {


    @Autowired
    CompanyService companyService;

    @Override
    public List<Menu> index(String companyId) {

        //得到公司对应的所有权限
        List<ApplicationPopedom> allPopedoms = companyService.getCompanyAllPopedom(companyId);

        //先选出菜单
        List<ApplicationPopedom> popedoms = allPopedoms.stream().filter(a -> a.getIsMenu().equals("1") || a.getIsMenu().equals("2")).collect(Collectors.toList());

        //转换节点到菜单
        List<Menu> menuList = popedoms.stream().map(a -> new Menu(a)).collect(Collectors.toList());

        //构建菜单树
        List<Menu> result = buildMenuTree(menuList, null);

        //添加默认显示
        result.add(new Menu("*", "/404", true));

        return result;
    }


    //递归生成树
    private List<Menu> buildMenuTree(List<Menu> menuList, String pid) {
        List<Menu> treeList = new ArrayList<>();
        menuList.stream().forEach(menu -> {
            if (StringUtils.equals(pid, menu.getParentId())) {
                menu.setChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }
        });
        return treeList;
    }
}