package com.tuoheng.common.advice;

import com.tuoheng.common.common.SysExceptionEnum;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.JacksonUtil;
import com.tuoheng.common.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 吴彬
 * @CreateTime: 2023-05-22  19:09
 * @Description: 自定义异常处理器
 * @Version: 1.0
 */
@RestControllerAdvice
@Slf4j
public class CustomExceptionHandler {


    /**
     * 密码校验异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleAuthenticationException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
//            errorMessage.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(" ");
            errorMessage.append(fieldError.getDefaultMessage()).append(" ");
        }
        log.error("参数格式错误：{}", errorMessage);
        return new ResponseEntity<>(JsonResult.error(JsonResult.ERROR, errorMessage.toString()), HttpStatus.OK);
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<JsonResult<Void>> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return new ResponseEntity<>(JsonResult.error(SysExceptionEnum.SYS_EXCEPTION.getCode(),
                e.getMessage()), HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleConstraintViolationException(ConstraintViolationException e) {
        String message = e.getConstraintViolations()
                .stream()
                .map(constraintViolation -> constraintViolation.getMessage())
                .collect(Collectors.joining(" "));
        log.error("参数格式错误：{}", message);
        return new ResponseEntity<>(JsonResult.error(JsonResult.ERROR, message), HttpStatus.OK);
    }

    /**
     * 校验异常处理
     * 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        JsonResult<Void> error = JsonResult.error(SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getCode(),
                SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getMessage());
        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        if (!CollectionUtils.isEmpty(fieldErrors)) {
            error.setMsg(fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(" ")));
        } else {
            if (!CollectionUtils.isEmpty(result.getAllErrors())) {
                ObjectError currError = result.getAllErrors().get(0);
//                error.setMsg(currError.getObjectName() + currError.getDefaultMessage());
                error.setMsg(currError.getDefaultMessage());
            }
        }
        log.error("参数格式错误：{}", JacksonUtil.obj2StringPretty(error));
        return new ResponseEntity<>(error, HttpStatus.OK);
    }

    /**
     * 校验异常处理
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("参数格式错误：", e);
        return new ResponseEntity<>(JsonResult.error(JsonResult.ERROR, e.getMessage()), HttpStatus.OK);
    }

    /**
     * 系统业务异常处理
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleServiceException(ServiceException e) {
        // 打印业务异常日志
        log.warn("系统业务逻辑异常，异常状态码 {}，异常信息：{}", e.code, e.getMessage());
        return new ResponseEntity<>(JsonResult.error(e.getCode(), e.getMsg()), HttpStatus.OK);
    }

    /**
     * 系统数据访问异常处理
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleDataAccessException(DataAccessException e) {
        log.error("系统数据访问异常，异常信息:", e);
        return new ResponseEntity<>(JsonResult.error(SysExceptionEnum.DATAACCESS_EXCEPTION.getCode(),
                SysExceptionEnum.DATAACCESS_EXCEPTION.getMessage()), HttpStatus.BAD_REQUEST);
    }

    /**
     * 系统异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<JsonResult<Void>> handleException(Exception e) {
        log.error("系统异常，异常信息:", e);
        return new ResponseEntity<>(JsonResult.error(SysExceptionEnum.SYS_EXCEPTION.getCode(),
                SysExceptionEnum.SYS_EXCEPTION.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
