package com.abbidot.tracker.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.retrofit2.NetworkApi
import kotlinx.coroutines.launch

/**
 *Created  by .yzq on 2022/3/4/004.
 * @link
 * @description: 宠物绑定，解绑操作
 */
class PetRelationViewModel : ViewModel() {

    val mUnbindPetLiveData = MutableLiveData<Result<String>>()
    val mUnbindPetListLiveData = MutableLiveData<Result<MutableList<PetBean>>>()
    val mBindPetLiveData = MutableLiveData<Result<String>>()
    val mDeletePetLiveData = MutableLiveData<Result<String>>()
    val mAssignOtherPetLiveData = MutableLiveData<Result<String>>()

    fun bindPet(activity: BaseActivity<*>, deviceId: String, petId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val result = NetworkApi.bindPet(userId, deviceId, petId)
            mBindPetLiveData.value = result
        }
    }

    fun unbindPet(activity: BaseActivity<*>, deviceId: String, petId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val result = NetworkApi.unbindPet(userId, deviceId, petId)
            mUnbindPetLiveData.value = result
        }
    }

    fun deletePet(activity: BaseActivity<*>, petId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val result = NetworkApi.deletePet(userId, petId)
            mDeletePetLiveData.value = result
        }
    }

    /**
     * 获取未绑定的设备宠物列表
     */
    fun getUnbindPetList(activity: BaseActivity<*>) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val result = NetworkApi.getUnbindPetList(userId)
            mUnbindPetListLiveData.value = result
        }
    }

    /**
     * 获取未绑定的宠物设备列表
     */
    fun assignOtherPet(
        activity: BaseActivity<*>, deviceId: String, originPetId: String, assignPetId: String
    ) {
        activity.showLoading(true)
        viewModelScope.launch {
            val userId = MMKVUtil.getString(MMKVKey.UserId)
            val result = NetworkApi.assignOtherPet(userId, deviceId, originPetId, assignPetId)
            mAssignOtherPetLiveData.value = result
        }
    }
}