package cn.cslg.pas.common.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

@Component
public class ApiUtils {
    @Value("${authorUrl}")
    private String url;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public String invokeApi(JSONObject params, String api, String type, String field) throws IOException {
        RequestBody postParams = RequestBody.create(JSON, String.valueOf(params));
        OkHttpClient okHttpClient = new OkHttpClient();
        String resBody = null;
        if (type.equals("post")) {
            Request request = new Request.Builder()
                    .url(url + api)
                    .post(postParams)
                    .build();
            resBody = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
        } else if (type.equals("get")) {
            Request request = new Request.Builder()
                    .url(url + api)
                    .get()
                    .build();
            resBody = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
        }

        JSONObject jsonObject = JSONObject.parseObject(resBody, JSONObject.class);
        return jsonObject.get(field).toString();
    }
}
