package com.keyware.shandan.frame.config.security;

import com.keyware.shandan.system.utils.SysSettingUtil;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 自定义errorPage
 */
@Component
public class ErrorPageConfig implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {

        /**
         * ErrorPage 有两个参数
         * 参数1 响应状态码
         * 参数2 出现响应状态码的时候的跳转路径  可以自定义跳转路径
         */

        //将ErrorPage 注册到注册器中
        registry.addErrorPages(
                new ErrorPage(HttpStatus.FORBIDDEN, "/error/403"),
                new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"),
                new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500")
                );
    }
}

/**
 * 错误页面跳转
 */
@Controller
class ErrorPageController {
    @GetMapping("/error/403")
    public ModelAndView error403(){
        return new ModelAndView("common/error/403","sysLogo",SysSettingUtil.getCurrentSysSetting().getSysLogo());
    }

    @GetMapping("/error/404")
    public ModelAndView error404() {
        return new ModelAndView("common/error/404", "sysLogo", SysSettingUtil.getCurrentSysSetting().getSysLogo());
    }

    @GetMapping("/error/500")
    public ModelAndView error500(HttpServletRequest request, HttpServletResponse response) {
        /*
         如果error请求中携带code和state参数，
         说明是统一认证在配置Nginx反向代理之后出现的错误，实际已经登录成功，在此拦截error请求，并重定向到系统首页
         */
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        if(code!=null && state!=null){
            try {
                response.sendRedirect(request.getContextPath());
                return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ModelAndView("common/error/500","sysLogo",SysSettingUtil.getCurrentSysSetting().getSysLogo());
    }
}
