package com.xty.network

import com.xty.network.json.FastJsonConverterFactory
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import org.apache.http.conn.ssl.AllowAllHostnameVerifier
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

class MyRetrofit private constructor() {
    var BLUETOOTH_MAC="" //蓝牙mac地址
    private val url by lazy { BuildConfig.url }

     companion object {
        private var instance: MyRetrofit? = null
            get() {
                if (field == null) {
                    field = MyRetrofit()
                }
                return field
            }

        fun get(): MyRetrofit {
            return instance!!
        }
    }





    private fun okhttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .writeTimeout(30000, TimeUnit.SECONDS)
            .connectTimeout(30000, TimeUnit.SECONDS)
            .readTimeout(30000, TimeUnit.SECONDS)
            .callTimeout(30000, TimeUnit.SECONDS)
            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())           //忽略证书验证
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .addInterceptor(TokenIntercept())
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
            .build()
    }

    fun initRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl(url)
            .client(okhttpClient())
            .addConverterFactory(FastJsonConverterFactory.create())
            // .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun <T> create(clazz: Class<T>): T {
        return initRetrofit().create(clazz)
    }

    /**
     * 字符串转换RequestBody
     */
    fun getRequestBody(json: String): RequestBody {
        return RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(), json)
    }

 /*   *//**
     * 得到 mulitpart 类型的转换RequestBody
     *//*
    fun getMultiPartStrRb(json: String): RequestBody {
        return RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(), json);
    }
*/
    /**
     * 得到 mulitpart 类型的转换RequestBody
     */
    fun getMultiPartFileRb(json: File): RequestBody {
        return RequestBody.create("multipart/form-data".toMediaTypeOrNull(), json);
    }
}