package easydo.technology.config.exception;

import easydo.technology.exception.BadRequestException;
import easydo.technology.exception.BizException;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


/**
 * 处理Controller抛出的异常*
 * @author tianyf
 */
@RestControllerAdvice
@Log4j2
public class BizExceptionHandler {

    /**
     * 处理 BadRequestException
     * 返回 异常中定义的 错误状态码
     */
    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<Object> handleBadRequestException(BadRequestException e) {
        log.error("[ 请求异常捕获 ] " + e.getMessage());
        Map<String, Object> vo = new HashMap<>();
        vo.put("success", false);
        vo.put("message", e.getMessage());
        vo.put("error", "");
        return new ResponseEntity<>(vo, HttpStatus.valueOf(e.getStatus()));
    }

    /**
     * 处理业务异常 (BizException)
     * 返回 400 错误
     */
    @ExceptionHandler(BizException.class)
    public ResponseEntity<Object> handleBizException(BizException e) {
        log.error("[ 业务异常捕获 ] " + e.getMessage());
        Map<String, Object> vo = new HashMap<>();
        vo.put("success", false);
        vo.put("message", e.getMessage());
        vo.put("error", "");
        return new ResponseEntity<>(vo, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理所有不可知的系统异常 (Exception)
     * 返回 500 错误
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception e) {
        log.error("[ 系统异常捕获 ] ", e);
        Map<String, Object> vo = new HashMap<>();
        vo.put("success", false);
        vo.put("message", "系统错误");
        vo.put("error", e.getMessage() != null ? e.getMessage() : e.getClass().getName());
        return new ResponseEntity<>(vo, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 为 @NotNull / @NotEmpty / @NotBlank 提供异常后的消息抛出*
     * @param bindException
     * @return
     */
    @ExceptionHandler({BindException.class})
    public ResponseEntity<Object> throwCustomException(BindException bindException){
        log.error("[ @Vaild异常捕获 ] " + bindException.getMessage());
        Map<String, Object> vo = new HashMap<>();
        vo.put("success", false);
        vo.put("message", bindException.getBindingResult().getFieldError().getDefaultMessage());
        vo.put("error", "参数校验失败");
        return new ResponseEntity<>(vo, HttpStatus.BAD_REQUEST);
    }
}
