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 com.lukouguoji.gnc.model.GncTransferRef
import kotlinx.coroutines.Dispatchers


class GoutTransferInfoViewModel : ViewModel() {
    /**
     * 转运查询 返回数据
     */
    var flatcarObjFromNet = JSONObject()
    var wbListArrFromNet = JSONArray()
    var gncTransferRefList = arrayListOf<GncTransferRef>()

    /**
     * 转运查询
     */
    inner class WaybillParam(val id: Int, val carId: String?)
    private val queryFlatByNoLiveData = MutableLiveData<WaybillParam>()
    val queryFlatByNoObserver = Transformations.switchMap(queryFlatByNoLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                var response = JSONObject()
                if (param.id != -9999) {
                    response = UserNetwork.queryFlatById(param.id)
                } else if (param.carId != null) {
                    response = UserNetwork.queryFlatByNo(param.carId)
                } else {
                }
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutTransferViewModel", e.stackTraceToString())
            }

        }
    }

    fun queryFlatByNo(id: Int, carId: String?) {
        queryFlatByNoLiveData.value = WaybillParam(id, carId)
    }

    /**
     * 转运确认
     */
    private val completedTransferLiveData = MutableLiveData<JSONObject>()
    val completedTransferObserver = Transformations.switchMap(completedTransferLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.completedTransfer(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutTransferViewModel", e.stackTraceToString())
            }

        }
    }

    fun completedTransfer(paramObj: JSONObject) {
        completedTransferLiveData.value = paramObj
    }
}