package com.lukouguoji.mit.viewModel

import android.util.Log
import androidx.lifecycle.*
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.module_base.common.String.emptyToNull
import com.lukouguoji.module_base.http.user.UserNetwork
import com.wega.library.loadingDialog.LoadingDialog
import kotlinx.coroutines.Dispatchers
import kotlin.collections.set

class OutLoadingPullViewModel : ViewModel() {

    /**
     * 选中
     */
    val checkCount: LiveData<Int>
        get() = _checkCount

    private val _checkCount = MutableLiveData<Int>()

    init {
        _checkCount.value = 0
    }

    fun plusOne() {
        val count = _checkCount.value ?: 0
        _checkCount.value = count + 1
    }

    fun subOne() {
        val count = _checkCount.value ?: 0
        _checkCount.value = count - 1
    }

    fun setCheckCount(count: Int) {
        _checkCount.value = count
    }


    /**
     * 分页搜索
     */
    private val searchParam = MutableLiveData<JSONObject>()
    val searchParamLive = Transformations.switchMap(searchParam) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.queryWbOutLoading(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }

    fun search(
        limit: Int,
        page: Int,
        fid: Int,
        location: String,
    ) {

        val param = JSONObject()
        param["limit"] = limit
        param["page"] = page
        param["id"] = fid
        param["location"] = location.emptyToNull()

        searchParam.value = param
    }

    /**
     * 拉货完结
     */
    private val completedLiveData = MutableLiveData<JSONObject>()
    val completedObserver = Transformations.switchMap(completedLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.pullOutLoading(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }

    fun completed(param: JSONArray) {
        val paramObj = JSONObject()
        paramObj["list"] = param
        completedLiveData.value = paramObj
    }

}