package com.fzm.mall.server.admin.exception;

import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import com.fzm.mall.server.admin.repo.ResponseVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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 org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;

@ControllerAdvice
@ResponseBody
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class ControllerExceptionHandler {

    private final ResponseFactory res;

    /*@ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleIllegalArgumentException() {
        return res.getResponse();
    }*/

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        e.printStackTrace();
        return res.getResponse(MallResponseError.SYS_EXCEPTION);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return res.getResponse(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleConstraintViolationException(ConstraintViolationException e) {
        return res.getResponse(e.getConstraintViolations().iterator().next().getMessageTemplate());
    }


    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleMyException(MyException e) {
        return res.getResponse(e.getCode());
    }

}
