/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.huimv.acquisition.result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestControllerAdvice
public class RRExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(RRException.class)
	public R handleRRException(RRException e){
		R r = new R();
		r.put("code", e.getCode());
		r.put("msg", e.getMessage());
		logger.error(e.getMsg(),e);
		return r;
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public R handlerNoFoundException(Exception e) {
		logger.error(e.getMessage(), e);
		return R.error(404, "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public R handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.toString());
		String message = e.getCause().getMessage();
		String[] s = message.split(" ");
		return R.error(600,s[2].replace("'","") + " 已经存在!");
	}

//	@ExceptionHandler(AuthorizationException.class)
//	public R handleAuthorizationException(AuthorizationException e){
//		logger.error(e.getMessage(), e);
//		return R.error("没有权限，请联系管理员授权");
//	}
//
//	@ExceptionHandler(value = LimitAccessException.class)
//	public R handleLimitAccessException(LimitAccessException e) {
//		logger.error("LimitAccessException", e);
//		return  R.error(429,e.getMessage());
//	}

	//当校验失败时，会抛出MethodArgumentNotValidException
	//输出错误原因到前端
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public R handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
		logger.error(ex.getMessage(),ex);
		StringBuilder sb = new StringBuilder();
		for(ObjectError error : ex.getBindingResult().getAllErrors()){
			if(error instanceof FieldError){
				FieldError e = (FieldError) error;
				sb.append(e.getField()).append(e.getDefaultMessage()).append(" ");
			}
		}
		return R.error(1001,sb.toString());
	}

//	@ExceptionHandler(ConstraintViolationException.class)
//	public R handleConstraintViolationException(ConstraintViolationException e) {
//		logger.error(e.getMessage(),e);
//		StringBuilder sb = new StringBuilder();
//		e.getConstraintViolations().forEach(constraintViolation -> sb.append(constraintViolation.getMessage()).append(" "));
//		return R.error(1001,sb.toString().substring(0,sb.length() - 1));
//	}

	@ExceptionHandler(MissingServletRequestParameterException.class)
	public R handMissingServletRequestParameterException(MissingServletRequestParameterException e) {
		logger.error(e.getMessage(),e);
		return R.error(1001,e.getMessage());
	}

	@ExceptionHandler(DataIntegrityViolationException.class)
	public R handDataIntegrityViolationException(DataIntegrityViolationException e) {
		logger.error(e.getMessage(),e);
		return R.error(1001,e.getCause().getMessage());
	}

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public R handHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		logger.error(e.getMessage(), e);
		return R.error(1001, e.getMessage());
	}
	@ExceptionHandler(Exception.class)
	public R handleException(Exception e){
		logger.error(e.getMessage(), e);
		return R.error();
	}
}
