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

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.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
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理 IntegrationException
     * 可以根据需要返回 JSON 或错误页面
     */
    @ExceptionHandler(IntegrationException.class)
    public Object handleBizException(IntegrationException e, HttpServletRequest request) {
        // 判断请求是否期望 JSON 响应（例如 API 接口）
        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.getErrorCode().getDefaultMessage());
            // 返回 JSON 格式的错误信息
            return ResponseEntity.badRequest().body(result);
        } else {
            // 返回错误页面（适用于传统 Web 应用）
            ModelAndView mav = new ModelAndView("integrationError");
            mav.addObject("errorCode", e.getErrorCode().getCode());
            //mav.addObject("errorMsg", e.getErrorCode().getDefaultMessage());
            mav.addObject("errorMsg", e.getMessage());
            return mav;
        }
    }
}