package com.dahe.gldriver.net

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import kotlin.Throws
import org.json.JSONObject
import java.io.IOException
import java.lang.Exception
import java.nio.charset.StandardCharsets

class TokenInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val response: Response = chain.proceed(request)
        val responseBody = response.body
        if (responseBody != null) {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE) // Buffer the entire body.
            val buffer = source.buffer()
            try {
                val result = buffer.clone().readString(StandardCharsets.UTF_8)
                val jsonObject = JSONObject(result)
                val code = jsonObject.getInt("code")
                if (code == -1) { //判断返回code

//                    SPUtils.cleanUserInfo(App.getApp());
//                    Intent intent = new Intent(App.getApp(), LoginActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                    App.getApp().startActivity(intent);
//                    ToastUtils.showToast(App.getApp(), "您的账号再异地登录，请重新登录");
//                    ToastUtils.showShort("身份过期，请重新登录");
                    //跳转方式
                    //1.使用MyApplication添加跳转
                    //2.使用路由跳转
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return response
    }
}