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
import kotlinx.coroutines.withContext

class LoginViewModel : ViewModel() {

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

    val timerNumber = MutableLiveData<Int>()

    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>("/api/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>("/api/user/sendSms", map)
            res?.let {
                if (it.code == 200) {
                    sendCodeState.postValue(true)
                } else {
                    sendCodeState.postValue(false)
                    ToastUtils.show(it.error)
                }
            }?:let {
                sendCodeState.postValue(false)
            }
        }
    }

}