package com.zhimai.websocket.http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


import com.zhimai.websocket.util.Logger;

import org.json.JSONObject;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 新版本okhttp
 */
public class MyOkHttpUtils {
    private static final String TAG = "----MyOkHttpUtils----";
    private static MyOkHttpUtils myOkHttpUtils;

    private static final int CONNECTION_TIME_OUT = 2000;//连接超时时间
    private static final int SOCKET_TIME_OUT = 2000;//读写超时时间
    private static final int MAX_IDLE_CONNECTIONS = 30;// 空闲连接数
    private static final long KEEP_ALLIVE_TIME = 60000L;//保持连接时间


    //1. 创建OkhttpClient 对象
//    private static OkHttpClient client=new OkHttpClient.Builder().connectTimeout(10000L, TimeUnit.MILLISECONDS)
//                    .readTimeout(10000L, TimeUnit.MILLISECONDS).build();
    private OkHttpClient client;

    public static MyOkHttpUtils getInstance() {
        if (myOkHttpUtils == null) {
            myOkHttpUtils = new MyOkHttpUtils();

        }
        return myOkHttpUtils;
    }

    public MyOkHttpUtils() {
//        client=new OkHttpClient.Builder().connectTimeout(10000L, TimeUnit.MILLISECONDS)
//                .readTimeout(10000L, TimeUnit.MILLISECONDS).build();
//        client=new OkHttpClient();
        ConnectionPool connectionPool = new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALLIVE_TIME, TimeUnit.MILLISECONDS);
        this.client = new OkHttpClient()
                .newBuilder()
                .readTimeout(SOCKET_TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(SOCKET_TIME_OUT, TimeUnit.MILLISECONDS)
                .connectionPool(connectionPool)
                .retryOnConnectionFailure(false) //自动重连设置为false
                .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(new RetryIntercepter(2)) //重试拦截器2次
                .addNetworkInterceptor(new NetworkIntercepter()) //网络拦截器，统一打印日志---
                .build();

    }

    private void init() {

    }

