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.JSONObject
import com.lukouguoji.module_base.common.String.emptyToNull
import com.lukouguoji.module_base.http.user.UserNetwork
import kotlinx.coroutines.Dispatchers

class GoutWareHouseListViewModel : ViewModel() {

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

        }
    }

    fun search(
        limit: Int,
        page: Int,
        carrier: String,
        beginDate: String,
        endDate: String,
        fdate: String,//航班日期
        fno: String,//航班编码
        dest: String,//目的港
        location: String,//舱位
        range: String,
        status: String,
        wbNo: String,
        groupName: String,
    ) {
        val param = JSONObject()
        param["limit"] = limit
        param["page"] = page
        param["carrier"] = carrier.emptyToNull()
        param["beginDate"] = beginDate.emptyToNull()
        param["endDate"] = endDate.emptyToNull()
        param["fdate"] = fdate.emptyToNull()
        param["dest"] = dest.emptyToNull()
        param["fno"] = fno.emptyToNull()
        param["location"] = location.emptyToNull()
        param["range"] = range.emptyToNull()
        param["locStatus"] = status.emptyToNull()
        param["wbNo"] = wbNo.emptyToNull()
        param["groupName"] = groupName.emptyToNull()

        searchParam.value = param
    }

    /**
     * 数据汇总
     */
    val summaryObserver = Transformations.switchMap(searchParam) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.totalGncWareHouse(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }


}