package cn.com.countrygarden.bi.main.handler;

import cn.com.countrygarden.bi.main.exception.AuthorizeException;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.exception.PerformanceException;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(GlobalHandlerExceptionResolver.class);

    /**
     * 在这里处理所有得异常信息
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest req,
                                         HttpServletResponse resp,
                                         Object o, Exception e) {
        String message;
        Result result = new Result();
        if (e instanceof ServiceException) {
            message = "服务异常：" + e.getMessage();
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
        } else if (e instanceof AuthorizeException) {
            message = "身份校验失败：" + e.getMessage();
            //result.setResultCode(ResultCode.UNAUTHORIZED).setResultMsg(message);
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
        } else if (e instanceof NotFoundException) {
            message = "接口 [" + req.getRequestURI() + "] 不存在";
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            message = "接口 [" + req.getRequestURI() + "] 不支持的请求方法";
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
        } else if (e instanceof ServletException) {
            message = "系统服务异常：" + e.getMessage();
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
        } else if(e instanceof PerformanceException){
            message = e.getMessage();
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
        } else {
            message = "接口 [" + req.getRequestURI() + "] 异常，请联系管理员";
            result.setResultCode(ResultCode.NOK).setResultMsg(message);
            message += "：" + e.getMessage() + "： " + e.getStackTrace();
        }
        logger.error(message, e);
        responseResult(resp, result);
        return new ModelAndView();
    }

    /**
     * 将错误信息添加到response中
     *
     * @param response
     * @param result
     */
    private void responseResult(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
}
