package network.config.applyOptions;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.request.RequestUtils;
import com.jess.arms.http.GlobalHttpHandler;
import com.gingersoft.gsa.cloud.base.utils.constans.AppConstans;
import com.gingersoft.gsa.cloud.base.utils.encryption.Aes;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.base.utils.other.AppUtils;

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", "");
        }
//        String token = "e64a3959460141a4996d92ab07b0e14b";

        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", AppUtils.getVerName(GsaCloudApplication.getAppContext()));
        builder.set("mobileId", "1");
        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);
    }


}
