package com.renrenliao.im.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.renrenliao.im.ext.handleException
import com.renrenliao.im.ext.toast
import com.renrenliao.im.utils.LogUtils
import com.renrenliao.im.utils.RingToast
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

abstract class BaseViewModel : ViewModel() {

    val kv = MMKV.defaultMMKV()

    val dialogLoadingState by lazy { MutableLiveData<Boolean>() }



    /**
     * 一般用于 同步 请求  并发多个请求 请单独更具自定义的业务写
     */
    fun launchUI(
        block: suspend CoroutineScope.() -> Unit,
        isShowToast: Boolean = false,
        isShowDiaLoading:Boolean = false,

    ) {
        viewModelScope.launch {
            //各种状态开始

            if (isShowDiaLoading){
                dialogLoadingState.value = true
            }

            runCatching {
                block()
            }.onSuccess {

            }.onFailure {
                val exception = handleException(it)
                LogUtils.error("${exception.errCode}  ${exception.errorMsg}")
                if (isShowToast) {
                   // toast(exception.errorMsg)
                    RingToast.show(exception.errorMsg)
                }
            }
            //各种状态结束
            if (isShowDiaLoading){
                dialogLoadingState.value = false
            }

        }
    }


}