package com.ads.common.exception;

import com.ads.common.data.JsonResult;
import com.ads.common.util.UtilConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author wuyifeng
 * @Description 异常处理
 * @Date 2019/6/3 9:51
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionAdvice {

    /**
     * 处理数据校验异常
     *
     * @param e MethodArgumentNotValidException
     * @return JsonResult
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            StringBuilder message = new StringBuilder();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            if (fieldErrors.size() == 1) {
                message.append(bindingResult.getFieldError().getDefaultMessage());
            } else if (fieldErrors.size() > 1) {
                fieldErrors.forEach(fieldError -> {
                    message.append(fieldError.getDefaultMessage()).append(";\n");

                });
            }
            return JsonResult.fail(UtilConst.CODE_1002, message.toString());
        }
        return null;
    }

    @ExceptionHandler(BusinessException.class)
    public JsonResult handleException(BusinessException e) {
        return JsonResult.fail(UtilConst.CODE_1001, e.getMessage());
    }

    @ExceptionHandler(RoleResourceException.class)
    public JsonResult handleException(RoleResourceException e) {
        return JsonResult.fail(UtilConst.CODE_403, e.getMessage());
    }

    @ExceptionHandler(LoginException.class)
    public JsonResult handleException(LoginException e) {
        return JsonResult.fail(UtilConst.CODE_401,"账号已失效，请重新登录！");
    }

    @ExceptionHandler(FormatException.class)
    public JsonResult handleException(FormatException e) {
        return JsonResult.fail(UtilConst.CODE_1001, e.getMessage(), e.getParams());
    }
}
