package com.stm.asset.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stm.asset.base.StmApplication;
import com.stm.asset.utils.PropertyUtil;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.annotations.EverythingIsNonNull;

/**
 * 类名称：HttpUtil
 * 类描述：网络请求工具类
 * 创建人：story
 * 创建时间：2021-12-10 17:15
 */
public class HttpUtil {

    private static HttpUtil httpUtil;
    private OkHttpClient okHttpClient;

    private HttpUtil() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new LoggingInterceptor());
        if (PropertyUtil.isUseHttps(StmApplication.getInstance().getApplicationContext())) {
            try {
                builder.hostnameVerifier(TrustAllSSLSocketFactory.getHostnameVerifier());
                builder.sslSocketFactory(TrustAllSSLSocketFactory.createSSLSocketFactory(), new TrustAllSSLSocketFactory.TrustAllManager());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        builder.callTimeout(20000, TimeUnit.MILLISECONDS);
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        builder.readTimeout(60000, TimeUnit.MILLISECONDS);
        builder.writeTimeout(60000, TimeUnit.MILLISECONDS);
        okHttpClient = builder.build();
    }

    public static HttpUtil getInstance() {
        if (httpUtil == null) {
            httpUtil = new HttpUtil();
        }
        return httpUtil;
    }

    public void sendJson1(String interfaceName, RequestParams requestParams, RequestCallback callback) {
//        StmApplication.getInstance().getAppExecutors().networkIO().execute(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        });


        Request.Builder builder = new Request.Builder();
        String url = buildUrl(interfaceName);
        Log.i("HttpUtil", String.format("请求方法: %s", url));
        builder.url(url);
        if (requestParams.getHeaders() != null && requestParams.getHeaders().size() > 0) {
            Log.i("HttpUtil", String.format("请求参数 head：%s", new Gson().toJson(requestParams.getHeaders())));
            for (Map.Entry<String, String> headerEntry : requestParams.getHeaders().entrySet()) {
                builder.header(headerEntry.getKey(), headerEntry.getValue());
            }
        }
        if (requestParams.getBodyParams() != null && requestParams.getBodyParams().size() > 0) {
            Log.i("HttpUtil", String.format("请求参数 body：%s", new Gson().toJson(requestParams.getBodyParams())));
//                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestParams.getBodyParams()));
//                    builder.post(requestBody);
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : requestParams.getBodyParams().entrySet()) {
                bodyBuilder.add(entry.getKey(), entry.getValue());
            }
            builder.post(bodyBuilder.build());
        }
        Request request = builder.build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            @EverythingIsNonNull
            public void onFailure(Call call, IOException e) {
                callback.onFailure(new HttpException(e.getCause()), e.getMessage());
            }

            @Override
            @EverythingIsNonNull
            public void onResponse(Call call, Response response) {
                boolean flag = false;
                if (response.isSuccessful()) {
                    try {
                        ResponseBody body = response.body();
                        if (body != null) {
                            String result = body.string();
                            Log.i("HttpUtil", result);
                            callback.onSuccess(new Gson().fromJson(result, TypeToken.get(callback.getType()).getType()));
                            flag = true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (!flag) {
                    callback.onFailure(new HttpException("返回数据异常"), "返回数据异常");
                }
            }
        });
    }


    public void sendJson(String interfaceName, RequestParams requestParams, RequestCallback callback) {
        Request.Builder builder = new Request.Builder();
        String url = buildUrl(interfaceName);
        Log.i("HttpUtil", String.format("请求方法: %s", url));
        builder.url(url);
        if (requestParams.getHeaders() != null && requestParams.getHeaders().size() > 0) {
            Log.i("HttpUtil", String.format("请求参数 head：%s", new Gson().toJson(requestParams.getHeaders())));
            for (Map.Entry<String, String> headerEntry : requestParams.getHeaders().entrySet()) {
                builder.header(headerEntry.getKey(), headerEntry.getValue());
            }
        }
        if (requestParams.getBodyParams() != null && requestParams.getBodyParams().size() > 0) {
            Log.i("HttpUtil", String.format("请求参数 body：%s", new Gson().toJson(requestParams.getBodyParams())));
//            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestParams.getBodyParams()));
//            builder.post(requestBody);
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : requestParams.getBodyParams().entrySet()) {
                bodyBuilder.add(entry.getKey(), entry.getValue());
            }
            builder.post(bodyBuilder.build());
        }
        Request request = builder.build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            @EverythingIsNonNull
            public void onFailure(Call call, IOException e) {
                StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(new HttpException(e.getCause()), e.getMessage());
                    }
                });
            }

            @Override
            @EverythingIsNonNull
            public void onResponse(Call call, Response response) {
                StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        boolean flag = false;
                        if (response.isSuccessful()) {
                            try {
                                ResponseBody body = response.body();
                                if (body != null) {
                                    String result = body.string();
                                    Log.i("HttpUtil", result);
                                    callback.onSuccess(new Gson().fromJson(result, TypeToken.get(callback.getType()).getType()));
                                    flag = true;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (!flag) {
                            callback.onFailure(new HttpException("返回数据异常"), "返回数据异常");
                        }
                    }
                });
            }
        });
    }

    private String buildUrl(String interfaceName) {
        StmApplication sap = StmApplication.getInstance();
        StringBuilder sbd = new StringBuilder();
        boolean isHttps = PropertyUtil.isUseHttps(sap.getApplicationContext());
        if (isHttps) {
            sbd.append("https://");
        } else {
            sbd.append("http://");
        }
        String address = PropertyUtil.getHttpAddress(sap.getApplicationContext());
        sbd.append(address);
        String port = PropertyUtil.getHttpPort(sap.getApplicationContext());
        if (port != null && !port.equals("")) {
            sbd.append(":");
            sbd.append(port);
        }
        sbd.append("/");
        sbd.append(interfaceName);
        sbd.append(".app");
        return sbd.toString();
    }

}
