package com.api.config;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.*;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.model.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: RestExceptionHandler
 * @author: HuRui
 * @date: 2023/5/23
 **/

@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 默认全局异常处理。
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseData handleValidatedException(Exception e) {

        if (e instanceof  MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex =(MethodArgumentNotValidException)  e;
            ObjectError objectError = ex.getBindingResult().getAllErrors().stream().collect(Collectors.toList()).get(0);
            return ResponseMsgUtil.builderResponse(SysCode.OpenApi.getCode()+ErrorCode.OPEN_API_REQ_PARAMS_ERR.getCode(), objectError.getDefaultMessage(),null);

        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException ex = (ConstraintViolationException) e;
            ConstraintViolation<?> constraintViolation = ex.getConstraintViolations().stream().collect(Collectors.toList()).get(0);
            return ResponseMsgUtil.builderResponse(SysCode.OpenApi.getCode()+ErrorCode.OPEN_API_REQ_PARAMS_ERR.getCode(), constraintViolation.getMessage(),null);

        } else if (e instanceof BindException) {
            BindException ex = (BindException ) e;
            ObjectError objectError = ex.getAllErrors().stream().collect(Collectors.toList()).get(0);
            return ResponseMsgUtil.builderResponse(SysCode.OpenApi.getCode()+ErrorCode.OPEN_API_REQ_PARAMS_ERR.getCode(), objectError.getDefaultMessage(),null);
        }
        return ResponseMsgUtil.builderResponse(SysCode.OpenApi.getCode()+ErrorCode.OPEN_API_REQ_PARAMS_ERR.getCode(), ErrorCode.OPEN_API_REQ_PARAMS_ERR.getMsg(),null);
    }

}
