package com.kingdee.eas.custom.integration.base.advice;

import com.google.common.collect.Maps;
import com.kingdee.eas.custom.integration.base.exception.IntegrationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice("com.kingdee.eas.custom.integration")
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理 IntegrationException
     */
    @ExceptionHandler(IntegrationException.class)
    public Object handleBizException(IntegrationException e, HttpServletRequest request) {
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.contains("application/json")) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", e.getErrorCode().getCode());
            result.put("message", e.getMessage());
            result.put("data", Maps.newHashMap());
            return ResponseEntity.badRequest().body(result);
        } else {
            ModelAndView mav = new ModelAndView("integrationError");
            mav.addObject("errorCode", e.getErrorCode().getCode());
            mav.addObject("errorMsg", e.getMessage());
            return mav;
        }
    }

    /**
     * 处理请求体格式错误或为空
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Object handleMissingBody(HttpMessageNotReadableException e, HttpServletRequest request) {

        String message = e.getMessage();

        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.contains("application/json")) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("message", "请求体格式错误或为空");
            result.put("data", Maps.newHashMap());
            return ResponseEntity.badRequest().body(result);
        } else {
            ModelAndView mav = new ModelAndView("integrationError");
            mav.addObject("errorCode", "400");
            mav.addObject("errorMsg", "请求体格式错误或为空");
            return mav;
        }
    }
}
