package com.fdkankan.web.response;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.web.annotation.NotResponseAdvice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;

@ConditionalOnMissingBean(name = "customResponseAdvice")
@RestControllerAdvice
@Slf4j
public class BaseResponseAdvice implements ResponseBodyAdvice<Object> {

    @Value("${fdkk.language:zh_CN}")
    private String language;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        NotResponseAdvice methodAnnotation = methodParameter.getMethodAnnotation(NotResponseAdvice.class);
        if(Objects.nonNull(methodAnnotation)){
            return false;
        }
        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 ResultData) {
            return getI18n((ResultData) body);
        }else if(body instanceof Result){
            return body;
        } else {
            return getI18n(ResultData.ok(body));
        }
    }

    private ResultData getI18n(ResultData data){
        if("zh_CN".equals(language)){
           return data;
        }
        data.setMessage(null);
        return data;
    }

}
