package com.lukouguoji.gnc.viewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.module_base.http.user.UserNetwork
import kotlinx.coroutines.Dispatchers

class GoutCollectionViewModel : ViewModel() {

    private val searchParam = MutableLiveData<JSONObject>()

    val searchParamLive = Transformations.switchMap(searchParam) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.search(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }

    fun search(limit: Int, page: Int, text: String) {
        val param = JSONObject()
        param["limit"] = limit
        param["page"] = page
        param["text"] = text

        searchParam.value = param
    }


    /**
     * 代理人
     */
    var agentCodeList = JSONArray()
    private val agentCodeLiveData = MutableLiveData<String>()
    fun agentCode(time: String) {
        agentCodeLiveData.value = time
    }

    val agentCodeObserver = Transformations.switchMap(agentCodeLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.agentCodeGnc()
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    /**
     * 特码
     */
    var specialCodeList = JSONArray()
    private val specialCodeLiveData = MutableLiveData<String>()
    fun specialCode(time: String) {
        specialCodeLiveData.value = time
    }

    val specialCodeObserver = Transformations.switchMap(specialCodeLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.specialCode()
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

}