    public void get(String url, Map<String, String> pathParams, String token, final CallBackListener callBackListener) {
        HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
        for (String key : pathParams.keySet()) {
            builder.addQueryParameter(key, pathParams.get(key));
        }
        //2. 创建请求的Request 对象
        Request request = new Request.Builder()
                .get()
                .url(builder.build().toString())
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                .addHeader("QM-STORE-AUTH", "undefined")
                .addHeader("X-CSRF-TOKEN", "{{csrf_token()}}")
                .addHeader("Connection", "keep-alive")
                .addHeader("Accept", "*/*; v=1.0")
//                .addHeader("Referer", MyApplication.INAPI_BASE_RUL_HEAD)
//                .addHeader("Qm-From", "android")
                .addHeader("Qm-From-Type", "cy")
                .addHeader("Qm-Account-Token", token)
                .addHeader("Qm-seller-Token", token)
//                .addHeader("Qm-Account-Token",  Constant.Token)
                .addHeader("Qm-From", "android")
                .addHeader("Accept-Encoding", "identity")//服务器发的数据 压缩了，需要解压
                .build();

        //3. 在Okhttp中创建Call 对象，将request和Client进行绑定
        //4. 执行Call对象（call 是interface 实际执行的是RealCall）中的`execute`方法
//        try (Response response = client.newCall(request).execute()) {
//            return response.body().string();
//        }

        Call call = client.newCall(request);
//        try {
//
//            String result2=call.execute().body().string();
//            Logger.e(TAG,"返回数据："+result2);
//        }catch (IOException e){
//            Logger.e(TAG,"返回数据异常："+e.getMessage());
//        }

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callBackListener != null) {
                    callBackListener.error(e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (callBackListener != null) {
                    try {
                        String result = response.body().string();
                        Logger.e(TAG, "返回数据：" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optBoolean("status", false)) {
                            if (callBackListener != null) {
                                callBackListener.success(jsonObject.optString("data"));
                            }
                        } else {
                            if (callBackListener != null) {
                                callBackListener.fail(jsonObject.optString("message"));
                            }
                        }

                    } catch (Exception e) {
                        Logger.e(TAG, "返回数据异常：" + e.getMessage());
                        if (callBackListener != null) {
                            callBackListener.fail("返回数据异常");
                        }
                    }

                }
            }
        });
    }
    public void post(String url, Map<String, String> pathParams, String token, String baseUrl, final CallBackListener callBackListener) {
        RequestBody body = setRequestBody(pathParams);
        post(url, body, token, baseUrl, callBackListener);
    }
    public void post(String url,RequestBody body, String token, String baseUrl, final CallBackListener callBackListener) {
        Logger.e(TAG, "请求数据： url = " + url +"  ;; baseUrl = "+baseUrl);
        //1构造RequestBody
//        RequestBody body = setRequestBody(pathParams);
        //2. 创建请求的Request 对象
        Request request = new Request.Builder()
                .post(body)
                .url(url)//Accept-Encoding: identity

//                .addHeader("Accept", "application/json, text/plain, */*")
//                .addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
//                .addHeader("QM-STORE-AUTH", "undefined")
//                .addHeader("X-CSRF-TOKEN", "{{csrf_token()}}")
//                .addHeader("Connection", "keep-alive")
//                .addHeader("Accept", "*/*; v=1.0")
////                .addHeader("Referer", UrlUtils.BASICKURL)
//                .addHeader("Referer", baseUrl)
//                .addHeader("Qm-From-Type", "cy")
//                .addHeader("Qm-Account-Token", token)///----新机构中心不用这个  用 qm_seller_token
//                .addHeader("Qm-seller-Token", token)//新机构中心 token
//                .addHeader("Qm-From", "android")

                .addHeader("Accept", "*/*; v=1.0")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                .addHeader("Accept-Encoding", "identity")//服务器发的数据 压缩了，需要解压
                .addHeader("QM-STORE-AUTH", "undefined")
                .addHeader("X-CSRF-TOKEN", "{{csrf_token()}}")
                .addHeader("Connection", "keep-alive")
                .addHeader("Referer", baseUrl)
                .addHeader("Cookie", "qm_account_token="+token)
                .addHeader("content-type", "application/json")
                .addHeader("User-Agent", "wechatdevtools appservice port/62739")
                .addHeader("Qm-From-Type", "retail")
                .addHeader("Authorization", "Bearer $CommParamsRegister.instance.getToken()")
                .addHeader("Qm-Account-Token", token)
                .addHeader("Qm-seller-Token", token)
                .addHeader("Qm-From", "android")

                .build();

        Call call = client.newCall(request);
//        try {
//
//            String result2=call.execute().body().string();
//            Logger.e(TAG,"返回数据："+result2);
//        }catch (IOException e){
//            Logger.e(TAG,"返回数据异常："+e.getMessage());
//        }
        call.enqueue(new CallbackToMainThread(new CallbackToMainThread.MCallback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callBackListener != null) {
                    callBackListener.error(e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (callBackListener != null) {
                    try {
                        String result = response.body().string();
                        Logger.e(TAG, "返回数据：" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optBoolean("status", false)) {
                            if (callBackListener != null) {
                                callBackListener.success(jsonObject.optString("data"));
                            }
                        } else {
                            if (callBackListener != null) {
                                callBackListener.fail(jsonObject.optString("message"));
                            }
                        }

                    } catch (Exception e) {
                        Logger.e(TAG, "返回数据异常：" + e.getMessage());
                        if (callBackListener != null) {
                            callBackListener.fail("返回数据异常:"+ e.getMessage());
                        }
                    }

                }
            }
        }));

//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                if (callBackListener != null) {
//                    callBackListener.error(e.getMessage());
//                }
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) {
//                if (callBackListener != null) {
//                    try {
//                        String result = response.body().string();
//                        Logger.e(TAG, "返回数据：" + result);
//                        JSONObject jsonObject = new JSONObject(result);
//                        if (jsonObject.optBoolean("status", false)) {
//                            if (callBackListener != null) {
//                                callBackListener.success(jsonObject.optString("data"));
//                            }
//                        } else {
//                            if (callBackListener != null) {
//                                callBackListener.fail(jsonObject.optString("message"));
//                            }
//                        }
//
//                    } catch (Exception e) {
//                        Logger.e(TAG, "返回数据异常：" + e.getMessage());
//                        if (callBackListener != null) {
//                            callBackListener.fail("返回数据异常");
//                        }
//                    }
//
//                }
//            }
//        });
    }

    /**
     * post的请求参数，构造RequestBody
     *
     * @param BodyParams
     * @return
     */
    private RequestBody setRequestBody(Map<String, String> BodyParams) {
        RequestBody body = null;
        okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
        if (BodyParams != null) {
            Iterator<String> iterator = BodyParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formEncodingBuilder.add(key, BodyParams.get(key));
//                Log.d("post http", "post_Params==="+key+"===="+BodyParams.get(key));
            }
        }
        body = formEncodingBuilder.build();
        return body;
    }

    /**
     * 判断网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            //如果仅仅是用来判断网络连接
            //则可以使用cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


}
