package com.gingersoft.gsa.cloud.globalconfig.applyOptions;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.constans.AppConstans;
import com.gingersoft.gsa.cloud.base.utils.encryption.Aes;
import com.jess.arms.http.GlobalHttpHandler;
import com.jess.arms.utils.DeviceUtils;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


public class MyGlobalHttpHandler implements GlobalHttpHandler {

    private final String TAG = this.getClass().getSimpleName();

    @Override
    public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
        // 统一处理http响应。eg:状态码不是200时，根据状态码做相应的处理。
        e(httpResult);
        return response;
    }

    @Override
    public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
        // 统一处理http请求。eg:给request统一添加token或者header以及参数加密等操作
        String requestBody = request.toString();
        e(requestBody);
        String url = chain.request().url().url().toString();
        String token = "";

        if (GsaCloudApplication.isLogin) {
            int memberId = GsaCloudApplication.getMemberId(GsaCloudApplication.getAppContext());
            String loginToken = GsaCloudApplication.getLoginToken(GsaCloudApplication.getAppContext());
            token = Aes.aesEncrypt("9_" + memberId + "_" + System.currentTimeMillis() + "_" + loginToken);
            token = token.replaceAll("\r|\n", "");
        }
        Headers.Builder builder = new Headers.Builder();
        builder.set("mobileVersion", android.os.Build.VERSION.RELEASE);//set表示name1是唯一的，会覆盖掉已经存在的，add不会覆盖已经存在的头，可以存在多个
        builder.set("mobielModel", android.os.Build.MODEL);
        builder.set("apptype", AppConstans.APP_TYPE);
        builder.set("appinfo", DeviceUtils.getVersionName(GsaCloudApplication.getAppContext()));
        builder.set("mobileId", "1");
        Headers headers = request.headers();
        if (headers != null) {
            for (int i = 0; i < headers.size(); i++) {
                builder.set(headers.name(i), headers.value(i));
            }
        }
        if (GsaCloudApplication.isLogin)
            builder.set("token", token);
//        builder.set("Domain-Name", "common");

        return chain.request().newBuilder()
                .headers(builder.build())
                .build();
    }


    private void e(String msg) {
//        if (msg == null) {
//            return;
//        }
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
        //  把4*1024的MAX字节打印长度改为2001字符数
//        int max_str_length = 2001 - TAG.length();
        //大于4000时
//        while (msg.length() > max_str_length) {
//            LogUtil.e(TAG, msg);
//            msg = msg.substring(max_str_length);
//        }
        //剩余部分
//        LogUtil.e(TAG, msg);
    }


}
