package com.xhly.corelib.network

import android.os.Build
import android.util.Log
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.network.bean.ResponseData
import com.xhly.corelib.utils.GsonUtils

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.IOException
import java.net.URLDecoder
import java.net.URLEncoder
import java.nio.charset.Charset

class ResponseInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        return try {
            val requestBuilder: Request.Builder = request.newBuilder()
            //TODO 需要替换userid和机型
            Const.USERID?.let {
                requestBuilder.header("XH-UserId",Const.USERID.toString())
            }
            requestBuilder.header("XH-DeviceModel", Build.MODEL)
            request = requestBuilder.build()
            val originalResponse = chain.proceed(request)
            val responseBody = originalResponse.body
            val source = responseBody!!.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer()
            var charset = Charset.forName("UTF8")
            val contentType = responseBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(charset)
            }
            val bodyString = buffer.clone().readString(charset)
         /*   val data = GsonUtils.parseJsonWithGson(bodyString, ResponseData::class.java)
            if (data != null) {
            //TODO 接口统一退出
                if (data.code == 401) {
                    //强制退出
                    UIEvent(Const.LOGIN_OUT_401).post()
                }
            }*/
            originalResponse
        } catch (e: Exception) {
            e.printStackTrace()
           try {
               chain.proceed(request)
           }catch (e:Exception){
                  return createDefaultResponse()
           }
        }
    }
    fun createDefaultResponse(): Response {
        // 创建默认的响应体内容
        val responseBody = "{\"code\":0,\"msg\":\"\",\"obj\":false}" // 替换为您想要返回的默认响应体内容

        // 创建默认的响应对象
        val response = Response.Builder()
            .code(200) // 替换为您想要的响应码
            .message("{\"code\":0,\"msg\":\"\",\"obj\":false}") // 替换为您想要的响应消息
            .protocol(okhttp3.Protocol.HTTP_1_1) // 替换为您想要的协议
            .request(okhttp3.Request.Builder().url("http://example.com").build()) // 替换为请求对象
            .body(responseBody.toResponseBody()) // 设置响应体
            .build()

        return response
    }
}