package io.renren.modules.admin.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.Constant;

import io.renren.modules.admin.dao.AdminMenuDao;
import io.renren.modules.admin.entity.AdminMenuEntity;
import io.renren.modules.admin.service.AdminMenuService;
import io.renren.modules.sys.service.SysUserService;


@Service("adminMenuService")
public class AdminMenuServiceImpl extends ServiceImpl<AdminMenuDao, AdminMenuEntity> implements AdminMenuService {
	@Autowired
	private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AdminMenuEntity> page = this.page(
                new Query<AdminMenuEntity>().getPage(params),
                new QueryWrapper<AdminMenuEntity>()
        );

        return new PageUtils(page);
    }

	public List<AdminMenuEntity> queryListParentId(Long parentId, List<Long> menuIdList) {
		List<AdminMenuEntity> menuList = queryListParentId(parentId);
		if(menuIdList == null){
			return menuList;
		}
		
		List<AdminMenuEntity> userMenuList = new ArrayList<>();
		for(AdminMenuEntity menu : menuList){
			if(menuIdList.contains(menu.getMenuId())){
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}

	public List<AdminMenuEntity> queryListParentId(Long parentId) {
		return baseMapper.queryListParentId(parentId);
	}

	@Override
	public List<AdminMenuEntity> getUserMenuList(Long userId) {
		//系统管理员，拥有最高权限
		if(userId == Constant.SUPER_ADMIN){
			return getAllMenuList(null);
		}
		
		//用户菜单列表
		List<Long> menuIdList = sysUserService.queryAllMenuId(userId);
		return getAllMenuList(menuIdList);
	}

    /**
	 * 获取所有菜单列表
	 */
	private List<AdminMenuEntity> getAllMenuList(List<Long> menuIdList){
		//查询根菜单列表
		List<AdminMenuEntity> menuList = queryListParentId(0L, menuIdList);
		//递归获取子菜单
		getMenuTreeList(menuList, menuIdList);
		
		return menuList;
	}

	/**
	 * 递归
	 */
	private List<AdminMenuEntity> getMenuTreeList(List<AdminMenuEntity> menuList, List<Long> menuIdList){
		List<AdminMenuEntity> subMenuList = new ArrayList<AdminMenuEntity>();
		
		for(AdminMenuEntity entity : menuList){
			//目录
			if(entity.getType() == Constant.MenuType.CATALOG.getValue()){
				entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
			}
			subMenuList.add(entity);
		}
		
		return subMenuList;
	}
}