package com.union.ai.api.util;

import com.alibaba.fastjson.JSON;
import com.union.ai.api.dto.BaseParamDto;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 *
 */
@Slf4j
public class HttpClientUtil {


    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");

    private static int CONNECT_TIMEOUT = Integer.valueOf(PropertiesUtil.getProperty("http.connect.timeout", "5"));
    private static int WRITE_TIMEOUT = Integer.valueOf(PropertiesUtil.getProperty("http.write.timeout", "5"));
    private static int READ_TIMEOUT = Integer.valueOf(PropertiesUtil.getProperty("http.read.timeout", "5"));

    public static String sendPostJSON(String url, Object bizData) {

        String param = null;
        if (bizData instanceof String) {
            param = (String) bizData;
        } else {
            param = JSON.toJSONString(bizData);
        }
        String realUrl = url + "?appid=" + ThreadLocalUtil.appIdThreadLocal.get();
        log.info("请求百度url={}, begin ...", realUrl);
        String ret = HttpClientUtil.httpPostJson(realUrl, param);
        log.info("请求百度url={}, 结果：{}", realUrl, ret);
        return ret;
    }

    private static String httpPostJson(String url,  String jsonData){
        Request request = null;
        String result=null;
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if(StringUtils.isNotBlank(jsonData)){
            RequestBody body = RequestBody.create(JSON_TYPE, jsonData);
            requestBuilder.post(body);
        }
        request = requestBuilder.build();
        Call call = getOkHttpClient().newCall(request);
        try {
            Response response = call.execute();
            result=response.body().string();
        } catch (Exception e) {
            log.error("请求百度接口错误,url={},params={}", url, jsonData, e);
        }
        return result;
    }

    public static String httpPost(String url, Map<String,String> jsonData){

        String result=null;
        FormBody.Builder builder = new FormBody.Builder();
        if (!CollectionUtils.isEmpty(jsonData)) {
            for (String key : jsonData.keySet()) {
                builder.add(key, jsonData.get(key));
            }
        }
        FormBody formBody = builder.build();
        String realUrl = url + "?appid=" + ThreadLocalUtil.appIdThreadLocal.get();
        Request request = new Request.Builder()
                .url(realUrl)
                .post(formBody)
                .build();
        try {
            Call call = getOkHttpClient().newCall(request);
            Response response = call.execute();
            result=response.body().string();
        } catch (Exception e) {
            log.error("请求百度接口错误,url={},params={}", url, jsonData, e);
        }
        return result;
    }

    private static OkHttpClient getOkHttpClient() {
        return new OkHttpClient().newBuilder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(50,5,TimeUnit.MINUTES))
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .build();
    }
}
