package com.lukouguoji.gjc.viewModel

import android.util.Log
import androidx.lifecycle.*
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.module_base.common.String.emptyToNull
import com.lukouguoji.module_base.http.user.UserNetwork
import kotlinx.coroutines.Dispatchers

class GjcYiKuListViewModel : ViewModel() {
    /**
     * 航班号
     */
    var fid: Int? = null

    /**
     * 选中
     */
    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.searchGjcYiKu(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }

    fun search(
        limit: Int,
        page: Int,
        wbNo: String,
        dest: String,
        carrier: String
    ) {

        val param = JSONObject()
        param["limit"] = limit
        param["page"] = page
        param["wbNo"] = wbNo.emptyToNull()
        param["dest"] = dest.emptyToNull()
        param["carrier"] = carrier.emptyToNull()

        searchParam.value = param
    }


    /**
     * 确认移库
     */
    private val moveGnjYiKuLiveData = MutableLiveData<JSONObject>()
    val moveGnjYiKuObserver = Transformations.switchMap(moveGnjYiKuLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.moveGjcYiKu(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }

    fun moveGnjYiKu(ids: List<Int>) {
        val temObj = JSONObject()
        temObj["fid"] = 0 //随意填，不起作用
        temObj["ids"] = ids

        moveGnjYiKuLiveData.value = temObj
    }

}