package com.keao.edu.auth.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.keao.edu.auth.api.dto.MenuQueryInfo;
import com.keao.edu.auth.api.entity.SysMenu;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.auth.dal.dao.SysMenuDao;
import com.keao.edu.auth.dal.dao.SysUserDao;
import com.keao.edu.auth.service.SysMenuService;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.service.impl.BaseServiceImpl;

@Service
public class SysMenuServiceImpl extends BaseServiceImpl<Integer, SysMenu>  implements SysMenuService {
	
	@Autowired
	private SysMenuDao sysMenuDao;
	@Autowired
	private SysUserDao sysUserDao;

	@Override
	public BaseDAO<Integer, SysMenu> getDAO() {
		return sysMenuDao;
	}

	@Override
	public List<SysMenu> getMenusByRoleId(Integer roleId) {
		return sysMenuDao.getMenusByRoleId(roleId);
	}

	@Override
	public List<SysMenu> findByUser(MenuQueryInfo menuQueryInfo) {
		SysUser sysUser = sysUserDao.get(menuQueryInfo.getUserId());
		List<SysMenu> sysMenus = null;
		if(sysUser.getIsSuperAdmin()){
			menuQueryInfo.setUserId(null);
			sysMenus = sysMenuDao.findList(menuQueryInfo.getParentId(),menuQueryInfo.getDelFlag(),menuQueryInfo.getHid());
		}else {
			sysMenus = sysMenuDao.findByParentId(menuQueryInfo.getParentId(),menuQueryInfo.getDelFlag(),menuQueryInfo.getUserId(),menuQueryInfo.getHid());
		}
		for (SysMenu menu:sysMenus) {
			menu = getTree(menu,menuQueryInfo.getDelFlag(),menuQueryInfo.getUserId(),menuQueryInfo.getHid());
		}
		return sysMenus;
	}

	private SysMenu getTree(SysMenu menu, String delFlag,Integer userId,Integer hid){
		//得到根节点对象
		//获取子节点list
		List<SysMenu> sysMenus = null;
		if(userId == null){
			sysMenus = sysMenuDao.findList(menu.getId(),delFlag,hid);
		}else {
			sysMenus = sysMenuDao.findByParentId(menu.getId(),delFlag,userId,hid);
		}
		//如果存在子节点
		if(sysMenus != null && sysMenus.size() > 0) {
			//将子节点list放入父节点对象
			menu.setSysMenus(sysMenus);
			//遍历子节点....
			for (SysMenu sysMenu : sysMenus) {
				getTree(sysMenu,delFlag,userId,hid);
			}
		}
		return menu;
	}

	@Override
	public SysMenu findMenuByPermission(String permission){
		return sysMenuDao.findMenuByPermission(permission);
	}

	@Override
	public void recursiveDel(Integer parentId) {
		List<SysMenu> sysMenus = sysMenuDao.findList(parentId, "0",0);
		for (SysMenu menu:sysMenus) {
			menu = getTree(menu,"0",null,null);
		}
		List<Integer> collect = sysMenus.stream().map(sysMenu -> sysMenu.getId()).collect(Collectors.toList());
		if(collect == null || collect.size() <= 0){
			sysMenuDao.delete(parentId);
			return;
		}
		collect.add(parentId);
		sysMenuDao.batchDel(collect);
	}
}