package com.cm.common.advice;

import com.alibaba.fastjson.JSON;
import com.cm.common.enums.ErrorResultCodeEnum;
import com.cm.common.exception.*;
import com.cm.common.exception.base.SystemException;
import com.cm.common.result.ErrorResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

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


/**
 * @ClassName: ResponseAdvice
 * @Description: Response结果处理
 * @Author: WangGeng
 * @Date: 2019/2/26 5:14 PM
 * @Version: 1.0
 **/
@ControllerAdvice
public class ResponseAdvice {

    private static final Logger LOG = LoggerFactory.getLogger(ResponseAdvice.class);

    @ResponseBody
    @ExceptionHandler({SystemException.class, SQLSyntaxErrorException.class, Exception.class})
    public void responseException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
        if (e instanceof InsufficientAuthenticationException) {
            throw new InsufficientAuthenticationException(e.getMessage());
        }
        if (e instanceof FileException) {
            LOG.error(e.getMessage());
        } else {
            LOG.error(e.getMessage(), e);
        }
        ErrorResult result = new ErrorResult(ErrorResultCodeEnum.SYSTEM_ERROR.getValue(), "系统错误");
        if (e instanceof SaveException) {
            result.setCode(ErrorResultCodeEnum.SAVE_ERROR.getValue());
        } else if (e instanceof RemoveException) {
            result.setCode(ErrorResultCodeEnum.REMOVE_ERROR.getValue());
        } else if (e instanceof UpdateException) {
            result.setCode(ErrorResultCodeEnum.UPDATE_ERROR.getValue());
        } else if (e instanceof SearchException) {
            result.setCode(ErrorResultCodeEnum.QUERY_ERROR.getValue());
        } else if (e instanceof ParamsException) {
            result.setCode(ErrorResultCodeEnum.PARAMS_ERROR.getValue());
        } else if (e instanceof FileException) {
            result.setCode(ErrorResultCodeEnum.FILE_ERROR.getValue());
        } else if (e instanceof AppDeviceException) {
            result.setCode(ErrorResultCodeEnum.DEVICE_ERROR.getValue());
        } else if (e instanceof AppVersionException) {
            result.setCode(ErrorResultCodeEnum.DEVICE_VERSION_ERROR.getValue());
        } else if (e instanceof AccessTokenException) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        // 自定义提示信息
        if (e instanceof SystemException) {
            result.setMsg(e.getMessage());
        } else {
            StringBuilder errorMessageSB = new StringBuilder();
            for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                errorMessageSB.append(stackTraceElement.toString()).append("\n");
            }
            result.setDetail(errorMessageSB.toString());
            result.setDetail(e.getMessage());
        }
        String contentType = request.getContentType();
        if (contentType != null && (contentType.contains(MediaType.APPLICATION_JSON_VALUE) || contentType.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE))) {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.getWriter().write(JSON.toJSONString(result));
        } else {
            request.getSession().setAttribute("errorMessage", JSON.toJSONString(result));
        }
    }

}
