package com.lukouguoji.mit.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
import kotlin.collections.set

class OutLoadingViewModel : ViewModel() {

    private val logName = "OutLoadingViewModel"

    /**
     * 航班号
     */
    var fid: Int? = null
    var fno: String? = null
    var fdate: String? = null
    var cars: String = ""
    var fdest: String? = null
    var countryType: String? = null
    var countryName: String? = null
    var fdep:String?=null


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

        }
    }

    fun search(
        fdate: String,//航班日期
        fno: String//航班号
    ) {
        val param = JSONObject()
        param["fdate"] = fdate.emptyToNull()
        param["fno"] = fno.emptyToNull()

        searchParam.value = param
    }

    /**
     * 查询航班
     */
    private val queryFlightLiveData = MutableLiveData<JSONObject>()
    val queryFlightObserver = Transformations.switchMap(queryFlightLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.queryFlightMitInPack(param)
                emit(response)
            } catch (e: Exception) {
                Log.e(logName, e.stackTraceToString())
            }

        }
    }

    fun queryFlight(fdate: String, fno: String,fdep:String) {
        val temObj = JSONObject()
        temObj["fdate"] = fdate.emptyToNull()
        temObj["fno"] = fno.emptyToNull()
        temObj["fdep"] = fdep.emptyToNull()
        queryFlightLiveData.value = temObj
    }

    /**
     * 货物发放
     */
    private val provideGjjCangDanLiveData = MutableLiveData<JSONObject>()
    val provideGjjCangDanObserver = Transformations.switchMap(provideGjjCangDanLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.provideGjjCangDan(param)
                emit(response)
            } catch (e: Exception) {
                Log.e(logName, e.stackTraceToString())
            }

        }
    }

    fun provideGjjCangDan(fid: Int, ids: List<Int>) {
        val temObj = JSONObject()
        temObj["fid"] = fid
        temObj["ids"] = ids

        provideGjjCangDanLiveData.value = temObj
    }
}