package com.tykj.dev.misc.exception;


import com.tykj.dev.misc.base.ResultObj;
import com.tykj.dev.misc.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 错误处理类
 * 所有的报错信息都会通过本层的方法向外界返回
 *
 * @author HuangXiahao
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 报错信息都会通过这个方法处理并通过统一的返回方式进行返回
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseEntity errorMessage(Exception e) {
        e.printStackTrace();
        return ResultUtil.failed();
    }

    /**
     * 业务错误
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(ApiException.class)
    public ResponseEntity errorMessage(ApiException e) {
        log.warn("[自定义异常] {}", e.toString());
        if (e.getResponseEntity() != null) {
            return ResponseEntity.status(400).body(e.getResponseEntity().getBody());
        }
        return ResultUtil.failed();
    }

    /**
     * 数据合法性验证报错会通过这个方法处理并通过统一的返回方式进行返回
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ResponseEntity errorMessage(BindException e) {
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return ResultUtil.failed(message);
    }

    /**
     * 用户未登录时会通过这里处理
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity errorMessage(AuthenticationException e) {
        e.printStackTrace();
        return ResultUtil.unauthorized();
    }

    /**
     * 用户权限不足
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity errorMessage(AccessDeniedException e) {
        e.printStackTrace();
        return ResponseEntity.status(403).body(new ResultObj(e.getMessage()));
    }

}

