package com.rdiot.yx485.device

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.base.BaseViewModel
import com.rdiot.yx485.bean.ConsumableBean
import com.rdiot.yx485.http.Url
import com.rdiot.yx485.http.entity.BaseReplyBean
import com.rdiot.yx485.util.LocalCache
import com.zcolin.frame.http.ZHttp
import com.zcolin.frame.http.response.ZResponse
import okhttp3.Response

class ConsumableViewModel : BaseViewModel() {
    private val _consumable = MutableLiveData<ConsumableBean.DataBean>()
    val consumable: LiveData<ConsumableBean.DataBean> = _consumable

    private val _operationResult = MutableLiveData<Boolean>()
    val operationResult: LiveData<Boolean> = _operationResult

    /**
     * 获取耗材列表
     */
    fun loadConsumableList(homeId: String?) {
        val map = HashMap<String, String>()
        map["home_id"] = homeId ?: LocalCache.getDefaultHomeId()
        LogUtils.d(map.toString())

        ZHttp.getWithHeader<ConsumableBean>(
            Url.CONSUMABLE_LIST,
            getHeaders(),
            map,
            object : ZResponse<ConsumableBean>() {
                override fun onSuccess(response: Response?, resObj: ConsumableBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            _consumable.value = it.data
                            return
                        }
                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    /**
     * 重置耗材
     */
    fun resetConsumable(recordId: String) {
        ZHttp.putWithHeader<BaseReplyBean>(
            Url.CONSUMABLE_REPLACE + "/" + recordId,
            getHeaders(),
            object : ZResponse<BaseReplyBean>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            _operationResult.value = true
                            return
                        }
                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }
} 