package com.chenyang.nse.bussiness.controller.console;

import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseMenu;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseRole;
import com.chenyang.nse.bussiness.service.console.ConsoleService;
import com.chenyang.nse.bussiness.tools.object.JsonTool;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping({"/console"})
public class ConsoleController {
   @Autowired
   private ConsoleService consoleService;

   @RequestMapping({"/"})
   public String console(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "console/index";
   }

   @RequestMapping({"/top"})
   public String top(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "console/top";
   }

   @RequestMapping({"/bottom"})
   public String bottom(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "console/bottom";
   }

   @RequestMapping({"/initMenu"})
   public String initMenu(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      Object menuNeedRefresh = request.getSession().getAttribute("menuNeedRefresh");
      if (menuNeedRefresh != null && (Boolean)menuNeedRefresh) {
         List<TBaseRole> trole = loginUser.getTrole();
         List<TBaseMenu> menus = new ArrayList();

         for(TBaseRole role : trole) {
            String roleId = role.getId();
            menus.addAll(this.consoleService.qeuryMenusByRoleId(roleId));
         }

         loginUser.setMenus(menus);
         request.getSession().setAttribute("menuNeedRefresh", false);
      }

      String menu_json = JsonTool.toJsonString(loginUser.getMenus());
      if (menu_json == null) {
         return null;
      } else {
         model.addAttribute("menu", menu_json);
         return "console/left";
      }
   }
}
