package com.hh.lib_base.retrofit


import com.hh.lib_base.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier

/**
 * @Describe Retrofit工具类
 * @author Xia WeiHao
 * @date 2021/9/18
 */
object RetrofitUtils {
    @Volatile
    private var mInstance: RetrofitUtils? = null

    @Volatile
    var retrofit: Retrofit? = null
        get() {
            if (field == null) {
                synchronized(RetrofitUtils::class.java) {
                    if (field == null) {
                        field = initRetrofit()
                    }
                }
            }
            return field
        }
        private set

    /**
     * @Describe 初始化 RETROFIT
     * @author Xia WeiHao
     * @date 2021/10/9
     */
    private fun initRetrofit(): Retrofit {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(BuildConfig.BASE_URL)
            .client(initOkHttp())
            .build()
    }

    /**
     * @Describe 初始化 OKHTTP
     * @author Xia WeiHao
     * @date 2021/10/9
     */
    private fun initOkHttp(): OkHttpClient {
        val sslParams =
            HttpsUtils.getSslSocketFactory(null, null, null)
        //日志拦截器
        val loggingInterceptor =
            HttpLoggingInterceptor(HttpLogger())
        //设置日志拦截器的等级
        loggingInterceptor.level =
            HttpLoggingInterceptor.Level.NONE
        return OkHttpClient.Builder()
            .addInterceptor(HeaderInterceptor())
            .connectTimeout(10000L, TimeUnit.MILLISECONDS)
            .readTimeout(10000L, TimeUnit.MILLISECONDS)
            .writeTimeout(10000L, TimeUnit.MILLISECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(CommonAddAndHandleInterceptor())
            .hostnameVerifier(HostnameVerifier { hostname, session -> true })
            .sslSocketFactory(
                sslParams!!.sSLSocketFactory!!,
                sslParams!!.trustManager!!
            ) //当网络请求失败的时候，等到网络正常自动加载
            .retryOnConnectionFailure(true).build()
    }

    val instance: RetrofitUtils?
        get() {
            if (mInstance == null) {
                synchronized(RetrofitUtils::class.java) {
                    if (mInstance == null) {
                        mInstance = RetrofitUtils
                    }
                }
            }
            return mInstance
        }
}