package com.sixin.module_p.ui.lihuo

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlatcarBean
import com.lukouguoji.module_base.bean.GjjHandoverRecordBean
import com.lukouguoji.module_base.bean.GjjTallyAddBean
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.commonAdapter
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.sixin.module_p.helper.PDAHelper
import com.sixin.module_p.model.PdaLhSelectDialogModel
import dev.DevUtils
import dev.utils.common.NumberUtils
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class PdaLiHuoViewModel : BasePageViewModel() {

    // 平板车
    val car = MutableLiveData("")

    // 平板车信息
    val flatcarBean = MutableLiveData<FlatcarBean>()

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

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    private fun reset() {
        car.value = ""
        waybill.value = ""
        flatcarBean.value = FlatcarBean()
        pageModel.refresh()
        pageModel.handleDataList(emptyList())
    }

    fun init() {
        // 监听扫描信息
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                onPdaScan(it)
            }
            .launchIn(viewModelScope)
    }

    /**
     * Pda扫码回调
     */
    private fun onPdaScan(data: String) {
        val waybill = PDAHelper.getWaybillFormScan(data)
        if (waybill.isEmpty()) {
            car.value = data
            onCarChange(false)
        } else {
            this.waybill.value = waybill
            onWaybillChange(false)
        }
    }

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

    fun onCarChange(focus: Boolean) {
        if (focus) {
            return
        }
        getFlatcarInfo(car.value!!)
    }

    fun onWaybillChange(focused: Boolean = false) {
        if (focused || waybill.value!!.isEmpty()) {
            return
        }
        val code = waybill.value.noNull()
        if (NumberUtils.isNumber(code)) {
            // 运单号
            if (code.length == 11) {
                addWaybillInfo(code)
            }
            // 运单号 + 件号
            else if (code.length == 16) {
                addWaybillInfo(code.substring(0, 11), code.substring(11))
            }
        }
    }

    /**
     * 获取运单信息
     * @param waybillCode 运单号
     * @param jianCode 件号
     */
    private fun addWaybillInfo(waybillCode: String, jianCode: String = "") {
        val adapter = pageModel.rv!!.commonAdapter()!!
        if (adapter.itemCount > 0) {
            val bean = adapter.items.first() as GjjTallyAddBean
            if (bean.handoverRecordBean.getWaybillCode() == waybillCode) {
                bean.addJian(jianCode)
            } else {
                showToast("请先完成当前运单信息")
            }
            return
        }
        launchCollect({
            NetApply.api.getGjjTallyHandoverList(
                mapOf(
                    "prefix" to waybillCode.substring(0, 3),
                    "no" to waybillCode.substring(3),
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess() && !it.data.isNullOrEmpty()) {
                    if (it.data!!.size == 1) {
                        val bean = it.data!!.first()
                        val addBean = GjjTallyAddBean(bean)
                        if (jianCode.isNotEmpty()) {
                            addBean.addJian(jianCode)
                        }
                        adapter.addItem(addBean)
                    } else {
                        showSelectDialog(DevUtils.getTopActivity(), it.data!!, jianCode)
                    }
                } else {
                    showToast(it.msg.noNull("获取运单信息失败"))
                }
            }
        }
    }

    /**
     * 展示选择弹窗
     * 仅用于选择返回
     */
    private fun showSelectDialog(
        context: Context,
        list: List<GjjHandoverRecordBean>,
        jianCode: String = ""
    ) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        loge("展示选择弹窗 : ${list.size}")
        PdaLhSelectDialogModel(list) { bean ->
            val addBean = GjjTallyAddBean(bean)
            if (jianCode.isNotEmpty()) {
                addBean.addJian(jianCode)
            }
            adapter.addItem(addBean)
        }.show(context)
    }

    /**
     * 获取平板车数据
     */
    private fun getFlatcarInfo(id: String) {
        if (id.isEmpty()) {
            return
        }
        launchCollect({
            NetApply.api
                .getFlatcarInfo(id)
        }) {
            onSuccess = {
                if (it.verifySuccess() && it.data != null) {
                    flatcarBean.value = it.data
                } else {
                    showToast(it.msg.noNull("获取平板车信息失败"))
                }
            }
        }
    }

    /**
     * 确认点击
     */
    fun confirmClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val count = adapter.itemCount
        if (flatcarBean.value == null) {
            showToast("请先扫描平板车")
            return
        }
        if (count <= 0) {
            showToast("请先添加运单信息")
            return
        }

        val bean = adapter.items.first() as GjjTallyAddBean
        val jianListStr = bean.jianList.joinToString(",") { it.value }

        showLoading()
        launchCollect({
            val requestBody = mapOf(
                "carID" to flatcarBean.value!!.carId,
                "isBatch" to "1",
                "list" to jianListStr,
                "mfId" to bean.handoverRecordBean.mfId,
                "no" to bean.handoverRecordBean.no,
                "organizationcode" to bean.handoverRecordBean.organizationCode,
                "pc" to bean.handoverRecordBean.pc,
                "prefix" to bean.handoverRecordBean.prefix,
                "weight" to bean.handoverRecordBean.weight,
                "pcID" to bean.handoverRecordBean.pcID,
            ).toRequestBody()
            NetApply.api.gjjTallyConfirm(requestBody)
        }) {
            onSuccess = {
                dismissLoading()
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("确认成功"))
                    reset()
                } else {
                    showToast(it.msg.noNull("确认失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    override fun getData() {

    }
}