package com.lukouguoji.gjc.viewModel

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.liveData
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gjc.model.GjcFuBang
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.BoxDetailsForCarIdBean
import com.lukouguoji.module_base.common.String.emptyToNull
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.http.user.UserNetwork
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import kotlinx.coroutines.Dispatchers

class GjcFuBangViewModel : BaseViewModel() {
    var plCloseList = JSONArray()

    /**
     * 接口返回复磅信息
     */
    var fuBangInfoFormNetWork = JSONObject()
    var fuBangInfo = GjcFuBang()

    /**
     *  集装器编号，查询集装器自重
     */
    private val queryUldGjcReceiveLiveData = MutableLiveData<String>()
    val queryUldGjcReceiveObserver =
        Transformations.switchMap(queryUldGjcReceiveLiveData) { param ->
            liveData(Dispatchers.IO) {
                try {
                    var response = UserNetwork.queryUldGjcReceive(param)
                    emit(response)
                } catch (e: Exception) {
                    Log.e("GoutStartViewModel", e.stackTraceToString())
                }

            }
        }

    fun queryUldGjcReceive(id: String) {
        queryUldGjcReceiveLiveData.value = id
    }

    /**
     *  托盘编号，查询托盘自重
     */
    private val queryFlatcarGjcReceiveLiveData = MutableLiveData<String>()
    val queryFlatcarGjcReceiveObserver =
        Transformations.switchMap(queryFlatcarGjcReceiveLiveData) { param ->
            liveData(Dispatchers.IO) {
                try {
                    var response = UserNetwork.queryFlatcarGjcReceive(param)
                    emit(response)
                } catch (e: Exception) {
                    Log.e("GoutStartViewModel", e.stackTraceToString())
                }

            }
        }

    // 板箱详情
    val boxDetails = MutableLiveData<BoxDetailsForCarIdBean>()

    fun queryFlatcarGjcReceive(id: String) {
        queryFlatcarGjcReceiveLiveData.value = id
    }

    fun getBoxDetailsByCarId(carId: String) {
        launchCollect({
            NetApply.api.getGjcBoxAssembleByCarIdList(
                mapOf(
                    "carid" to carId
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.data != null) {
                    boxDetails.value = it.data
                }
            }
        }
    }

    /**
     * 完成复磅
     */
    private val completedLiveData = MutableLiveData<JSONObject>()
    val completedObserver = Transformations.switchMap(completedLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.completedGjcFuBang(param!!)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun completed(gjcFuBang: GjcFuBang) {
        val jsonObject = fuBangInfoFormNetWork
        jsonObject["carId"] = gjcFuBang.carId
        jsonObject["uld"] = gjcFuBang.uld
        jsonObject["carWeight"] = gjcFuBang.carWeight
        jsonObject["uldWeight"] = gjcFuBang.uldWeight
        jsonObject["netWeight"] = gjcFuBang.netWeight
        jsonObject["dgrCode"] = gjcFuBang.dgrCode
        jsonObject["boardType"] = gjcFuBang.boardType
        jsonObject["cargoWeight"] = gjcFuBang.cargoWeight
        jsonObject["plClose"] = gjcFuBang.plClose
        jsonObject["plCloseSize"] = gjcFuBang.plCloseSize
        jsonObject["totalWeight"] = gjcFuBang.totalWeight
        jsonObject["height"] = gjcFuBang.height
        jsonObject["fdate"] = gjcFuBang.fdate
        jsonObject["fno"] = gjcFuBang.fno
        jsonObject["fdest"] = gjcFuBang.fdest
        jsonObject["cargoType"] = gjcFuBang.cargoType
        jsonObject["remark"] = gjcFuBang.remark
        completedLiveData.value = jsonObject
    }

    fun onConfirmClick(context: Context, gjcFuBang: GjcFuBang, callBack: () -> Unit) {
        showLoading()
        launchCollect({
            NetApply.api.gjcBoxWeighingSubmit(
                mapOf(
                    "carid" to gjcFuBang.carId,
                    "carweight" to gjcFuBang.carWeight,
                    "locId" to boxDetails.value?.locId,
                    "totalWeight" to gjcFuBang.totalWeight,
                    "gjcLoading" to listOf(
                        mapOf(
                            "cargoweight" to gjcFuBang.cargoWeight,
                            "locId" to boxDetails.value?.locId,
                            "netweight" to gjcFuBang.netWeight,
                            "remark" to gjcFuBang.remark,
                            "uldweight" to gjcFuBang.uldWeight,
                        )
                    ),
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast("提交成功")
                    callBack()
                } else {
                    showToast(it.msg.noNull("提交失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 货物类型 下拉框
     */
    var cargoList = JSONArray()
    private val cargoLiveData = MutableLiveData<String>()
    val cargoObserver = Transformations.switchMap(cargoLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.cargoSelectGjc()
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutFuBangViewModel", e.stackTraceToString())
            }

        }
    }

    fun cargoSelect(type: String) {
        cargoLiveData.value = type
    }

    /**
     * 查询航班
     */
    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("GjcFuBangViewModel", e.stackTraceToString())
            }

        }
    }

    fun queryFlight(fdate: String, fno: String) {
        val temObj = JSONObject()
        temObj["countryType"] = null
        temObj["fclose"] = null
        temObj["fdate"] = fdate.emptyToNull()
        temObj["fdep"] = null
        temObj["fdest"] = null
        temObj["fid"] = null
        temObj["fno"] = fno.emptyToNull()
        temObj["mclose"] = null


        queryFlightLiveData.value = temObj
    }
}

class CarParam(val carNo: String?, val userId: String?)