package com.wms_main.config.advice;

import com.wms_main.model.dto.response.wms.BaseWmsApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * WMS 接口异常处理类
 */
@ControllerAdvice(value = "com.wms_main.controller.wms")
@ResponseBody
@Slf4j
public class WmsControllerExceptionHandler {

    /**
     * 参数校验失败
     * @param ex 异常
     * @return 返回值
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseWmsApiResponse methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("Wms接口请求参数错误：{}", ex.getMessage());
        String errMessage = "请求参数错误";
        FieldError fieldError = ex.getBindingResult().getFieldError();
        if(fieldError != null) {
            errMessage = fieldError.getDefaultMessage();
        }
        return BaseWmsApiResponse.error(errMessage);
    }

    /**
     * 参数类型转换失败
     * @param ex 异常
     * @return 返回值
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public BaseWmsApiResponse parameterTypeException(HttpMessageConversionException ex) {
        log.error("Wms接口请求参数格式错误：{}", ex.getMessage());
        String errorMessage = "请求参数格式错误，请参照接口文档";
        return BaseWmsApiResponse.error(errorMessage);

    }

    /**
     * 捕获所有异常
     * @param e 异常
     * @return 返回值
     */
    @ExceptionHandler(value = Exception.class)
    public BaseWmsApiResponse handleException(Exception e) {
        log.error("Wms接口异常:{}", e.getMessage());
        return BaseWmsApiResponse.error(String.format("发生异常：%s", e.getMessage()));
    }

}
