package com.dahe.mylibrary.net;

import android.text.TextUtils;
import android.util.Log;


import com.google.zxing.common.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * json的Interceptor
 */

public class JsonInterceptor implements Interceptor {
    private static final String TAG = "JsonInterceptor";

    public JsonInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        //为了不消耗buffer，我们这里使用source先获得buffer对象，然后clone()后使用
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        //获得返回的数据
        Buffer buffer = source.buffer();
        //使用前clone()下，避免直接消耗
        String responseBodyStr = buffer.clone().readString(Charset.forName("UTF-8"));
        Log.i(TAG, "result-body= " + responseBodyStr);
        try {
            JSONObject jsonObject = new JSONObject(responseBodyStr);
            String str = jsonObject.optString("data");
            int code = jsonObject.optInt("code");
            if (-1 == code) {
                jsonObject.put("data", new JSONObject());
                throw new ResultException();
            } else {
                if (TextUtils.isEmpty(str)) {
                    jsonObject.put("data", new JSONObject());
                    //订单特殊处理
                    JSONObject order = jsonObject.optJSONObject("order");
                    if (order != null) {
//                        JSONArray rows = order.optJSONArray("rows");
                        JSONObject load = jsonObject.optJSONObject("load");
                        JSONObject billInfos = jsonObject.optJSONObject("billInfos");
                        JSONArray cars = jsonObject.optJSONArray("cars");
                        if (load!=null){
                            String loads = load.optString("loads");
                            order.putOpt("loads",loads);
                        }
                        if (billInfos!=null){
                            String num = billInfos.optString("num");
                            order.putOpt("num",num);
                        }
                        if (cars!=null&&cars.length()>0){
//                            String loads = load.optString("loads");
                            order.putOpt("cars",cars);
                        }
                        jsonObject.put("data", order);
                    } else {
                            //获取数量特殊处理
                        JSONArray countInfo = jsonObject.optJSONArray("countInfo");
                        if (countInfo != null) {
                            jsonObject.put("data", countInfo);
                        }
                    }

                    JSONArray rows = jsonObject.optJSONArray("rows");
                    if (rows!=null){
                        jsonObject.put("data", rows);
                    }

                    //上传凭证特殊处理
                    JSONObject waybillChild = jsonObject.optJSONObject("waybillChild");
                    JSONArray tmsBillInfos = jsonObject.optJSONArray("tmsBillInfos");
                    if (waybillChild != null || (tmsBillInfos != null&&tmsBillInfos.length()>0)) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("waybillChild", waybillChild);
                        jsonObject1.put("tmsBillInfos", tmsBillInfos);
                        jsonObject.put("data", jsonObject1);
                    }


                }
            }

            String data = jsonObject.toString();
            responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response = response.newBuilder().body(responseBody).build();
        return response;
    }
}
