package com.cirle.scientific.controller.error;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class UncaughtErrorControllor implements ErrorController {
    @Value("${server.error.path:${error.path:/error}}")
    protected String errorPath;

    @Override
    public String getErrorPath() {
        return errorPath;
    }

    /**
     * @param request
     * @param response
     * @return java.lang.Object
     */
    @RequestMapping(value = "")
    public void error(HttpServletRequest request, HttpServletResponse response) {
//        try {
//            HttpStatus statusCode = getHttpStatusCode(request);
//            if (statusCode.equals(HttpStatus.NOT_FOUND)) {
//                String from = request.getParameter("from");
//                if ("H5".equals(from)) {
//                    response.sendRedirect("/index/index?from=H5");
//                } else {
//                    response.sendRedirect("/index/index?from=web");
//                }
////                response.sendRedirect("/404");
//            } else {
//                response.sendRedirect("/other?code=" + statusCode);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    private HttpStatus getHttpStatusCode(HttpServletRequest request) {
        try {
            Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
            if (statusCode == null) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
            return HttpStatus.valueOf(statusCode);
        } catch (Exception e) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

}

