package com.jsc.oscm.util;

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;

public class HttpUtil {
    static final Logger logger = LogManager.getLogger(HttpUtil.class.getName());
    static final OkHttpClient httpClient = new OkHttpClient();

    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("CONNECTION ERROR: " + url);
        } finally {
            if (response != null) {
                Objects.requireNonNull(response.body()).close();
                response.close();
            }
        }
        return null;
    }

    public static String get(String url) {
        Request request = new Request.Builder().url(url).build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            logger.error("CONNECTION ERROR: " + url);
        } finally {
            if (response != null) {
                Objects.requireNonNull(response.body()).close();
                response.close();
            }
        }
        return null;
    }

    public static String formRequest(String url, Map<String, Object> formData) {
        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();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            logger.error("CONNECTION ERROR: " + url);
        } finally {
            if (response != null) {
                Objects.requireNonNull(response.body()).close();
                response.close();
            }
        }
        return null;
    }

    public static void multiPartRequest(String url, Map<String, Object> paramsMap, Map<String, Object> fileMap) {
        RequestBody fileBody = MultipartBody.create((byte[]) fileMap.get("bytes"), MediaType.get("application/octet-stream"));

        okhttp3.MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart(fileMap.get("name").toString(), fileMap.get("filename").toString(), fileBody);
        for (String key : paramsMap.keySet()) {
            builder.addFormDataPart(key, paramsMap.get(key).toString());
        }

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            logger.error("CONNECTION ERROR: " + url);
        } finally {
            if (response != null) {
                Objects.requireNonNull(response.body()).close();
                response.close();
            }
        }
    }

    public static void main(String[] args) {
        Map<String, Object> formData = new HashMap<>();
        formData.put("clientIP", "1.15.20.200");
        formData.put("filename", "中文测试.py");
        String result = formRequest("http://1.15.20.111:1201/api/fileDownload", formData);
        System.out.println(result);
    }
}
