package com.ypsx.yppos.viewmodel.request

import androidx.lifecycle.MutableLiveData
import com.ypsx.base.base.viewmodel.BaseViewModel
import com.ypsx.base.ext.launch
import com.ypsx.base.ext.request
import com.ypsx.base.util.LogUtils
import com.ypsx.yppos.utils.toast
import com.ypsx.yppos.http.data.bean.PosMachineResponse
import com.ypsx.yppos.http.data.request.ApplyPosMachineRequest
import com.ypsx.yppos.http.repository.request.HttpRequestCoroutine
import com.ypsx.yppos.room.repository.PosConfigRepository
import com.ypsx.base.util.eXLog
import com.ypsx.yppos.http.state.UpdateUiState
import kotlinx.coroutines.Job

class RequestRegisterViewModel : BaseViewModel() {
    var posDetails = MutableLiveData<PosMachineResponse>()
    var posState = MutableLiveData<UpdateUiState<String>>()
    private var job1: Job? = null
    private var job2: Job? = null


    fun applyPos(applyPosMachineRequest: ApplyPosMachineRequest) {
        job1 = request({ HttpRequestCoroutine.applyPos(applyPosMachineRequest) }, {
            posDetails.postValue(it)
        }, {
            val errorMsg = it.errorMsg
            posState.postValue(UpdateUiState(false, "", errorMsg))

        }, isShowDialog = true)
    }


    fun getById(id: String) {
        job2 = request({ HttpRequestCoroutine.getById(id) }, {
            posDetails.postValue(it)
        }, {
            it.errorMsg.eXLog()
            posState.postValue(UpdateUiState(false, "", it.errorMsg))
        }, isShowDialog = true)
    }

    fun savePosConfig(posMachineResponse: PosMachineResponse) {
        launch({ PosConfigRepository.getInstance().savePosDetail(posMachineResponse) }, {
            LogUtils.debugInfo("保存数据库PosConfig成功")
        }, {
            LogUtils.debugInfo("保存数据库PosConfig失败")
        })
    }

    fun cancelJob() {
        job1!!.cancel()
        job2!!.cancel()
    }
}