package com.bohuikeji.frame.module.admin.interceptor;

import com.bohuikeji.frame.module.admin.base.SuperBase;
import com.bohuikeji.frame.module.admin.entity.sys.SysMenu;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.service.ISysMenuService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 菜单页面拦截器
 * @author 10552
 */
@Slf4j
public class MenuInterceptor extends SuperBase implements HandlerInterceptor {
    @Autowired
    ISysMenuService menuService;
    @Autowired
    HttpSession session;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        SysUser user=(SysUser)session.getAttribute("loginUser");
        if (!menuService.AuthCheck(user.getRoleId(),request.getRequestURI())){
            return false;
        }
        //获取被点击菜单
        String id=request.getParameter("menu_id");
        if(StringUtils.isBlank(id)){
            return true;
        }
        SysMenu menu=menuService.getById(id);
        if (menu==null){
            log.error("无法找到菜单,可能已被删除。ID=[{}]",id);
            return false;
        }
        //设置当前活动菜单
        menu.setActive("active");
        //更新上级菜单，并设为活动状态
        SysMenu superMen=menuService.getById(menu.getSuperId());
        if (superMen!=null){
            superMen.setOpen("open");
            superMen.setActive("active");
            menu.setSuperMenu(superMen);
        }
        session.setAttribute("activeMenu",menu);
        return true;
    }
}
