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.base.BaseFragment
import com.abbidot.tracker.bean.FamilyBean
import com.abbidot.tracker.bean.FamilyPetBean
import com.abbidot.tracker.bean.InviteInfoBean
import com.abbidot.tracker.retrofit2.NetworkApi
import kotlinx.coroutines.launch

/**
 *Created  by .yzq on 2022/3/11/011.
 * @link
 * @description:
 */
class FamilyViewModel : ViewModel() {

    val mInviteLiveData = MutableLiveData<Result<String>>()
    val mFamilyListLiveData = MutableLiveData<Result<FamilyPetBean>>()
    val mFamilyRemoveLiveData = MutableLiveData<Result<String>>()
    val mInviteInfoLiveData = MutableLiveData<Result<InviteInfoBean>>()

    fun invite(activity: BaseActivity<*>, familyBean: FamilyBean) {
        activity.showLoading(true)
        viewModelScope.launch {
            familyBean.apply {
                val result = NetworkApi.invite(
                    userId,
                    userName,
                    sendEmail,
                    deviceId,
                    acceptEmail,
                    relation,
                    avatar,
                    petId,
                    petName
                )
                mInviteLiveData.value = result
            }
        }
    }

    fun inviteCN(
        fragment: BaseFragment<*>, userId: String, userName: String, deviceId: String, phone: String
    ) {
        fragment.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.inviteCN(userId, userName, deviceId, phone)
            mInviteLiveData.value = result
        }
    }


    fun getFamilies(activity: BaseActivity<*>, deviceId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.getFamilies(deviceId)
            mFamilyListLiveData.value = result
        }
    }

    fun removeFamily(activity: BaseActivity<*>, familyId: String) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.removeFamily(familyId)
            mFamilyRemoveLiveData.value = result
        }
    }

    /**
     * 获取设备邀请信息
     */
    fun getDeviceInviteInfo(activity: BaseActivity<*>) {
        activity.showLoading(true)
        viewModelScope.launch {
            val email = MMKVUtil.getString(MMKVKey.Email)
            val result = NetworkApi.getDeviceInviteInfo(email)
            mInviteInfoLiveData.value = result
        }
    }
}