package com.community.huiju.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.dao.SysMenuMapper;
import com.community.huiju.model.SysMenu;
import com.community.huiju.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 物业web端菜单表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-01-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
	
	@Autowired
	private SysMenuMapper sysMenuMapper;
	/**
	 * 获取递归菜单
	 *
	 * @param userElement
	 * @return
	 */
	@Override
	public ResponseBean getMenuList(UserElement userElement) {
		ResponseBean responseBean = new ResponseBean();
		QueryWrapper<SysMenu> sysMenuQueryWrapper = new QueryWrapper<>();
		sysMenuQueryWrapper.ne("status", "9");
		List<SysMenu> sysMenuList = sysMenuMapper.selectList(sysMenuQueryWrapper);
		List<SysMenu> menuList = new ArrayList<SysMenu>();
		sysMenuList.stream().forEach(sysMenu -> {
			//父节点是0的，为根节点。
			if(sysMenu.getParentId().equals(0)){
				menuList.add(sysMenu);
			}
		});
		
		//递归
		menuList.stream().forEach(sysMenu -> {
			List<SysMenu> childList = getChild(sysMenu.getId(), sysMenuList);
			sysMenu.setChildren(childList);
		});
		responseBean.addSuccess(menuList);
		return responseBean;
	}
	
	public List<SysMenu> getChild(Integer id,List<SysMenu> allMenuList){
		//子菜单
		List<SysMenu> childList = new ArrayList<SysMenu>();
		allMenuList.stream().forEach(sysMenu -> {
			//相等说明：为该根节点的子节点。
			if(sysMenu.getParentId().equals(id)){
				childList.add(sysMenu);
			}
		});
		//递归
		childList.stream().forEach(sysMenu -> {
			sysMenu.setChildren(getChild(sysMenu.getId(), allMenuList));
		});
		//如果节点下没有子节点，返回一个空List（递归退出）
		if(childList.size() == 0){
			return new ArrayList<SysMenu>();
		}
		return childList;
	}
}
