package com.casic.detector.vm

import androidx.lifecycle.MutableLiveData
import com.casic.detector.base.BaseApplication
import com.casic.detector.extensions.getResponseMessage
import com.casic.detector.extensions.getResponseState
import com.casic.detector.model.LoginResultModel
import com.casic.detector.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(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(BaseApplication.get())
        }
    }, {
        loadState.value = LoadState.Fail
        if (BaseApplication.get().isNetworkConnected()) {
            "连接服务器失败，IP或端口错误".show(BaseApplication.get())
        } else {
            "网络连接失败".show(BaseApplication.get())
        }
    })
}