package com.supervision.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.config.domain.GlobalResult;
import com.supervision.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 统一返回
 *
 * @author wb
 * @date 2022/3/10 13:24
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class, basePackages = {"com.**.controller"})
public class ResponseConfig implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(@Nullable MethodParameter methodParameter,
                            @Nullable Class<? extends HttpMessageConverter<?>> aClass) {
        assert methodParameter != null;
        return !methodParameter.getDeclaringClass().getName().contains("swagger");
    }

    @Override
    @SuppressWarnings("all")
    public Object beforeBodyWrite(Object o, @Nullable MethodParameter methodParameter, @Nullable MediaType mediaType,
                                  @Nullable Class<? extends HttpMessageConverter<?>> aClass, @Nullable ServerHttpRequest serverHttpRequest,
                                  @Nullable ServerHttpResponse serverHttpResponse) {
        serverHttpResponse.getHeaders().set("Content-Type", "application/json");

        if (Objects.isNull(o)) {
            return GlobalResult.ok(null, "success");
        }
        if (o instanceof GlobalResult) {
            return o;
        }
        // 对于String类型的返回值需要进行特殊处理
        if (o instanceof String) {
            return JSONUtil.toJsonStr(GlobalResult.ok(o, "success"));
        }
        return GlobalResult.ok(o, "success");
    }

    /**
     * 业务异常处理
     *
     * @param exception 业务异常
     * @return 通用返回值
     */
    @ExceptionHandler(BusinessException.class)
    public GlobalResult<?> businessExceptionResponse(BusinessException exception) {
        log.error(exception.getMessage(), exception);
        Integer code = null == exception.getCode() ? HttpStatus.INTERNAL_SERVER_ERROR.value(): exception.getCode();
        String message = StrUtil.isNotEmpty(exception.getMessage()) ? exception.getMessage() : "业务异常";
        return GlobalResult.error( code, exception.getMessage(), message);
    }



    /**
     * 参数验证异常处理
     *
     * @param exception 参数验证异常
     * @return 通用返回值
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public GlobalResult<?> validationExceptionResponse(MethodArgumentNotValidException exception) {
        log.error(exception.getMessage(), exception);
        // 格式化错误信息
        String errorMsg = exception.getBindingResult().getFieldErrors().stream()
                .map(e -> e.getField() + ":" + e.getDefaultMessage()).collect(Collectors.joining("、"));
        return GlobalResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMsg, "参数验证异常");
    }


    /**
     * 添加手动校验参数的异常处理
     * @param exception 参数验证异常
     * @return 通用返回值
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public GlobalResult<?> manualValidationExceptionResponse(IllegalArgumentException exception) {
        log.error(exception.getMessage(), exception);
        return GlobalResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage(), "参数验证异常");
    }

    /**
     * 未知异常处理
     *
     * @param exception 未知异常
     * @return 通用返回值
     */
    @ExceptionHandler(Exception.class)
    public GlobalResult<?> validationExceptionResponse(Exception exception) {
        log.error(exception.getMessage(), exception);
        return GlobalResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "未知错误", "未知错误");
    }


}
