package com.gingersoft.gsa.cloud.common.config.globalconfig.applyOptions.intercept;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.BuildConfig;
import com.gingersoft.gsa.cloud.common.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.oaId.DeviceID;
import com.gingersoft.gsa.cloud.common.utils.encryption.Aes;
import com.jess.arms.utils.DeviceUtils;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 添加請求頭信息
 */
public class HeadersInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
        String cacheControl = originalRequest.cacheControl().toString();

        Headers.Builder builder = new Headers.Builder();
        builder.set("mobileVersion", android.os.Build.VERSION.RELEASE); //安卓版本号
        builder.set("mobileModel", android.os.Build.MODEL);//手机型号
        builder.set("mobileBrand", android.os.Build.BRAND);//手机品牌
        builder.set("apptype", AppConstant.APP_TYPE);
        builder.set("appinfo", DeviceUtils.getVersionName(GsaCloudApplication.getAppContext()));
        builder.set("mobileId", "1");
        builder.set("uid", UserContext.newInstance().getMemberId() + "");

        String deviceId = DeviceID.getDeviceId();
        if (deviceId != null) {
            builder.set("deviceId", deviceId);
        }
        Headers headers = originalRequest.headers();
        for (int i = 0; i < headers.size(); i++) {
            builder.set(headers.name(i), headers.value(i));
        }
        if (UserContext.newInstance().isLogin()) {
            builder.set("token", getToken());
        } else if (BuildConfig.DEBUG) {
            builder.set("uuid", "999");
            builder.set("uid", "397");
        }
        Request requestWithUserAgent = originalRequest.newBuilder()
                .headers(builder.build())
                .build();
        return chain.proceed(requestWithUserAgent);
    }

    private String getToken() {
        String token = "";
        if (UserContext.newInstance().isLogin()) {
            int memberId = UserContext.newInstance().getMemberId();
            String loginToken = UserContext.newInstance().getLoginToken();
            token = Aes.aesEncrypt("9_" + memberId + "_" + System.currentTimeMillis() + "_" + loginToken);
            token = token.replaceAll("\r|\n", "");
        }
        return token;
    }
}