package com.zztrapp.zztrapp.http;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;

import com.zztrapp.zztrapp.constant.Constant;
import com.zztrapp.zztrapp.ui.mine.activity.LoginActivity;
import com.zztrapp.zztrapp.utilcode.klogs.KLog;
import com.zztrapp.zztrapp.utilcode.util.NetworkUtils;
import com.zztrapp.zztrapp.utilcode.util.SPUtils;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Subscriber;

/**
 * Describe
 * 用于在Http请求开始时，自动显示一个ProgressDialog
 * 在Http请求结束时，关闭ProgressDialog
 * 调用者自己对请求数据进行处理
 * Created by Bby on 2021/10/2
 * Email bby0856@163.com
 */

public class ProgressSubscriber<T> extends Subscriber<T> implements IProgressCancelListener {

    private ISubscriberOnNextListener mSubscriberOnNextListener;
    private ProgressDialogHandler mProgressDialogHandler;

    private Context context;
    private final Activity mActivity;
    private Dialog dialog;

    public ProgressSubscriber(ISubscriberOnNextListener mSubscriberOnNextListener, Context context, Boolean isShowDialog) {
        this.mSubscriberOnNextListener = mSubscriberOnNextListener;
        this.context = context.getApplicationContext();
        mActivity = (Activity) context;
        if (isShowDialog) {
            mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
        } else {
            mProgressDialogHandler = null;
        }
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        showProgressDialog();
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {

        if (e instanceof SocketTimeoutException) {//网络超时
            if (mSubscriberOnNextListener != null) {
                KLog.e("网络超时");

//                Toast.makeText(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
//                mSubscriberOnNextListener.onError(Constant.ERROR_TIMEOUT, "网络不给力");
                mSubscriberOnNextListener.onError(Constant.ERROR, "请求超时");
            }
        } else if (e instanceof ConnectException) {//连接失败
            if (mSubscriberOnNextListener != null) {
                KLog.e("连接失败");

//                mSubscriberOnNextListener.onError(Constant.ERROR,"网络中断，请检查您的网络状态");
//                mSubscriberOnNextListener.onError(Constant.ERROR, "网络不给力");
                mSubscriberOnNextListener.onError(Constant.ERROR, "连接不到服务器");
            }
        } else if (e instanceof ApiException) {
            if (mSubscriberOnNextListener != null) {
                if (((ApiException) e).getStatusCode() == 101) {//登录过期
                    SPUtils.getInstance().clear();
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("登录过期，请重新登录");
                    Intent intent = new Intent(context, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    if (mActivity != null) {
                        mActivity.finish();
                    }

                } else
                    mSubscriberOnNextListener.onError(((ApiException) e).getStatusCode(), ((ApiException) e).getMessage());
            }
        } else {//请求异常
            if (mSubscriberOnNextListener != null) {
                KLog.e("请求异常" + e);
                if (!NetworkUtils.isConnected()) {
                    mSubscriberOnNextListener.onError(Constant.ERROR, "网络不给力");
                } else {
                    if (e.toString().contains("401")) {
                        //登录过期
                        SPUtils.getInstance().clear();
                        ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("登录过期，请重新登录");
                        Intent intent = new Intent(context, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                        if (mActivity != null) {
                            mActivity.finish();
                        }
                    } else {
                        mSubscriberOnNextListener.onError(Constant.ERROR_OTHER, e.toString());
                    }

                }
            }
        }
        dismissProgressDialog();

    }

    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param t 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T t) {
        if (mSubscriberOnNextListener != null) {
            mSubscriberOnNextListener.onNext(t);
        }
    }

    /**
     * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
     */
    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }

}