package com.xmomen.module.core.web.exception;

import com.alibaba.fastjson.JSONObject;
import com.xmomen.framework.exception.BusinessException;
import com.xmomen.framework.web.rest.RestError;
import com.xmomen.module.core.web.WebCommonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

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


public class GlobalMappingExceptionResolver extends SimpleMappingExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response, Object handler, Exception ex) {
        // 判断是否是ajax请求
        if (!WebCommonUtils.isJSON(request)) {// 不是ajax请求
            // 调用父类的方法处理异常
            return super.doResolveException(request, response, handler, ex);
        }
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        //设置ContentType
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //避免乱码
        response.setCharacterEncoding("UTF-8");
        // 创建RestError对象
        RestError restError = new RestError(ex, request);
        //设置状态码
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        String message = "";
        // 判断异常类型
        if(ex instanceof IllegalArgumentException || ex instanceof BusinessException){
            // 如果是IllegalArgumentException或BusinessException，设置状态码为400
            status = HttpStatus.BAD_REQUEST.value();
            // 设置错误信息为异常信息
            message = ex.getMessage();
        }else{
            // 否则，设置错误信息为“系统异常，请联系管理员”
            message = "系统异常，请联系管理员";
        }
        // 设置响应状态码
        response.setStatus(status);
        // 设置RestError对象的状态码
        restError.setStatus(status);
        // 设置RestError对象的错误信息
        restError.setMessage(message);
        try {
            // 将RestError对象转换为JSON字符串，并写入响应
            response.getWriter().write(JSONObject.toJSONString(restError));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 记录异常信息
        logger.error(ex.getMessage(), ex);
        return mv;
    }
}
