package com.lukouguoji.module_base.http.user

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
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 com.lukouguoji.module_base.impl.HttpLogImpl
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.util.ServiceCommon
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit


object ServiceCreator {

    var ipAddress = SharedPreferenceUtil.getString(Constant.Share.ipAddress).noNull(
        MyApplication.context.getString(R.string.system_url_inner)
    )

    var retrofit: Retrofit = createRetrofit()

    fun createRetrofit(): Retrofit {
        println("ipAddress:"+ipAddress.toString())
        return Retrofit.Builder()
            .baseUrl(ipAddress)
            .client(httpClientBuilder(SelfLoginInterceptor).build())
            .addConverterFactory(FastJsonConverterFactory())
            .build()
    }

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

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

    //给OKHttpClient添加拦截器
    fun httpClientBuilder(custom: Interceptor): OkHttpClient.Builder {
        // 初始化日志拦截器
        val logInterceptor = HttpLoggingInterceptor(HttpLogImpl())
        // 设置日志拦截器的日志级别
        logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(custom)
            .addInterceptor(logInterceptor)
        builder.connectTimeout(30, TimeUnit.SECONDS)
        builder.readTimeout(30, TimeUnit.SECONDS)
        builder.writeTimeout(30, TimeUnit.SECONDS)
        return builder
    }

}

object WeightDataServiceCreator {

    fun getIpAddress(): String {
        return MyApplication.context.getString(R.string.weight_url)
    }

    var retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(getIpAddress())
        .client(OkHttpClient.Builder().build())
        .addConverterFactory(GsonConverterFactory.create())
        .addConverterFactory(StringConverterFactory.create())
        .build()

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

    inline fun <reified T> create(): T {

        return create(T::class.java)
    }

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

        var authorised: Request
        if (!originalRequest.url.toString().contains("/api/login?")) {
            authorised = originalRequest.newBuilder()
                .addHeader("Authorization", token)
                .addHeader("timestamp", System.currentTimeMillis().toString() + "")
                .build()
        } else {
            authorised = originalRequest.newBuilder().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: JSONObject
                    try {
                        parseObject = JSON.parseObject(respBody)
                    } catch (e: Exception) {
                        try {
                            val tempObj = JSONObject()
                            tempObj["data"] = JSON.parseArray(respBody)
//                        Log.w("respBody",e.stackTraceToString())
                            var contentType = response.body!!.contentType()
                            return response.newBuilder()
                                .body(ResponseBody.create(contentType, tempObj.toJSONString()))
                                .build()
                        } catch (e: Exception) {
                            return response
                        }
                    }
                    when (parseObject.getInteger("status")) {
                        401 -> {
                            ServiceCommon.exitLogin()
                            sendHandler(1, "用户信息已过期，请重新登陆！")
                        }

                        500 -> {
                            sendHandler(1, parseObject.getString("message"))
                        }

                        5001 -> {
                            ServiceCommon.exitLogin()
                            sendHandler(1, "用户信息已过期，请重新登陆！")
                        }
                    }
                }
            }

            401 -> {
                ServiceCommon.exitLogin()
                sendHandler(1, "用户信息已过期，请重新登陆！")
            }

            500 -> {
//                sendHandler(1, "网络出错,请稍后再试！")
                val tempObj = JSONObject()
                tempObj["data"] = JSONObject().put("status", Constant.Result.fail)
                var contentType = response.body!!.contentType()
                return response.newBuilder()
                    .body(ResponseBody.create(contentType, tempObj.toJSONString())).build()
            }

            else -> {
//                sendHandler(1, "地址错误！")
                val dataObj = JSONObject()
                dataObj["status"] = Constant.Result.fail
                val tempObj = JSONObject()
                tempObj["data"] = dataObj
                var contentType = response.body!!.contentType()

//                return response
//                    .newBuilder()
//                    .message(tempObj.toJSONString())
//                    .body(ResponseBody.create(contentType, tempObj.toJSONString().toByteArray()))
//                    .build()
                return Response.Builder().code(200)
                    .message(tempObj.toJSONString())
                    .request(chain.request())
                    .protocol(Protocol.HTTP_1_0)
                    .body(ResponseBody.create(contentType, tempObj.toJSONString().toByteArray()))
                    .build()
            }
        }
        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()
            }
        }
    }

    private fun sendHandler(what: Int, obj: String) {
        val msg = Message()
        msg.what = what
        msg.obj = obj
        handler.sendMessage(msg)
    }
}