package com.tuoheng.admin.advice;

import com.tuoheng.common.common.SysExceptionEnum;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.dao.DataAccessException;
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 org.springframework.http.HttpStatus;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义异常处理器
 *
 * @author zhu_zishuang
 * @date 2021-03-12
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {
    /**
     * 密码校验异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResult<Object> handleAuthenticationException(BindException e) {
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getDefaultMessage() + "!";
        }
        return JsonResult.error(SysExceptionEnum.PARAMETER_EMPTY_EXCEPTION.getCode(), errorMessage);
    }

    /**
     * 校验异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public JsonResult<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.warn("系统参数校验异常，异常信息：{}", e.getMessage());

        JsonResult<Object> 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());
            }
        }

        return error;
    }

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

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



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