package com.example.demo.exception.handler;


import com.example.demo.exception.BizException;
import com.example.demo.exception.ValidateException;
import com.example.demo.result.ResponseData;
import com.example.demo.result.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
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.servlet.NoHandlerFoundException;


import java.io.FileNotFoundException;
import java.util.List;

/**
 * 统一处理服务调用异常
 */
@ControllerAdvice(basePackages = "com.example.demo.controller")
public class ControllerExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 所有异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData exceptionHandler(Exception e) {

        LOG.error("An error has occurred in the system：", e);
        return new ResponseUtil().setErrorMsg("An error has occurred in the system. Please contact the administrator.");
    }


    /**
     * 下载地址还未生成结果文件异常
     * @param e
     * @return
     */

    @ExceptionHandler(value = FileNotFoundException.class)
    @ResponseBody
    public ResponseData handle(FileNotFoundException e) {
        LOG.error("The result file has not been generated yet:", e);
        return new ResponseUtil().setErrorMsg("he result file is currently being generated. Please try again later.");
    }





    @ExceptionHandler(value = ValidateException.class)
    @ResponseBody
    public ResponseData handle(ValidateException e) {
        LOG.error("业务方法参数校验失败：", e);
        return new ResponseUtil().setErrorMsg("验证码错误");
    }





    /**
     * 所有自定义异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResponseData handle(BizException e) {
        LOG.error("业务异常：", e);
        return new ResponseUtil().setErrorMsg(e.getMessage());
    }

//    /**
//     * 客户端请求参数校验不通过
//     *
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(value = ConstraintViolationException.class)
//    @ResponseBody
//    public ResponseData handle(ConstraintViolationException e) {
//        LOG.error("[客户端请求参数校验不通过]", e);
//        Iterator<ConstraintViolation<?>> it = e.getConstraintViolations().iterator();
//        return new ResponseUtil().setErrorMsg("客户端请求参数校验不通过");
//    }


    /**
     *  客户端请求体JSON格式错误或字段类型不匹配
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public ResponseData handle(HttpMessageNotReadableException e) {
        LOG.error("[客户端请求体JSON格式错误或字段类型不匹配]", e);
        return new ResponseUtil().setErrorMsg("客户端请求体JSON格式错误或字段类型不匹配");
    }

    /**
     * 客户端请求体参数校验不通过, 请求参数或者Json字段不满足校验规则
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class )
    @ResponseBody
    public ResponseData handle(MethodArgumentNotValidException e) {
        LOG.error("[客户端请求体参数校验不通过]", e);
        String errorMsg = this.handle(e.getBindingResult().getFieldErrors());
        return new ResponseUtil().setErrorMsg("客户端请求体参数校验不通过: " + errorMsg);
    }

    /**
     * 客户端请求体参数校验不通过, 请求参数或者Json字段不满足校验规则
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class} )
    @ResponseBody
    public ResponseData handle(BindException e) {
        LOG.error("[客户端请求体参数校验不通过]", e);
        String errorMsg = this.handle(e.getBindingResult().getFieldErrors());
        return new ResponseUtil().setErrorMsg("客户端请求体参数校验不通过: " + errorMsg);
    }


    private String handle(List<FieldError> fieldErrors) {
        StringBuilder sb = new StringBuilder();
        for (FieldError obj : fieldErrors) {
            sb.append(obj.getField());
            sb.append("=[");
            sb.append(obj.getDefaultMessage());
            sb.append("]  ");
        }
        return sb.toString();
    }
}
