package com.fdkankan.common.response;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.response.ResultData;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
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.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class BaseResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
        MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
        ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//        if(serverHttpRequest.getURI().getPath().contains("feign")){
//            return body;
//        }
//        log.info("响应拦截成功。。。");
//        List<String> strings = serverHttpRequest.getHeaders().get("Accept-Language");
//        System.out.println(strings.get(0));

        //admin监控请求，直接返回
        if(serverHttpRequest.getURI().getPath().contains("actuator")){
            return body;
        }

        if(body instanceof String){
            return JSONObject.toJSONString(ResultData.ok(body));
        }
        if(body instanceof Page){
            Page page = (Page) body;
            return ResultData.ok(new PageInfo(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords()));
        }
        if (body instanceof ResultData) {
            return body;
        } else {
            return ResultData.ok(body);
        }
    }
}
