package com.sxyz.rfid.retrofit.callback;


import android.content.Intent;

import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.Gson;
import com.sxyz.rfid.App;
import com.sxyz.rfid.R;
import com.sxyz.rfid.ui.login.LoginActivity;
import com.sxyz.rfid.utils.L;
import com.sxyz.rfid.utils.LocalUtils;
import com.sxyz.rfid.utils.ToastUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @Description: 抽象的回调接口
 * @Author: wuchunyuan
 * @CreateDate: 2020/7/8 13:42
 * @UpdateUser: wuchunyuan
 * @UpdateDate: 2020/7/8 13:42
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public abstract class Object2Observer<T extends Response1Base> implements Observer<T> {

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(T response) {
        String code = response.code;
        String mMsg = response.msg;
        switch (code) {
            case "200"://获取成功
                onSuccess(response);
                L.e("接口返回json================================================>\n" + new Gson().toJson(response.body));
//                    L.i("返回的json===>" + new Gson().toJson(response.body));
                break;
            case "401"://重新登录
                try {
                    LocalUtils.clearSp();
                    Intent intent = new Intent(App.getContext(), LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    App.getContext().startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                onFailed(null);
                ToastUtil.showShort(mMsg);
                break;

        }
    }

    @Override
    public void onError(Throwable throwable) {
        L.e("-->\n请求错误信息-->" + throwable.getMessage());
        onFailed(throwable);
        if (NetworkUtils.isConnected()) {
            NetErrorHandler.getErrorMessage(throwable);
        } else {
            ToastUtil.showShort(App.getContext().getResources().getString(R.string.tips_network_errors));
        }
    }

    @Override
    public void onComplete() {
    }

    /**
     * @description Token 失效回调
     * @author wuchunyuan
     * @time 2024/11/22 11:07
     */
//    public abstract void onTokenError(T response);

    /**
     * @description 成功回调
     * @author wuchunyuan
     * @time 2020/7/9 11:07
     */
    public abstract void onSuccess(T response);

    /**
     * @description 失败回调
     * @author wuchunyuan
     * @time 2020/7/9 11:07
     */
    public abstract void onFailed(Throwable throwable);

}
