package com.ypsx.yppos.viewmodel.request

import androidx.lifecycle.MutableLiveData
import com.ypsx.base.base.viewmodel.BaseViewModel
import com.ypsx.base.ext.request
import com.ypsx.base.ext.requestNoCheck
import com.ypsx.base.ext.util.loge
import com.ypsx.yppos.utils.toast
import com.ypsx.yppos.http.apiService
import com.ypsx.yppos.http.data.bean.AppVersionResponse
import com.ypsx.yppos.http.data.bean.LoginResponse
import com.ypsx.yppos.http.data.request.KickoffRequest
import com.ypsx.yppos.http.repository.request.HttpRequestCoroutine
import com.ypsx.yppos.http.state.UpdateUiState
import com.ypsx.yppos.room.repository.PosConfigRepository
import com.ypsx.yppos.utils.dXLog

class RequestLoginViewModel : BaseViewModel() {
    var posDetails = MutableLiveData<UpdateUiState<LoginResponse>>()
    var posDetails2 = MutableLiveData<UpdateUiState<Int>>()
    var appVersion = MutableLiveData<AppVersionResponse>()

    private val posConfig = PosConfigRepository.getInstance().loadConfig()


    fun login(username: String, password: String) {
        val storeId = posConfig?.storeId!!
        val posId = posConfig.id
        request({ HttpRequestCoroutine.posLogin(posId, storeId, username, password) }, {
            val uiState = UpdateUiState(isSuccess = true, data = it)
            posDetails.postValue(uiState)

        }, {

            if (it.errCode == 10025) {
                val uiState = UpdateUiState(isSuccess = false, 0, errorMsg = it.errorMsg)
                posDetails2.postValue(uiState)
            } else {
                it.errorMsg.loge()
//                it.errorMsg.toast()
                val uiState = UpdateUiState(isSuccess = true, 0, errorMsg = it.errorMsg)
                posDetails2.postValue(uiState)
            }

        })
    }

    fun posKickOff(username: String) {
        val kickoffRequest = KickoffRequest(username)
        requestNoCheck({ apiService.posKickOff(kickoffRequest) }, {
            val uiState = UpdateUiState(isSuccess = true, 0, errorMsg = it.message)
            posDetails2.postValue(uiState)
        }, {
            val uiState = UpdateUiState(isSuccess = true, 0, errorMsg = it.errorMsg)
            posDetails2.postValue(uiState)
        })
//        val posId = posConfig.id
    }

    fun upgradeApk(posID: String) {
        request({ apiService.getLastAppVersion(posID) }, {
            if (it != null) {
                appVersion.postValue(it)
            }
        }, {
            it.errorMsg.dXLog()

        })
    }

}