package com.xty.base.vm

import android.app.Dialog
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hjq.toast.ToastUtils
import com.xty.common.LogUtils
import com.xty.common.util.CommonUtils
import com.xty.network.ApiInterface
import com.xty.network.MyRetrofit
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import org.json.JSONObject
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLHandshakeException

open class BaseVm(var loading: Dialog?) : ViewModel() {

    constructor() : this(null)

    val nowData: MutableLiveData<String> by lazy { MutableLiveData<String>() }   //登陆失效处理
    val retrofits by lazy { MyRetrofit.get() }

    fun apiInterface() = retrofits.create(ApiInterface::class.java)


    private val handlerExcept by lazy {
        CoroutineExceptionHandler { _, throwable ->
            LogUtils.e("startHttp", "异常捕获")
            try {
                if (loading != null) {
                    loading!!.dismiss()
                }
                when (throwable) {

                    is ConnectException -> ToastUtils.show("网络异常")
                    is HttpException -> {
                        var exception = throwable
                        when ((exception as HttpException).code()) {
                            500 -> ToastUtils.show("服务器繁忙，请稍后重试")
                            502 -> ToastUtils.show("当前网络状态不佳，请稍后重试")
                            504 -> ToastUtils.show("请求超时，请检查网络")
                            else -> ToastUtils.show("连接异常错误码:${(exception as HttpException).code()}")
                        }
                        return@CoroutineExceptionHandler
                    }
                    is SocketTimeoutException -> {
                        ToastUtils.show("连接超时")
                        return@CoroutineExceptionHandler
                    }
                    is UnknownHostException -> {
                        ToastUtils.show("当前网络状态不佳，请再试一次")
                        return@CoroutineExceptionHandler
                    }
                }
                // nowData.postValue()
                LogUtils.e("http", "异常错误类型$throwable")
//                uploadRequestErrorLog("请求错误：$throwable")
                //ToastUtils.show(throwable.message)
            } catch (e: Exception) {
                LogUtils.e("http", "请求错误$e")
//                uploadRequestErrorLog("请求错误：$e")
            }
        }
    }

    //静默上传测试日志,注意控制避免内存溢出
    fun uploadRequestErrorLog(str: String) {
        startHttp(false) {
            var json = JSONObject()
            // json.put("pageNum",page)
            //json.put("pageSize",Const.PAGE_SIZE)
            json.put("userId", CommonUtils.getMyUserId())
            json.put("content", str)
            apiInterface().saveLog(retrofits.getRequestBody(json.toString()))
        }
    }

    fun startHttp(isShowLoading: Boolean = true, http: suspend () -> Unit) {
        viewModelScope.launch(handlerExcept) {
            supervisorScope {
                launch(handlerExcept) {
                    if (loading != null && isShowLoading) {
                        loading!!.show()
                    }
                    http.invoke()
                    if (loading != null && loading!!.isShowing && isShowLoading) {
                        loading!!.dismiss()
                    }
                }
            }
        }
    }
}