package cn.reghao.autodop.dmaster.rbac.controller.page;

import cn.reghao.autodop.dmaster.rbac.UserContext;
import cn.reghao.autodop.dmaster.rbac.model.po.Menu;
import cn.reghao.autodop.dmaster.rbac.model.po.User;
import cn.reghao.autodop.dmaster.rbac.service.HomeService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Slf4j
@Api(tags = "登录页和首页")
@Controller
public class HomePageController implements ErrorController {
    private final HomeService homeService;

    public HomePageController(HomeService homeService) {
        this.homeService = homeService;
    }

    @GetMapping("/")
    public String index(Model model) {
        User user = UserContext.currentUser();
        List<Menu> menus = homeService.userMenus(user.getRole());
        Map<Integer, Menu> treeMenu = homeService.treeMenu(menus);

        model.addAttribute("user", user);
        model.addAttribute("treeMenu", treeMenu);
        return "/main";
    }

    @GetMapping("/login")
    public String toLogin(Model model) {
        model.addAttribute("isCaptcha", false);
        return "/login";
    }

    @GetMapping("/home")
    public String home(Model model) {
        return "/home/index";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }

    /**
     * 处理错误页面
     *
     * @param
     * @return
     * @date 2021-05-19 下午2:35
     */
    @RequestMapping("/error")
    @ResponseBody
    public String handleError(Model model, HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == 404) {
            return "接口不存在";
        } else if (statusCode == 400) {
            return "参数错误";
        } else if (statusCode == 500) {
            return "服务器内部错误";
        }
        log.error("http status code: " + statusCode);

        model.addAttribute("statusCode", statusCode);
        model.addAttribute("msg", "页面去火星啦～");
        return "/404";
    }
}
