package com.tjzhxx.union.public_store.retrofit;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.tjzhxx.union.public_store.LogUtils;

import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 描述:
 * @author yanghuaxiong
 * @create 2018/5/4 下午4:35
 *
 */
public class RetrofitUtils {
    private static Retrofit singleton;
    private static CookieManager cookieManager;
    private final static int CONNECT_TIMEOUT = 30;
    private final static int READ_TIMEOUT = 30;
    private final static int WRITE_TIMEOUT = 30;

    /**
     * @param clazz
     * @param baseUrl
     * @param <T>
     * @return
     */
    public static <T> T createApi(Class<T> clazz, String baseUrl) {
        if (singleton == null) {
            synchronized (RetrofitUtils.class) {
                if (singleton == null) {
                    Retrofit.Builder builder = new Retrofit.Builder();
                    builder.baseUrl(baseUrl);
                    builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
                    builder.addConverterFactory(GsonConverterFactory.create());
                    //设置cookie管理d
                    cookieManager = (cookieManager != null ? cookieManager : new CookieManager());
                    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

                    OkHttpClient.Builder okBuilder = new OkHttpClient.Builder()
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//设置连接超时时间
                    okBuilder.addInterceptor(new RequestInterceptor());
                    builder.client(okBuilder.build());

                    singleton = builder.build();

                    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                        }
                    });
                }
            }
        }
        return singleton.create(clazz);
    }
    /**
     * 请求拦截器，保存cookie和  修改请求header
     */
    private static class RequestInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request()
                    .newBuilder()
//                    .addHeader("Accept","*/*")
//                    .addHeader("Accept-Language", languageS)
//                    .addHeader("Authorization", UserInfoPreUtils.getInstance(RentingApplication.getInstance()).getAuthorization())
//                    .addHeader("Wellcee-DID",Constants.EuipmentID)
                    .build();
            Response response = chain.proceed(request);
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            LogUtils.e("TAG", chain.request().url().toString());
            LogUtils.e("TAG", content);
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();
//            return response;
        }
    }
}
