package com.ypsx.yppos.http

import com.elvishew.xlog.XLog
import com.ypsx.yppos.http.data.request.RefreshTokenRequest
import com.ypsx.yppos.utils.CacheUtil
import com.ypsx.yppos.utils.InterceptorUtils
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import org.json.JSONObject

class RetryInterceptor: Interceptor {

    private val NOT_LOGIN_CODE = 20
    private val TOKEN_AUTHENTICATION_FAILED = 19
    private val CODE = "code"
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)

        try {
            val body = response.body()
            val jsonObject = JSONObject(InterceptorUtils.getRspData(body))
            val code: Int = jsonObject.getInt(CODE)
            //Token失效重新登录(过滤掉注销会员的接口，退出登录时不必判断接口是否成功，默认进入登录页面，避免此处重复进入)
            if (code == NOT_LOGIN_CODE
                || code == TOKEN_AUTHENTICATION_FAILED
            ) {
                var loginResponse = CacheUtil.getLoginResponse()
                var refreshToken =
                    apiService.refreshToken(RefreshTokenRequest(loginResponse!!.accessToken))
                loginResponse.accessToken = refreshToken.data.refreshToken
                CacheUtil.setLoginResponse(loginResponse)
                val newRequest: Request = request.newBuilder().header("access-token", loginResponse.accessToken)
                    .build()
                return chain.proceed(newRequest);
            }
        } catch (e: Exception) {
            val requestUrl = if (request.url() == null) "空" else request.url().toString()
            XLog.i("接口 = " + requestUrl + " 发生异常：" + e.message)
        }
        return response
    }
}