package com.sixin.module_p.ui.shouyun

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.SYWaybillBean
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.ktx.getLifecycleOwner
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.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.util.DictUtils
import com.sixin.module_p.helper.PDAHelper
import dev.DevUtils
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class PdaShouYunViewModel : BaseViewModel() {

    val weight = MutableLiveData("0")

    // 运单号
    val waybill = MutableLiveData("")

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

    // 托盘重量
    val palletWeight = MutableLiveData("0")

    // 运抵数量
    val arrivalCount = MutableLiveData("1")

    // 运抵重量
    val arrivalWeight = MutableLiveData("0")

    // 运抵体积
    val arrivalVolume = MutableLiveData("0")

    // 备注
    val remark = MutableLiveData("")

    // 运单信息
    val waybillBean = MutableLiveData<SYWaybillBean?>()

    fun init() {
        // 获取通道列表
        DictUtils.getChannelList {
            channelList.postValue(listOf(KeyValue("请选择收运通道", "")) + it)
        }
        // 监听扫描信息
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                getWaybillInfo(it)
            }
            .launchIn(viewModelScope)

        // 监听地磅重量并赋值
        weight.observe(DevUtils.getTopActivity().getLifecycleOwner()) {
            computeArrivalWeight()
        }
        palletWeight.observe(DevUtils.getTopActivity().getLifecycleOwner()) {
            computeArrivalWeight()
        }
        arrivalWeight.observe(DevUtils.getTopActivity().getLifecycleOwner()) {
            arrivalVolume.value = ((it.toFloatOrNull() ?: 0f) / 220f).limit()
        }
    }

    private fun computeArrivalWeight() {
        arrivalWeight.value = ((weight.value?.toFloatOrNull() ?: 0f)
                - (palletWeight.value?.toFloatOrNull() ?: 0f)).limit()
    }

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

    /**
     * 运单号 改变
     */
    fun onWaybillChange(focused: Boolean = false) {
        if (focused) {
            return
        }
        getWaybillInfo(waybill.value.noNull())
    }

    /**
     * 获取运单信息
     */
    private fun getWaybillInfo(data: String) {
        val waybill = PDAHelper.getWaybillFormScan(data)
        if (waybill.isEmpty()) {
            return
        }
        this@PdaShouYunViewModel.waybill.value = waybill
        launchCollect({
            NetApply.api.getSyWaybillInfo(waybill, arrivalWeight.value.noNull(""))
        }) {
            onSuccess = {
                if (!it.verifySuccess()) {
                    showToast(it.msg.noNull("获取运单信息失败"))
                } else {
                    it.data?.let { data ->
                        waybillBean.postValue(data)

//                    arrivalCount.value = data.recheckCount.noNull("1")
//                    arrivalWeight.value = data.arriveWeight.noNull("0")
//                    arrivalVolume.value = data.arriveVolume.noNull("0")
                    }
                }
            }
        }
    }

    /**
     * 确认点击
     */
    fun confirmClick() {
        if (waybillBean.value.verifyNullOrEmpty("请扫描运单")
            || palletWeight.value.verifyNullOrEmpty("请输入托盘重量")
            || arrivalCount.value.verifyNullOrEmpty("请输入运抵件数")
            || arrivalWeight.value.verifyNullOrEmpty("请输入运抵重量")
            || arrivalVolume.value.verifyNullOrEmpty("请输入运抵体积")
        ) {
            return
        }
        val bean = waybillBean.value!!
        showLoading()
        launchCollect({
            NetApply.api.completionCollection(
                mapOf(
                    "maWbId" to bean.maWbId,
                    "wbNo" to bean.wbNo,
                    "pclist" to bean.pclist,
                    "agentCode" to bean.agent.noNull(bean.agentCode.noNull()),
                    "goods" to bean.goods,
                    "spCode" to bean.spCode,
                    "businessType" to bean.businessType,
                    "awbType" to bean.awbType,
                    "pc" to bean.pc,
                    "weight" to bean.grossWeight,
                    "volume" to bean.volume,
                    "arrivePc" to arrivalCount.value,
                    "arriveWeight" to arrivalWeight.value,
                    "arriveVolume" to arrivalVolume.value,
                    "activeId" to bean.activeId,
                    "remark" to remark.value,
                    "dep" to bean.dep,
                    "dest" to bean.dest,
                    "dest1" to bean.dest1,
                    "by1" to bean.by1,
                    "checkIn" to bean.checkIn,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    resetData()
                    if (!it.msg.isNullOrEmpty()) {
                        showToast(it.msg!!)
                    }
                } else {
                    showToast(it.msg.noNull("收运失败"))
                }
            }
            onComplete = {
                dismissLoading()
            }
        }
    }

    private fun resetData() {
        waybillBean.value = null
        palletWeight.value = "0"
        arrivalWeight.value = "0"
        arrivalCount.value = "1"
        arrivalVolume.value = "0"
        remark.value = ""
    }
}