package com.casic.common.detector.gd.vm

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.casic.common.detector.gd.extensions.getResponseMessage
import com.casic.common.detector.gd.extensions.getResponseState
import com.casic.common.detector.gd.model.LoginResultModel
import com.casic.common.detector.gd.retrofit.RetrofitServiceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.base.BaseViewModel
import com.pengxh.kt.lite.extensions.isNetworkConnected
import com.pengxh.kt.lite.extensions.launch
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.LoadState

/**
 * 用户相关 VM
 * */
class UserViewModel : BaseViewModel() {
    private val gson by lazy { Gson() }
    val loginResult = MutableLiveData<LoginResultModel>()

    fun login(context: Context, account: String, password: String) = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.login(account, password)
        if (response.getResponseState()) {
            loadState.value = LoadState.Success
            loginResult.value = gson.fromJson<LoginResultModel>(
                response, object : TypeToken<LoginResultModel>() {}.type
            )
        } else {
            loadState.value = LoadState.Fail
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
        loadState.value = LoadState.Fail
        if (context.isNetworkConnected()) {
            "连接服务器失败，IP或端口错误".show(context)
        } else {
            "网络连接失败".show(context)
        }
    })
}