package com.tuoheng.common.core.advice;

import com.tuoheng.common.core.enums.SysExceptionEnum;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
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.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

/**
 * 自定义异常处理器
 *
 * @author zhu_zishuang
 * @date 2021-03-12
 */
@RestControllerAdvice
public class CustomExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomExceptionHandler.class);

    /**
     * 密码校验异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResult<Object> handleAuthenticationException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getDefaultMessage() + "!";
        }
        return JsonResult.error(SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getCode(), errorMessage);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonResult<Object> handleConstraintViolationException(ConstraintViolationException e) {
        String message = e.getConstraintViolations()
                .stream()
                .map(constraintViolation -> {
                    return constraintViolation.getPropertyPath().toString() + ": " + constraintViolation.getMessage();
                })
                .collect(Collectors.joining(","));
        LOGGER.error("参数格式错误：{}", message);
        return JsonResult.error(SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getCode(), SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getMsg());
    }

    /**
     * 校验异常处理
     * 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public JsonResult<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        LOGGER.warn("系统参数校验异常，异常信息：{}", e.getMessage());

        JsonResult<Object> error = JsonResult.error(SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getCode(),
                SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getMsg());

        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());
            }
        }
        return error;
    }

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

    /**
     * 系统数据访问异常处理
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public JsonResult<Object> handleDataAccessException(DataAccessException e) {
        LOGGER.error("系统数据访问异常，异常信息：{}", e);
        return JsonResult.error(SysExceptionEnum.DATAACCESS_EXCEPTION.getCode(), SysExceptionEnum.DATAACCESS_EXCEPTION.getMsg());
    }

    /**
     * 系统异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResult<Object> handleException(Exception e) {
        System.out.println(e.getSuppressed());
        System.out.println(e.getCause().getMessage());
        System.out.println(e.getCause().getCause());
        LOGGER.error("系统异常，异常信息：{}", e);
        return JsonResult.error(SysExceptionEnum.SYS_EXCEPTION.getCode(), SysExceptionEnum.SYS_EXCEPTION.getMsg());
    }
}
