package cn.quantgroup.customer.exception;


import cn.quantgroup.customer.rest.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.exception.DataException;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by Miraculous on 15/7/6.
 * 出现异常，进入这个handler。
 */
@Slf4j
@ControllerAdvice
@RestController
public class ExceptionHandlers {

    private static final JsonResult EXCEPTION_RESULT = new JsonResult("服务出错。", (long) HttpStatus.INTERNAL_SERVER_ERROR.value(), null);


    @ExceptionHandler(ValidationException.class)
    public JsonResult validException(ValidationException exception) {
        ConstraintViolationException exs = (ConstraintViolationException) exception;
        Set<ConstraintViolation<?>> constraintViolations = exs.getConstraintViolations();
        if (constraintViolations.isEmpty()) {
            log.error("这里出了个错....", exception.getMessage());
            return null;
        }
        String message = constraintViolations.iterator().next().getMessage();
        return JsonResult.buildErrorStateResult(message, null);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleBindException(Exception e) {
        BindingResult result = null;
        if (e instanceof MethodArgumentNotValidException) {
            result = ((MethodArgumentNotValidException) e).getBindingResult();
        } else if (e instanceof BindException) {
            result = ((BindException) e).getBindingResult();
        }
        if (result != null) {
            List<ObjectError> errors = result.getAllErrors();
            StringBuilder sb = new StringBuilder();
            if (errors != null && errors.size() > 0) {
                Iterator<ObjectError> iterator = errors.iterator();
                ObjectError err = null;
                while ((err = iterator.next()) != null) {
                    sb.append(err.getDefaultMessage());
                    if (iterator.hasNext()) {
                        sb.append("; ");
                    } else {
                        sb.append("。");
                        break;
                    }
                }
            }
            return JsonResult.buildErrorStateResult(sb.toString(), null);
        }
        return null;
    }

    @ExceptionHandler({DataException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleDataException(DataException e) {
        return JsonResult.buildErrorStateResult(e.getMessage(), null);
    }


    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleBadSqlGrammarException(BadSqlGrammarException e) {
        log.error("sql语法解析异常 error sql = 【{}】", e.getSql(), e);
        return JsonResult.buildErrorStateResult("参数错误。", null);
    }


    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public JsonResult handelMissingServletRequestParameterException(MissingServletRequestParameterException re) {
        return JsonResult.buildErrorStateResult(re.getMessage(), null);
    }



}
