package network.config.applyOptions;

import com.jess.arms.http.GlobalHttpHandler;
import com.joe.base.application.BaseApplication;
import com.joe.base.utils.constans.AppConstans;
import com.joe.base.utils.constans.UserConstans;
import com.joe.base.utils.encryption.Aes;
import com.joe.base.utils.log.LogUtil;
import com.joe.base.utils.other.AppUtils;
import com.joe.base.utils.request.RequestUtils;

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时，根据状态码做相应的处理。
        LogUtil.d("onHttpResultResponse: " + httpResult);
        e(httpResult);
        return response;
    }

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

        String token = Aes.aesDecrypt(UserConstans.memberId + "_" + System.currentTimeMillis() + "_" + UserConstans.token);
        if (request.method().equals("GET") || request.method().equals("POST")) {
            Headers headers = new Headers.Builder()
                    .set("secretKey", AppConstans.SECRETKEY_VALUES)//set表示name1是唯一的，会覆盖掉已经存在的，add不会覆盖已经存在的头，可以存在多个
                    .set("apptype", AppConstans.APP_TYPE)
                    .set("appinfo", AppUtils.getVerName(BaseApplication.getAppContext()))
                    .set("mobielModel", android.os.Build.MODEL)
                    .set("mobileVersion", android.os.Build.VERSION.RELEASE)
                    .set("mobileId", RequestUtils.getMobileToken(BaseApplication.getAppContext()))
                    .set("token", token)
//                    .set("encrypt", 1 + "")
//                    .set("uid", UserConstans.memberId + "")
//                    .set("appVersion", SApplication.VerCode + "")
                    .set("Domain-Name", "common")
                    .build();
            return chain.request().newBuilder()
                    .headers(headers)
                    .build();
        }
        return chain.request().newBuilder()
                .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);
    }


}
