package com.zxhl.cms.net.callback;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.zxhl.cms.AppContext;
import com.zxhl.cms.ad.upload.model.Response;
import com.zxhl.cms.common.Constant;
import com.zxhl.cms.net.RxExceptionUtil;
import com.zxhl.cms.router.RounterApi;
import com.zxhl.cms.router.RounterBus;
import com.zxhl.cms.utils.RxBus;
import com.zxhl.cms.utils.Utils;
import com.zxhl.cms.net.SettingPreference;

import java.lang.reflect.Type;

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

/**
 * Created by gaoleichao on 2018/5/5.
 */

public abstract class BaseObserver<T> implements Observer<Response<T>> {

    private Disposable disposable;

    @Override
    public void onNext(@NonNull Response<T> result) {
        if (TextUtils.equals(result.getStatus(), "200")) {
            if (result.getResult() != null) {
                onSuccess(result.getResult().getData());
            } else {
                onSuccess(null);
            }
        } else if (TextUtils.equals(result.getStatus(), "101")) {
            String token = SettingPreference.getUserToken();
            if (!TextUtils.isEmpty(token)) {
                SettingPreference.saveToken("");
                SettingPreference.saveUserInfo(null);
                RxBus.get().post(Constant.REFRESH_LOGIN_STATS,1);
//                Intent intent = Constant.Param.isLocal ? RounterBus.getRounter(RounterApi.class).getIntentActivityLocalLogin() : RounterBus.getRounter(RounterApi.class).getIntentActivityLogin();
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                AppContext.get().startActivity(intent);
                Utils.showToast(AppContext.get(), "登录失效,请重新登录");
            }
        } else if (TextUtils.equals(result.getStatus(), "160")) {
            RxBus.get().post(Constant.UPDATEDEFILE, true);
//            Utils.showToast(Appli.getContext(), "请重试");
            onFailure(null, "160", "请重试");//该异常可以汇报服务端
        }else if(TextUtils.equals(result.getStatus(), "105")){
            onFailure(new Exception(result.getMsg()), result.getStatus(), result.getMsg());//该异常可以汇报服务端
            Utils.showToast(AppContext.get(), result.getMsg());
        } else {
            onFailure(new Exception(result.getMsg()), result.getStatus(), result.getMsg());//该异常可以汇报服务端
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        onFailure(e, "103", RxExceptionUtil.exceptionHandler(e));
    }

    @Override
    public void onComplete() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        disposable = d;
    }

    public abstract void onSuccess(T result);

    public abstract void onFailure(Throwable e, String code, String errorMsg);
}
