package com.qiuguo.iot.base.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

public class WebClientUtils {
    private static WebClient webClient = WebClient.builder().defaultHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE).build();

    public static Mono<JSONObject> get(String url) {
        return get(url, null);

    }

    public static Mono<JSONObject> post(String url, JSONObject body) {
        return post(url, body, null);

    }

    public static Mono<JSONObject> get(String url, Map<String, String> headers) {
        if(headers == null || headers.size() == 0) {
            return webClient.get().uri(url).retrieve().bodyToMono(JSONObject.class);
        }else{
            return webClient.get().uri(url).headers(httpHeaders -> {
                for (String key:headers.keySet()
                     ) {
                    httpHeaders.set(key, headers.get(key));
                }
            }).retrieve().bodyToMono(JSONObject.class);
        }

    }

    public static Mono<JSONObject> post(String url, JSONObject body, Map<String, String> headers) {
        if(headers == null || headers.size() == 0) {
            return webClient.post().uri(url).bodyValue(body.toString()).retrieve().bodyToMono(JSONObject.class);
        }else{
            return webClient.post().uri(url).bodyValue(body.toString()).headers(httpHeaders -> {
                for (String key:headers.keySet()
                ) {
                    httpHeaders.set(key, headers.get(key));
                }
            }).retrieve().bodyToMono(JSONObject.class);
        }

    }

}
