package com.rehome.mqttclienttemperature.response;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BindException.class)
    public Result handleValidationException(BindException ex) {
        Result result = Result.failedByParamValidated();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            System.out.println(error.getField());
            System.out.println(error.getDefaultMessage());
            String baseErrorStr = result.getMessage();
            if(error.getField()!=null){
                baseErrorStr=baseErrorStr+","+error.getField();
                result.setMessage(baseErrorStr);
            }
            if(error.getDefaultMessage()!=null){
                baseErrorStr=baseErrorStr+":"+error.getDefaultMessage();
                result.setMessage(baseErrorStr);
            }
        }
        return result;
    }
}


//@RestControllerAdvice
//public class GlobalExceptionHandler {
//    @ExceptionHandler(BindException.class)
//    public R handleValidationException(BindException ex) {
//        R result = R.error();
//        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
//            result.data(error.getField(), error.getDefaultMessage());
//        }
//        Optional<Object> firstError = result.getData().values().stream().findFirst();
//        return result.msg("请完善信息: "+firstError.orElse("表单内容") +
//                (ex.getErrorCount()>1?" 等多项问题":""));
//    }
//}

//参考：https://www.cnblogs.com/liuscraft/p/17366441.html

//<dependencies>
//<dependency>
//<groupId>org.springframework.boot</groupId>
//<artifactId>spring-boot-starter-validation</artifactId>
//</dependency>
//</dependencies>


//@RestController
//@RequestMapping("/users")
//@Validated
//public class UserController {
//    @PostMapping
//    public String createUser(@RequestBody User user, BindingResult result) {
//        if (result.hasErrors()) {
//            // 处理错误信息
//            return "error";
//        }
//        // 处理用户信息
//        return "success";
//    }
//}