package cn.reghao.bnt.web.config.web.exception;

import io.swagger.v3.oas.annotations.tags.Tag;
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.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 处理 controller 返回的错误, 替换默认的 BasicErrorController
 * 将 /error 作为 Tomcat 的 ErrorPage, org.apache.catalina.core.StandardHostValve#status 方法中会调用 request.setAttribute 方法
 * 设置错误信息, Attribute 的 key 来自 jakarta.servlet.RequestDispatcher
 *
 * @author reghao
 * @date 2020-06-19 13:34:19
 */
@Tag(name = "controller 错误处理接口")
@Slf4j
@Controller
public class ControllerErrorHandler implements ErrorController {
    @RequestMapping("/error")
    public String handleError(Model model, HttpServletRequest request) {
        int statusCode = 500;
        Object object = request.getAttribute("jakarta.servlet.error.status_code");
        if (object != null) {
            statusCode = (int) object;
        }

        model.addAttribute("code", statusCode);
        if (statusCode == 404) {
            model.addAttribute("msg", "页面不存在");
        } else if (statusCode == 403) {
            model.addAttribute("msg", "没有权限");
        } else if (statusCode == 400) {
            model.addAttribute("msg", "参数错误");
        } else if (statusCode == 500) {
            model.addAttribute("msg", "服务器内部错误");
        } else {
            model.addAttribute("msg", "未知错误");
        }

        String prevUrl = (String) request.getAttribute("jakarta.servlet.forward.request_uri");
        String viewPath = "/classic/error";
        if (prevUrl != null && prevUrl.startsWith("/bg")) {
            viewPath = "/admin/error";
        }
        return viewPath;
    }
}
