package com.repair.common.exception;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.repair.common.result.ResponseStatusEnum;
import com.repair.model.result.CommonResult;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统一异常拦截处理
 * 可以针对异常的类型进行捕获，然后返回json信息到前端
 */
@ControllerAdvice
public class EmsExceptionHandler {

    //org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
    final static Logger logger=LoggerFactory.getLogger(EmsExceptionHandler.class);

    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public CommonResult BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        logger.error("错误信息",message);
        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
    }

    //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public CommonResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        logger.error("错误信息",message);
        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
    }

    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public CommonResult exception(NullPointerException e) {
        e.printStackTrace();
        //String error=e.getFieldError().getDefaultMessage();
        logger.error("错误信息",e.fillInStackTrace());
        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult exception(Exception e) {
        e.printStackTrace();
        //String error=e.getFieldError().getDefaultMessage();
        logger.error("错误信息",e.fillInStackTrace());
        return CommonResult.fail(e.getMessage());
    }

    //mysql连接超时
    @ExceptionHandler(MyBatisSystemException.class)
    @ResponseBody
    public CommonResult exception(MyBatisSystemException e) {
        e.printStackTrace();
        //String error=e.getFieldError().getDefaultMessage();
        logger.error("错误信息",e.fillInStackTrace());
        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_MYSQL_TIMEOUT_ERROR);
    }

    //请求方式错误
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public CommonResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        e.printStackTrace();
        logger.error("错误信息",e.fillInStackTrace());
        //String error=e.getFieldError().getDefaultMessage();
        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_REQUEST_METHOD_ERROR);
    }

    //传参空异常
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public CommonResult missingServletRequestParameterException(MissingServletRequestParameterException e) {
        String name=  e.getParameterName();
        logger.error("错误信息",e.fillInStackTrace());

        //String error=e.getFieldError().getDefaultMessage();
        return CommonResult.fail(name+"不能为空");
    }

    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public CommonResult returnMyException(MyCustomException e) {
        e.printStackTrace();
        logger.error("错误信息",e.fillInStackTrace());
        return CommonResult.resultValue(e.getResponseStatusEnum());
    }

    /**
     * 传入JSON数据格式错误
     * @param e
     * @return
     */
    @ExceptionHandler(JsonParseException.class)
    @ResponseBody
    public CommonResult returnMyException(JsonParseException e) {
        logger.error("错误信息",e.fillInStackTrace());
        e.printStackTrace();
        return CommonResult.resultValue(ResponseStatusEnum.SEND_PARAMS);
    }


    /**
     * 传入JSON数据格式转换错误
     * @param e
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public CommonResult httpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("错误信息",e.fillInStackTrace());
        e.printStackTrace();//
        if(e.getCause() instanceof  InvalidFormatException){
            InvalidFormatException e1=   (InvalidFormatException)e.getCause();
            Object erro1= e1.getValue();
            Object erro2=e1.getTargetType().getSimpleName();
            System.out.print(erro1);
            System.out.print(erro2);
        }

        String error=e.getMessage();
        return CommonResult.resultValue(ResponseStatusEnum.SEND_PARAMS_TYPE);
    }







    /**
     * 参数验证错误
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResult returnException(MethodArgumentNotValidException e) {
        logger.error("错误信息",e.fillInStackTrace());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = getErrors(result);
        return CommonResult.fail(map.values().toString().replace("[","").replace("]",""));
    }

    /**
     * 参数验证错误
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public CommonResult returnException(MethodArgumentTypeMismatchException e) {
        logger.error("错误信息",e.fillInStackTrace());
        String value=e.getValue().toString();
        String paraType=e.getRequiredType().getName().toString();

        return CommonResult.errorMsg(e.getName()+"数据格式转换错误");
    }


    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            // 发送验证错误的时候所对应的某个属性
            String field = error.getField();
            // 验证的错误消息
            String msg = error.getDefaultMessage();
            map.put(field, msg);
        }
        return map;
    }


}
