package com.lukouguoji.module_base.http.system

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.lukouguoji.module_base.MyApplication
import com.lukouguoji.module_base.R
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import retrofit2.Retrofit
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit


object SystemServiceCreator {

    fun getIpAddress() = MyApplication.context.getString(R.string.auto_url)

    var retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(getIpAddress())
        .client(httpClientBuilder(SelfLoginInterceptor).build())
        .addConverterFactory(SystemFastJsonConverterFactory())
        .build()

    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    inline fun <reified T> create(): T {
        if (getIpAddress() == "") {
            MyApplication.startLogin()
        }
        return create(T::class.java)
    }

    //给OKHttpClient添加拦截器
    fun httpClientBuilder(custom: Interceptor): OkHttpClient.Builder {
        //HttpLoggingInterceptor,okhttp3自带的拦截器，用于输出log，比如请求流和响应流
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(custom)
        builder.connectTimeout(5, TimeUnit.SECONDS)
        builder.readTimeout(5, TimeUnit.SECONDS)
        builder.writeTimeout(5, TimeUnit.SECONDS)
        return builder
    }

}

/**
 * 拦截器
 */
object SelfLoginInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()
        var token = SharedPreferenceUtil.getString(Constant.Share.token)
        val authorised: Request = originalRequest.newBuilder()
            .addHeader("Authorization", token)
            .addHeader("timestamp", System.currentTimeMillis().toString() + "")
            .build()

        //响应拦截
        var response = chain.proceed(authorised)
        when (response.code) {
            200 -> {
                val responseBody = response.body
                var respBody: String? = null
                if (responseBody != null) {
                    val source = responseBody.source()
                    source.request(Long.MAX_VALUE)
                    val buffer = source.buffer()
                    var charset: Charset = Charset.forName("utf-8")
                    val contentType = responseBody.contentType()
                    if (contentType != null) {
                        try {
                            charset = contentType.charset(charset)!!
                        } catch (e: UnsupportedCharsetException) {
                            e.printStackTrace()
                        }
                    }
                    respBody = buffer.clone().readString(charset)
                }
                //如果返回参数是500，登陆失败，清空 token和 password
                if (respBody != null && respBody != "") {
                    var parseObject = JSON.parseObject(respBody)
                    when (parseObject.getInteger("status")) {
                        401 -> {
                            SharedPreferenceUtil.remove(Constant.Share.userName)
                            SharedPreferenceUtil.remove(Constant.Share.authList)
                            SharedPreferenceUtil.remove(Constant.Share.token)
                            var msg = Message()
                            msg.what = 1
                            msg.obj = parseObject.getString("message")
                            handler.sendMessage(msg)
                            MyApplication.startLogin()
                        }
                        500 -> {
                            var msg = Message()
                            msg.what = 1
                            msg.obj = parseObject.getString("message")
                            handler.sendMessage(msg)
                        }
                    }
                }
            }
            401 -> {
                SharedPreferenceUtil.remove(Constant.Share.userName)
                SharedPreferenceUtil.remove(Constant.Share.authList)
                SharedPreferenceUtil.remove(Constant.Share.token)
                MyApplication.startLogin()
            }
            else -> {
                var msg = Message()
                msg.what = 1
                msg.obj = "地址错误！"
                handler.sendMessage(msg)
            }
        }
        return response
    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            // 在这里可以进行UI操作
            when (msg.what) {
                1 -> Toast.makeText(MyApplication.context, msg.obj.toString(), Toast.LENGTH_LONG).show()
            }
        }
    }
}