package com.sixin.module_p.ui.guobang

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GbCarOrUldBean
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.impl.observe
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.limit
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue

class PdaGuoBangViewModel : BaseViewModel() {

    val weight = MutableLiveData("0")

    // 平板车或集装器
    val carUld = MutableLiveData("")
    val carUldBean = MutableLiveData(GbCarOrUldBean.Data())

    // 通道列表
    val channelList = MutableLiveData(emptyList<KeyValue>())
    private var channel = KeyValue("", "")

    // 板型
    val version = MutableLiveData("")

    // 高度
    val height = MutableLiveData("")

    // 收口
    val mouth = MutableLiveData("")

    // 尺寸
    val size = MutableLiveData("")

    // IMP代码
    val impCode = MutableLiveData("")

    // 装机重量
    val zjWeight = MutableLiveData("")

    // 货物重量
    val hwWeight = MutableLiveData("")

    val cargoTypeList = mutableListOf<KeyValue>()

    fun init(activity: AppCompatActivity) {
        // 获取通道列表
        DictUtils.getChannelList {
            channelList.postValue(listOf(KeyValue("请选择收运通道", "")) + it)
        }
        DictUtils.getCargoTypeList {
            cargoTypeList.clear()
            cargoTypeList.addAll(it)
        }

        weight.observe(activity) {
            computeWeight()
        }

        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .observe(activity) {
                carUld.value = it
                getCarOrUldData(it)
            }
    }

    /**
     * 通道 选中
     */
    fun channelSelected(position: Int) {
        channel = channelList.value!![position]
    }

    /**
     * 运单号 改变
     */
    fun onCarOrUldChange(focused: Boolean = false) {
        if (focused || carUld.value.isNullOrEmpty()) {
            return
        }
        getCarOrUldData(carUld.value!!)
    }

    /**
     * 获取平板车/集装器数据
     */
    private fun getCarOrUldData(data: String) {
        if (data.isEmpty()) {
            return
        }
        launchCollect({
            NetApply.api
                .getCarOrUldInfoForGb(data)
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    val bean = carUldBean.value!!.createForMerge(it.data!!.data!!)

                    if (!bean.getGjcLoadingBean().cargotype.isNullOrEmpty()) {
                        bean.getGjcLoadingBean().cargoName = cargoTypeList.firstOrNull { item ->
                            item.value == bean.getGjcLoadingBean().cargotype
                        }?.key
                    }

                    carUldBean.value = bean
                    computeWeight()
                } else {
                    showToast(it.msg.noNull("获取数据失败"))
                }
            }
        }
    }

    /**
     * 清空 点击
     */
    fun clearClick() {
        carUld.value = ""
    }

    private fun computeWeight() {
        val total = weight.value?.toFloatOrNull() ?: 0f
        val data = carUldBean.value!!
        val carWeight = data.carweight?.toFloatOrNull() ?: 0f
        val uldWeight = data.uldWeight?.toFloatOrNull() ?: 0f
        zjWeight.value = (total - carWeight).limit()
        hwWeight.value = (total - carWeight - uldWeight).limit()
    }

    /**
     * 确认点击
     */
    fun confirmClick() {
        val data = carUldBean.value!!
        if (data.carid.isNullOrEmpty() && data.uld.isNullOrEmpty()) {
            showToast("请扫描平板车或集装器")
            return
        }
        showLoading()
        launchCollect({
            NetApply.api.gjcBoxWeighingSubmit(
                mapOf(
                    "carid" to data.carid,
                    "carweight" to data.carweight,
                    "locId" to data.getGjcLoadingBean().locId,
                    "totalWeight" to data.totalWeight,
                    "gjcLoading" to listOf(
                        mapOf(
                            "cargoweight" to hwWeight.value,
                            "locId" to data.getGjcLoadingBean().locId,
                            "netweight" to zjWeight.value,
                            "remark" to "",
                            "uldweight" to data.uldWeight,
                        )
                    ),
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast("提交成功")
                    resetData()
                } else {
                    showToast(it.msg.noNull("提交失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    private fun resetData() {
        weight.value = "0"
        carUld.value = ""
        carUldBean.value = GbCarOrUldBean.Data()
        channel = KeyValue("", "")
        version.value = ""
        height.value = ""
        mouth.value = ""
        size.value = ""
        impCode.value = ""
        computeWeight()
    }
}