package com.ym.modulecommon.net;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.ym.modulecommon.AppliContext;
import com.ym.modulecommon.utils.LogUtils;
import com.ym.modulecommon.utils.AdPreference;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

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

    private Disposable disposable;

    @Override
    public void onNext(@NonNull Response<T> result) {
        if (TextUtils.equals(result.status, "200")) {
            if (result.result != null) {
                onSuccess(result.result.data);
            } else {
                onSuccess(null);
            }
        } else if (TextUtils.equals(result.status, "101")) {
        } else if (TextUtils.equals(result.status, "160")) {
            onFailure(null, "160", "请重试");//该异常可以汇报服务端
        } else {
            onFailure(new Exception(result.msg), result.status, result.msg);//该异常可以汇报服务端
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
//        if(e.getMessage().contains("403")){//
////            NetConfig.setBase_Url(NetConfig.Environment.DEV);
//            AdPreference.saveEvnvironment(NetConfig.Environment.DEV.toString());
//            NetConfig.setBase_Url(NetConfig.Environment.DEV);
//            restartApp();
//        }
        LogUtils.e("huang",e.fillInStackTrace()+"   "+e.getLocalizedMessage()+"  "+e.getMessage()+"    "+e.getSuppressed());
        onFailure(e, "250", e.getMessage());//该异常可以汇报服务端
    }
    // 重启应用
    private void restartApp() {
        Intent intent = new Intent();
// 参数1：包名，参数2：程序入口的activity
        intent.setClassName(AppliContext.get().getPackageName(), "com.ym.msdh.SplashActivity");
        @SuppressLint("WrongConstant") PendingIntent restartIntent = PendingIntent.getActivity(
                AppliContext.get(), 0, intent,
                Intent.FLAG_ACTIVITY_NEW_TASK);
        AlarmManager mgr = (AlarmManager) AppliContext.get().getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                restartIntent); // 1秒钟后重启应用
//        finishProgram(); // 自定义方法，关闭当前打开的所有avtivity
    }


    @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);
}
