package com.dtok.framework.http;

import com.dtok.framework.util.MD5Util;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OkHttpUtil {


    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();

    public static Response sendPostRequest(String url, Map<String, String> params) throws IOException {
        //动态添加参数
        FormBody.Builder formBody = new FormBody.Builder();
        //遍历参数,KV对应。
        for (Map.Entry<String, String> mapping : params.entrySet()) {
            formBody.add(mapping.getKey(), String.valueOf(mapping.getValue()));
        }

        Request request = new Request.Builder()
                .url(url)
                .post(formBody.build())
                .build();
        return okHttpClient.newCall(request).execute();
    }

    public static Response post(String url) throws IOException {
        //动态添加参数
        FormBody.Builder formBody = new FormBody.Builder();
        //遍历参数,KV对应

        Request request = new Request.Builder()
                .url(url)
                .post(formBody.build())
                .build();
        return okHttpClient.newCall(request).execute();
    }


    public static void encodingRequestBody(Map<String, String> params) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("he3yun.com-");
        Map<String, String> newMap = params.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
                stringStringEntry -> stringStringEntry.getValue().toLowerCase(Locale.ROOT)));

        Map<String, String> sortedParams = newMap.entrySet().stream().sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            stringBuilder.append(params.get(entry.getKey())).append("-");
        }
        String timestamp = String.valueOf(new Date().getTime());
        stringBuilder.append(timestamp);
        System.out.println("HASH: =>" + stringBuilder);
        System.out.println(MD5Util.stringToMD5(stringBuilder.toString()));
        params.put("timestamp", timestamp);
        params.put("hashCode", MD5Util.stringToMD5(stringBuilder.toString()));
    }

    public static Response get(String url, Map<String, String> params) throws IOException {
        HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            log.info(String.format("K: %s - V: %s", param.getKey(), param.getValue()));
        }

        Request request = new Request.Builder().url(httpBuilder.build())


                .build();
        return okHttpClient.newCall(request).execute();
    }

    public static Response get(String url) throws IOException {
        HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        Request request = new Request.Builder().url(httpBuilder.build())
                .build();
        return okHttpClient.newCall(request).execute();
    }

    public static Response get(String url, Map<String, String> params, Map<String, String> extraParam) throws IOException {
        for (Map.Entry<String, String> entry : extraParam.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            log.info(String.format("K: %s - V: %s", param.getKey(), param.getValue()));
        }

        Request request = new Request.Builder().url(httpBuilder.build())


                .build();
        return okHttpClient.newCall(request).execute();
    }

    public static Response get(String url, Map<String, String> params, String checkListDetail, String remark) throws IOException {

        HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            log.info(String.format("K: %s - V: %s", param.getKey(), param.getValue()));
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("checkListDetail", checkListDetail)
                .build();
        Request request = new Request.Builder().url(httpBuilder.build())
                .post(requestBody)
                .build();
        return okHttpClient.newCall(request).execute();
    }

    public static String upload(String url, Map<String, String> params, File file, Map<String, String> extraParam) throws IOException, UnirestException {
        for (Map.Entry<String, String> entry : extraParam.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        log.info(String.format("upload... %s", file.getName()));
        HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            log.info(String.format("K: %s - V: %s", param.getKey(), param.getValue()));
        }

        Request request = new Request.Builder().url(httpBuilder.build()).build();
        System.out.println(file.getName());

        System.out.println(String.valueOf(request.url()));
        HttpResponse<String> response =
                Unirest.post(String.valueOf(request.url()))
                        .field("fileData", file)
                        .asString();
        return response.getBody();
    }


}
