package com.cheng.blzb.ui.fragment.home.bszz

import androidx.lifecycle.MutableLiveData
import com.cheng.blzb.bean.SendCodeEntity
import com.cheng.blzb.net.ApiFactory
import com.example.base.common.RxCountDown
import com.example.base.extensions.toast
import com.example.base.utils.L
import com.example.base.viewmodel.BaseViewModel
import io.reactivex.rxjava3.disposables.Disposable
import okhttp3.RequestBody

class BSZZViewModel: BaseViewModel() {
    private var disposable: Disposable? = null

    var sendCodeLiveData = MutableLiveData<SendCodeEntity>()
    val countTimeLiveEvent = MutableLiveData<Long>()
    val addLiveData = MutableLiveData<Any>()

    fun sendCode(phone: String) {
        showDialog()
        launchOnUiTryCatch({
            val map = HashMap<String, String>()
            map["phone"] = phone
            val response = ApiFactory.apiService.sendCode(map)
            if (response.status) {
                sendCodeLiveData.postValue(response.data)
                startTimer()
            } else {
                toast(response.message, true)
            }
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

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

    private fun startTimer() {
        disposable?.dispose()
        disposable = RxCountDown.countdown(60).subscribe {
            countTimeLiveEvent.value = it
        }
    }

    override fun onCleared() {
        super.onCleared()
        disposable?.dispose()
    }
}