package com.cheng.blzb.ui.fragment.login.onekey

import androidx.lifecycle.MutableLiveData
import com.example.base.extensions.toast
import com.example.base.utils.L
import com.example.base.viewmodel.BaseViewModel
import com.google.gson.JsonObject
import com.cheng.blzb.net.ApiFactory
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

class OnekeyLoginViewModel : BaseViewModel() {
    val accountLiveData = MutableLiveData<List<com.cheng.blzb.bean.AccountEntity>>()
    val onekeyLoginLiveData = MutableLiveData<com.cheng.blzb.bean.LoginEntity>()
    val wxLoginLiveData = MutableLiveData<com.cheng.blzb.bean.LoginEntity>()

    fun accountList() {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.accountList("login")
            if (response.status) {
                accountLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun oneKeyLogin(gyuid: String, token: String) {
        showDialog()
        launchOnUiTryCatch({
            val jsonOneKey = JsonObject()
            jsonOneKey.addProperty("gyuid", gyuid)
            jsonOneKey.addProperty("token", token)
            val jsonObject = JsonObject()
            jsonObject.addProperty("login_type", "onekey")
            jsonObject.add("onekey", jsonOneKey)
            jsonObject.addProperty("bind", false)
            val response = ApiFactory.apiService.login(jsonObject.toString().toRequestBody())
            if (response.status) {
                onekeyLoginLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun loginByWx(requestBody: RequestBody) {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.login(requestBody)
            if (response.status) {
                wxLoginLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }
}