package cc.smtweb.framework.core.mvc.config;

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.mvc.realm.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

/**
 * 〈异常处理〉
 *
 * @author kevin
 * @since 1.0.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
//
//    /**
//     * 〈校验的异常处理〉
//     */
//    @ExceptionHandler(value = {BindException.class})
//    @ResponseBody
//    public Result handleBindException(BindException be) {
//        return super.handleException(be);
//    }
//

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleAuthenticationException(AuthenticationException e) {
        return R.error("认证失败", e);
    }

    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R handleUnauthenticatedException(UnauthenticatedException e) {
        return R.error("认证失败", e);
    }

    @ExceptionHandler(UnknownAccountException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R handleUnknownAccountException(UnknownAccountException e) {
        return R.error("用户名或密码错误", e);
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R handleAuthorizationException(AuthorizationException e) {
        log.error("No permissions:" + e.getMessage());
        return R.error("没有权限", e);
    }

    @ExceptionHandler(ForbiddenException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R handleAuthorizationException(ForbiddenException e) {
        log.error("No permissions:" + e.getMessage());
        return R.error("没有权限", e);
    }

    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(Exception ex) {
        Throwable e = ex;
        if (ex instanceof java.lang.reflect.InvocationTargetException) {
            e = ex.getCause();
        }

        log.error(e.getMessage(), e);
        return R.error(e.getMessage(), e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException ex) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        List<String> validationMsg = errors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        // 不满足需求 一个一个提示
        return R.error(validationMsg.get(0));
    }
}
