package com.yidian.bcommon.http

import android.annotation.SuppressLint
import com.google.gson.JsonParseException
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.app.YdBaseApplication
import com.yidian.bcommon.constant.ResultCode
import com.yidian.utils.ToastUtil
import com.yidian.xpage.XPageManager
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import java.lang.reflect.ParameterizedType

abstract class HttpResultSubscriber<T>(private var showProgress: Boolean = false) : Observer<HttpResult<Any?>> {
  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(YdBaseApplication.context, "当前网络链接不畅，请检查您的网络情况")
      }
    } else if ("connect timed out" == e.message) {
      if (isShowErrorMsg) {
        ToastUtil.showToast(YdBaseApplication.context, "服务器连接超时")
      }
    } else if (e is JsonParseException || e.toString().contains("Json") || e.toString().contains("Gson")) {
      if (isShowErrorMsg) {
        ToastUtil.showToast(YdBaseApplication.context, "数据解析异常")
      }
    } else {
      if (isShowErrorMsg) {
        ToastUtil.showToast(YdBaseApplication.context, "网络请求异常")
      }
    }
    onRequestFailure(Exception(e.toString()))
  }

  override fun onNext(res: HttpResult<Any?>) {
    when (res.code) {
      ResultCode.SUCCESS -> {
        val type = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        val decodeResult = HttpParamsUtils.rsaDecryptResult<T>(res, type)
        onRequestSuccess(decodeResult)
      }
      ResultCode.INVALID -> {
        XPageManager.push(XRouterPathConstants.LOGIN_LIFE_CIRCLE, null)
      }
      else -> {
        val decodeResult = HttpResult<T>()
        decodeResult.code = res.code
        decodeResult.reason = res.reason
        decodeResult.status = res.status
        onFailure(decodeResult)
        ToastUtil.showToast(YdBaseApplication.context, res.reason)
      }
    }
  }

  abstract fun onSuccess(result: HttpResult<T>?)
  abstract fun onFailure(result: HttpResult<T>?)

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

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