package com.ccwangluo.accelerator.ui.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccwangluo.accelerator.model.LoginRes
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.http.HttpGo
import com.hjq.toast.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {

    val sendCodeState = MutableLiveData<Boolean>()
    val loginState = MutableLiveData<Boolean>()

    fun login(phone: String, authCdoe: String) {
        val map = mutableMapOf<String, String>()
        map.put("phone", phone)
        map.put("verifyCode",authCdoe)
        viewModelScope.launch(Dispatchers.IO) {
            val res = HttpGo.postSync<LoginRes>("/user/verifyCode/login", map)
            res?.let {
                if (it.code == 200) {
                    LoginUtils.token = it.data?.token
                    loginState.postValue(true)
                } else {
                    ToastUtils.show(it.error)
                }
            }

        }
    }

    fun getAuthCode(phone: String) {
        val map = mutableMapOf<String, String>()
        map.put("phone", phone)
        viewModelScope.launch(Dispatchers.IO) {
            val res = HttpGo.postSync<Boolean>("/user/sendSms", map)
            res?.let {
                if (it.code == 200) {
                    sendCodeState.postValue(true)
                } else {
                    ToastUtils.show(it.error)
                }
            }
        }
    }

}