package com.lanyun.common.ext

import android.app.ProgressDialog.show
import android.content.Context
import android.widget.Toast
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.lanyun.common.base.BaseViewModel
import com.lanyun.common.widget.GsonUtils
import com.lanyun.net.base.AppException
import com.lanyun.net.base.ExceptionHandle
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * 一些常用的方法
 */

fun Any?.toJsonStr(): String {
    return GsonUtils.toJson(this)
}

/**
 * toast
 */
fun Any.toast(context: Context) =
    Toast.makeText(context, this.toString(), Toast.LENGTH_SHORT).show()


inline fun <reified T> String.fromJson(): T? {
    return try {
        Gson().fromJson(this, T::class.java)
    } catch (e: Exception) {
        null
    }
}

fun <T> BaseViewModel.requestNoCheck(
    block: suspend () -> T,
    success: (T) -> Unit,
    error: (AppException) -> Unit = {},
    isShowDialog: Boolean = false,
    loadingMessage: String = "请求网络中..."
): Job {
    //如果需要弹窗 通知Activity/fragment弹窗
   // if (isShowDialog) loadingChange.showDialog.postValue(loadingMessage)
    return viewModelScope.launch {
        runCatching {
            //请求体
            block()
        }.onSuccess {
            //网络请求成功 关闭弹窗
            //loadingChange.dismissDialog.postValue(false)
            //成功回调
            success(it)
        }.onFailure {
            //网络请求异常 关闭弹窗
            //loadingChange.dismissDialog.postValue(false)
            //打印错误消息
            it.message?.loge()
            //打印错误栈信息
            it.printStackTrace()
            //失败回调
            error(ExceptionHandle.handleException(it))
        }
    }
}
