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.SysUtils
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
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>()

    val timerNumber = MutableLiveData<Int>()

    fun login(phone: String, authCdoe: String) {
        val map = mutableMapOf<String, String>()
        map.put("phone", phone)
        map.put("verifyCode", authCdoe)
        SysUtils.getDeviceUUID()?.let { map.put("did", it) }
        viewModelScope.launch(Dispatchers.IO) {
            val res = HttpGo.postSync<LoginRes>("/api/user/verifyCode/login", map)
            res?.let {
                if (it.code == 200) {
                    DataRePortUtils.report("st_login_vercode_result", mapOf("result" to 1))
                    LoginUtils.token = it.data?.token
                    LoginUtils.uid = it.data?.phone
                    loginState.postValue(true)
                } else {
                    val map = mutableMapOf<String, Any>("result" to 0)
                    it.error?.let { it1 ->
                        map.put("cause", it1)
                    }
                    DataRePortUtils.report(
                        "st_login_vercode_result", map
                    )
                    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)
            }
        }
    }

}