package com.dahe.pass.net;

import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            try {
                String result = buffer.clone().readString(StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(result);
                int 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 (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
