package com.yidian.common.http

import android.annotation.SuppressLint
import com.google.gson.JsonParseException
import com.yidian.common.YacBaseApplication
import com.yidian.utils.ToastUtil
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable

abstract class HttpResultSubscriber<T>(private var showProgress: Boolean = false) : Observer<HttpResult<T>?> {
    private var isShowErrorMsg = true

    override fun onSubscribe(d: Disposable) { //网络请求之前
        if(showProgress){

        }
    }

    override fun onComplete() { //网络请求完成
        if(showProgress){

        }
    }

    override fun onError(e: Throwable) {
        if (e.toString().contains("ConnectException") || e.toString().contains("Unable to resolve host")) {
            if (isShowErrorMsg) {
                ToastUtil.showToast(YacBaseApplication.context, "当前网络链接不畅，请检查您的网络情况")
            }
        } else if ("connect timed out" == e.message) {
            if (isShowErrorMsg) {
                ToastUtil.showToast(YacBaseApplication.context, "服务器连接超时")
            }
        } else if (e is JsonParseException || e.toString().contains("Json") || e.toString().contains("Gson")) {
            if (isShowErrorMsg) {
                ToastUtil.showToast(YacBaseApplication.context, "数据解析异常")
            }
        } else {
            if (isShowErrorMsg) {
                ToastUtil.showToast(YacBaseApplication.context, "网络请求异常")
            }
        }
        onRequestFailure(Exception(e.toString()))
    }

    override fun onNext(result: HttpResult<T>?) {
        if (result?.code == 0) {
            onRequestSuccess(result)
        }else{
            onFailer(result)
            ToastUtil.showToast(YacBaseApplication.context, result?.reason)
        }
    }

    abstract fun onSuccess(result: HttpResult<T>?)
    abstract fun onFailer(result: HttpResult<T>?)
    @SuppressLint("NewApi")
    fun onRequestFailure(e: Throwable?) {
        val result: HttpResult<T> = HttpResult()
        result.code = -100
        result.reason = e?.message
        result.status = "failed"
        onFailer(result)
    }

    @SuppressLint("NewApi")
    fun onRequestSuccess(result: HttpResult<T>) {
        onSuccess(result)
    }
}