package com.jsc.dsp.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import okhttp3.FormBody.Builder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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

public class HttpUtils {
    static final Logger logger = LogManager.getLogger(HttpUtils.class.getName());
    static final OkHttpClient httpClient = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS).build();

    public static String post(String url, Object data) {
        RequestBody requestBody = RequestBody.create(JSON.toJSONBytes(data), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = null;
        try {
            Call call = httpClient.newCall(request);
            response = call.execute();
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }

    public static String get(String url) {
//		OkHttpClient httpClient = new OkHttpClient();

        Request request = new Request.Builder().url(url).build();
        try (Response response = httpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    public static String formRequest(String url, Map<String, Object> formData) {
//		OkHttpClient httpClient = new OkHttpClient();
        Builder formBodyBuilder = new FormBody.Builder();
        for (String key : formData.keySet()) {
            formBodyBuilder.add(key, formData.get(key).toString());
        }
        Request request = new Request.Builder().url(url).post(formBodyBuilder.build()).build();
        try (Response response = httpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 解析url
     *
     */
    public static Map<String, String> parse(String urlParams) {
        if (urlParams == null || urlParams.trim().equals("")) {
            return null;
        }
        if (urlParams.startsWith("\"") && urlParams.endsWith("\"")) {
            urlParams = urlParams.substring(1, urlParams.length() - 1);
        }
        String[] paramsList = urlParams.split("&");
        Map<String, String> params = new HashMap<>();
        for (String param : paramsList) {
            String[] keyValue = param.split("=");
            if (keyValue.length > 1) {
                params.put(keyValue[0], keyValue[1]);
            } else {
                params.put(keyValue[0], "");
            }
        }
        return params;
    }
}