package com.img.rabbit.viewmodel

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.provider.api.ApiManager
import com.img.rabbit.provider.api.ResultVo
import com.img.rabbit.provider.storage.PreferenceUtil
import okhttp3.RequestBody.Companion.toRequestBody

class AccountBindViewModel : BaseViewModel() {
    // 解绑状态
    val unBindState = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
    // 错误状态
    val errorState = mutableStateOf<ErrorBean?>(null)

    /**
     * 请求登录(验证码)
     */
    fun requestUnBindByPhone(phone: String) {
        isLoading.value = true // 开始加载

        // 调用 API 获取数据
        val jsonPhone = JsonObject()
        jsonPhone.addProperty("phone", phone)

        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "phone")
        jsonObject.addProperty("bind", "2")
        jsonObject.add("data", jsonPhone)

        unBindAccount(jsonObject)
    }

    /**
     * 拿着微信授权码完成登录(在WXEntryActivity中调用)
     * @param wechatCode 微信授权码
     */
    fun requestUnBindByWechat(wechatCode: String) {
        if(wechatCode.isEmpty()){
            return
        }
        isLoading.value = true // 开始加载
        PreferenceUtil.saveWxCode(wechatCode)

        // 调用 API 获取数据
        val jsonWx = JsonObject()
        jsonWx.addProperty("code", wechatCode)
        jsonWx.addProperty("code_type", "")

        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "weixin")
        jsonObject.addProperty("bind", "2")
        jsonObject.add("data", jsonWx)

        unBindAccount(jsonObject)
    }

    fun unBindAccount(jsonObject: JsonObject){
        mLaunch {
            val response = ApiManager.serviceVo.login(jsonObject.toString().toRequestBody())
            if (response.status) {
                unBindState.value = response
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "解绑失败" })
            }
            isLoading.value = false // 加载完成
        }
    }
}