package com.xhly.corelib.network

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 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 需要替换token
         /*   requestBuilder.header("Authorization", "Bearer ${Const.token}")
            requestBuilder.header("Accept-Language", "zh-Hans")*/
            requestBuilder.header("XH-UserId","1")
            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) {
                throw RuntimeException("数据为空")
            } else {
                if (data.code == 401) {
                    //强制退出
                    UIEvent(Const.LOGIN_OUT_401).post()
                }
            }
            originalResponse
        } catch (e: Exception) {
            e.printStackTrace()
            chain.proceed(request)
        }
    }

}