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

import androidx.collection.ArrayMap
import androidx.lifecycle.MutableLiveData
import com.cheng.blzb.bean.BidItemEntity
import com.cheng.blzb.bean.BidTypeEntity
import com.cheng.blzb.bean.UserAuthEntity
import com.cheng.blzb.net.ApiFactory
import com.cheng.blzb.net.model.toListResult
import com.example.base.extensions.toast
import com.example.base.utils.L
import com.example.base.viewmodel.ListViewModel

class HomeViewModel : ListViewModel<BidItemEntity>() {
    val totalLiveData = MutableLiveData<String>()

    val typeLiveData = MutableLiveData<List<BidTypeEntity>>()
    val authLiveData = MutableLiveData<UserAuthEntity>()
    val recommendLiveData = MutableLiveData<List<String>>()

    override suspend fun requestApi(params: ArrayMap<String, String>): Result<List<BidItemEntity>> {
        params["sort"] = "123"
        val response = ApiFactory.apiService.getRecommendList(params)
        if (response.status) {
            totalLiveData.postValue(response.data.total)
        }
        return response.toListResult()
    }

    fun getBidTypeList(showLoading: Boolean = false) {
        if (showLoading) showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.getBidTypeList()
            if (response.status) {
                typeLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun getHotKeywordList(query: String) {
        launchOnUiTryCatch({
            val params = mutableMapOf<String, String>()
            params["query"] = query
            params["size"] = "4"
            val response = ApiFactory.apiService.getHotKeywords(params)
            if (response.status) {
                recommendLiveData.postValue(response.data)
            } else toast(response.message, true)
        }, {
            setError(it)
            L.d(it)
        })
    }

    fun checkAuth() {
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.checkAuth()
            if (response.status) {
                authLiveData.postValue(response.data)
            } else toast(response.message, true)
        }, {
            setError(it)
            L.d(it)
        })
    }

}