package com.danding.yang800.Util;

import android.content.Context;
import android.content.SharedPreferences;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.danding.yang800.BuildConfig;
import com.danding.yang800.General.HttpCallBack;
import com.danding.yang800.General.SingleRequestQueue;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 所以网络请求都是通过此类处理
 */
public class VolleyUtil {
    RequestQueue requestQueue;
    SharedPreferences sp;

    public VolleyUtil(Context context) {
        requestQueue = SingleRequestQueue.getRequestQueue(context);
        sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
    }

    public void request(final Context context, final String url, final boolean toast, final HashMap<String, String> param, final HttpCallBack httpCallBack) {
        LogUtil.d("http://" + BuildConfig.HOSTURL + "/api/gateway");
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                "http://" + BuildConfig.HOSTURL + "/api/gateway",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        LogUtil.d(response);
                        try {
                            JSONObject json = new JSONObject(response);
                            boolean success = json.getBoolean("success");
                            if (success) {
                                httpCallBack.onSuccess(json);
                            } else {
                                if (toast) {
                                    String errorMsg = json.getString("errorMessage");
                                    ToastUtil.show(context, errorMsg);
                                }
                                httpCallBack.onerrSuccess();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            httpCallBack.onFail();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                httpCallBack.onFail();
                LogUtil.d(error.toString());
//                if (NetUtil.getNetWorkState(context) == NetUtil.NETWORK_NONE && toast) {
//                    ToastUtil.show(context, "请检查您的网络");
//                }
            }
        }) {
            @Override
            protected HashMap<String, String> getParams() { //
                param.put("appKey", "yang800_wd");
                param.put("pampasCall", url);
                String sign = "";
                try {
                    sign = GeneralUtil.generateSignature(param, BuildConfig.SECRET);
                    LogUtil.d(sign + "sign");
//                    sign = GeneralUtil.generateSignature(param, "wd$ed380edc3f9802eb");
                } catch (Exception e) {
                }
                param.put("sign", sign);
                return param;
            }

            protected Response<String> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    Map<String, String> responseHeaders = response.headers;
                    String rawCookies = responseHeaders.get("Set-Cookie");
                    LogUtil.d(rawCookies + "rawCookies");
                    if (rawCookies != null && rawCookies.contains("store_id")) {
                        if (rawCookies.length() > 0) {
                            String[] splitCookie = rawCookies.split(";");
                            String cookie = splitCookie[0];
                            sp.edit().putString("Cookie", cookie).commit();
                        }
                    }
//                    if (sp.getString("Cookie", "").equals("")) {
//                        sp.edit().putString("Cookie", rawCookies).commit();
//                    }
                    String dataString = new String(response.data, "UTF-8");
                    return Response.success(dataString,
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (!sp.getString("Cookie", "").equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Cookie", sp.getString("Cookie", ""));
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        stringRequest.setTag("POST_TAG");
        requestQueue.add(stringRequest);
    }

    public void jsonRequest(final Context context, final JSONObject json, final HttpCallBack httpCallBack) {
        LogUtil.d(json.toString());
        JsonObjectRequest jsonOR = new JsonObjectRequest(Request.Method.POST,
                "https://" + BuildConfig.HOSTURL + "/api/gateway", json, new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject json) {
                try {
                    boolean success = json.getBoolean("success");
                    if (success) {
                        httpCallBack.onSuccess(json);
                    } else {
                        String errorMsg = json.getString("errorMessage");
                        ToastUtil.show(context, errorMsg);
                        httpCallBack.onerrSuccess();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    httpCallBack.onFail();
                }
            }
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                httpCallBack.onFail();
                LogUtil.d("err");
//                if (NetUtil.getNetWorkState(context) == NetUtil.NETWORK_NONE) {
//                    ToastUtil.show(context, "请检查您的网络");
//                }
            }
        }) {
            //            @Override
//            public byte[] getBody() {
//                HashMap<String, String> map = new HashMap<String, String>();
//                return encodeParameters(map, getParamsEncoding());
//            }
//            @Override
//            protected HashMap<String, String> getPostParams() { //
//                HashMap<String, String> map = new HashMap<String, String>();
//                map.put("appKey", "yang800_wd");
//                map.put("pampasCall", "store.goodsSort.update.goodsSort");
//                map.put("data", json.toString());
//                String sign = "";
//                try {
//                    sign = GeneralUtil.generateSignature(map, "wd$d_684");
//                    LogUtil.d(sign);
//                } catch (Exception e) {
//                }
//                map.put("sign", sign);
//                return map;
//            }


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
//                if (!sp.getString("Cookie", "").equals("")) {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Cookie", sp.getString("Cookie", ""));
                headers.put("x-op-req-body", "true");
                return headers;
//                } else {
//                    return super.getHeaders();
//                }
            }
        };
        requestQueue.add(jsonOR);
    }
