package com.img.rabbit.viewmodel

import android.annotation.SuppressLint
import androidx.compose.runtime.mutableStateOf
import com.google.gson.JsonObject
import com.img.rabbit.bean.local.ErrorBean
import com.img.rabbit.bean.response.LoginInfoEntity
import com.img.rabbit.bean.response.UserInfoEntity
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.provider.api.ResultVo
import okhttp3.RequestBody.Companion.toRequestBody

class AccountManagerViewModel : BaseViewModel() {
    // 获取账号状态
    @SuppressLint("MutableCollectionMutableState")
    val accountState = mutableStateOf<MutableList<UserInfoEntity>?>(null)
    @SuppressLint("MutableCollectionMutableState")
    val switchState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
    // 错误状态
    val errorState = mutableStateOf<ErrorBean?>(null)

    fun requestAccount() {
        isLoading.value = true // 开始加载
        mLaunch {
            val response = ApiManager.serviceVo.account()
            if (response.status) {
                //  处理获取账号列表
                accountState.value = response.data
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "获取账号失败..." })
            }
            isLoading.value = false // 开始加载
        }
    }

    fun switchAccount(userId: String) {
        isLoading.value = true // 开始加载

        // 调用 API 获取数据
        val jsonSwitch = JsonObject()
        jsonSwitch.addProperty("user_id", userId)

        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "device")
        jsonObject.add("data", jsonSwitch)

        mLaunch {
            val response = ApiManager.serviceVo.login(jsonObject.toString().toRequestBody())
            if (response.status) {
                //  处理切换账号
                switchState.value = response
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "切换账号失败..." })
            }
            isLoading.value = false // 开始加载
        }
    }
}