package com.tofly.gpsboot.common.exceptions;

import com.tofly.common.core.entity.ResultRespone;
import org.springframework.validation.BindException;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wujianjun
 * @date 2023/4/19 13:47
 */
@ControllerAdvice
public class MeiCunExceptionHandle {

//    @ExceptionHandler(ArithmeticException.class)
//    @ResponseBody
//    public GraceJSONResult returnArithmeticException(ArithmeticException e) {
//        return GraceJSONResult.errorMsg(e.getMessage());
//    }

    /**
     * 设置要捕获的异常，并作出处理 注意：这里可以返回试图，也可以放回JSON，这里就当做一个Controller使用
     *
     * @param ex {@link Exception}
     * @return {@link Map}
     */
//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public ResultRespone processUnauthenticatedException(Exception e) {
//        e.printStackTrace();
//        return ResultRespone.failed(ResponseStatusEnum.SYSTEM_ERROR);
//    }
    @ExceptionHandler(MeiCunException.class)
    @ResponseBody
    public ResultRespone returnMyCustomException(MeiCunException e) {
        return ResultRespone.failed(e.getResponseStatusEnum().status(), e.getResponseStatusEnum().msg());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultRespone returnMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> errors = getErrors(result);
        return ResultRespone.failed(errors);
    }

    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError fe : errorList) {
            String field = fe.getField();
            String message = fe.getDefaultMessage();
            map.put(field, message);
        }
        return map;
    }
}