//    public static HashMap getMap(ArrayList list) {
//        HashMap<String, String> map = new HashMap<String, String>();
//        if (list.size() > 0) {
//            for (String param : str) {
//                    map.put(param+"",param);
//            }
//        }
//    }
//    public void jsonRequest(final Context context, final String url, final boolean toast, final HashMap<String, String> param, final HttpCallBack httpCallBack) {
//        StringRequest stringRequest = new StringRequest(Request.Method.POST,
//                "http://" + BuildConfig.HOSTURL + "/api/gateway",
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        LogUtil.d(response);
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            boolean success = json.getBoolean("success");
//                            if (success) {
//                                httpCallBack.onSuccess(json);
//                            } else {
//                                if (toast) {
//                                    String errorMsg = json.getString("errorMessage");
//                                    ToastUtil.show(context, errorMsg);
//                                }
//                                httpCallBack.onerrSuccess();
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            httpCallBack.onFail();
//                        }
//
//                    }
//                }, new Response.ErrorListener() {
//
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                httpCallBack.onFail();
//                LogUtil.d("error");
//            }
//        }) {
//            @Override
//            protected HashMap<String, String> getParams() { //
//                param.put("appKey", "yang800_wd");
//                param.put("pampasCall", url);
//                String sign = "";
//                try {
//                    sign = GeneralUtil.generateSignature(param, "wd$d_684");
//                    LogUtil.d(sign);
//                } catch (Exception e) {
//                }
//                param.put("sign", sign);
//                return param;
//            }
//
//            protected Response<String> parseNetworkResponse(
//                    NetworkResponse response) {
//                try {
//                    Map<String, String> responseHeaders = response.headers;
//                    String rawCookies = responseHeaders.get("Set-Cookie");
//                    LogUtil.d(rawCookies + "rawCookies");
//                    if (rawCookies != null) {
//                        if (rawCookies.length() > 0) {
//                            String[] splitCookie = rawCookies.split(";");
//                            String cookie = splitCookie[0];
//                            sp.edit().putString("Cookie", cookie).commit();
//                        }
//                    }
////                    if (sp.getString("Cookie", "").equals("")) {
////                        sp.edit().putString("Cookie", rawCookies).commit();
////                    }
//                    String dataString = new String(response.data, "UTF-8");
//                    return Response.success(dataString,
//                            HttpHeaderParser.parseCacheHeaders(response));
//                } catch (UnsupportedEncodingException e) {
//                    return Response.error(new ParseError(e));
//                }
//            }
//
//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                if (!sp.getString("Cookie", "").equals("")) {
//                    HashMap<String, String> headers = new HashMap<String, String>();
//                    headers.put("Cookie", sp.getString("Cookie", ""));
//                    headers.put("x-op-req-body", "true");
//                    return headers;
//                } else {
//                    return super.getHeaders();
//                }
//            }
//        };
//        stringRequest.setTag("POST_TAG");
//        requestQueue.add(stringRequest);
//    }
}
