package com.lukouguoji.gjj.viewModel

import android.content.Intent
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.common.DetailsPageType
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.ktx.finish
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
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 dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

class GjjManifestAddViewModel : BaseViewModel() {

    // 页面类型（必须用LiveData）
    val pageType = MutableLiveData(DetailsPageType.Add)

    // 舱单ID（编辑时使用）
    var mfId: Long = 0

    // 航班ID
    var fid: String = ""

    // 航班日期
    val flightDate = MutableLiveData("")

    // 航班号
    val flightNo = MutableLiveData("")

    // 航程
    val range = MutableLiveData("")

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

    // UN编号
    val unNumber = MutableLiveData("")

    // 运单件数
    val waybillNum = MutableLiveData("")

    // 实到数量
    val actualNum = MutableLiveData("")

    // 实到重量
    val actualWeight = MutableLiveData("")

    // 计费重量
    val billingWeight = MutableLiveData("")

    // 始发港
    val departure = MutableLiveData("")

    // 目的港
    val destination = MutableLiveData("")

    // 品名(中)
    val goodsNameCn = MutableLiveData("")

    // 品名(英)
    val goodsNameEn = MutableLiveData("")

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


    // 业务类型 列表
    val businessTypeList = MutableLiveData<List<KeyValue>>()
    val businessType = MutableLiveData("")

    // 包装类型 列表
    val packageTypeList = MutableLiveData<List<KeyValue>>()
    val packageType = MutableLiveData("")

    // 代理列表
    val agentList = MutableLiveData<List<KeyValue>>()
    val agent = MutableLiveData("")

    // 特码列表
    val specialCodeList = MutableLiveData<List<KeyValue>>()
    val specialCode = MutableLiveData("")

    // 货物类型
    val goodsTypeList = MutableLiveData<List<KeyValue>>()
    val goodsType = MutableLiveData("")

    // 运单类型
    val waybillTypeList = MutableLiveData<List<KeyValue>>()
    val waybillType = MutableLiveData("")

    init {
        DictUtils.getAgentList(addAll = false) {
            agentList.postValue(listOf(KeyValue("", "")) + it)
        }
        DictUtils.getSpecialCodeList(addAll = false, flag = 1, ieFlag = "I") {
            val list = arrayListOf<KeyValue>()
            it.find { b -> b.key.contains("普通货物") }?.let { b ->
                list.add(b)
            }
            list.addAll(it.filter { b -> !b.key.contains("普通货物") })
            specialCodeList.postValue(list)
        }
        DictUtils.getBusinessTypeList(addAll = false) {
            businessTypeList.postValue(it)
        }
        DictUtils.getGjjPackageTypeList(addAll = false) {
            packageTypeList.postValue(listOf(KeyValue("", "")) + it)
        }
        DictUtils.getGjjGoodsTypeList(addAll = false) {
            goodsTypeList.postValue(it)
        }
        DictUtils.getWaybillTypeList(type = "II", addAll = false) {
            val list = arrayListOf<KeyValue>()
            it.find { b -> b.key.contains("干线") }?.let { b ->
                list.add(b)
            }
            list.addAll(it.filter { b -> !b.key.contains("干线") })
            waybillTypeList.postValue(list)
        }
    }

    /**
     * 初始化（从Intent获取参数）
     */
    fun initOnCreated(intent: Intent) {
        // 获取页面类型
        pageType.value = DetailsPageType.valueOf(
            intent.getStringExtra(Constant.Key.PAGE_TYPE) ?: DetailsPageType.Add.name
        )

        // 获取航班ID
        fid = intent.getStringExtra(Constant.Key.ID).noNull()
        departure.value = intent.getStringExtra(Constant.Key.DEPARTURE).noNull()
        destination.value = intent.getStringExtra(Constant.Key.DESTINATION).noNull()

        // 编辑模式：从Bean对象加载数据
        if (pageType.value == DetailsPageType.Modify) {
            val bean = intent.getSerializableExtra(Constant.Key.BEAN) as? com.lukouguoji.module_base.bean.GjjManifest
            if (bean != null) {
                loadManifestFromBean(bean)
            }
        }
    }

    /**
     * 从Bean对象加载数据（编辑模式）
     */
    private fun loadManifestFromBean(manifest: com.lukouguoji.module_base.bean.GjjManifest) {
        // 保存舱单ID
        mfId = manifest.mfId
        fid = manifest.fid.toString()

        // 填充表单字段
        waybillNo.value = manifest.wbNo
        waybillNum.value = manifest.totalPc.toString()
        actualNum.value = manifest.pc.toString()
        actualWeight.value = manifest.weight.toString()
        billingWeight.value = manifest.cashWeight.toString()
        departure.value = manifest.origin
        destination.value = manifest.dest
        goodsNameCn.value = manifest.goodsCn
        goodsNameEn.value = manifest.goods
        unNumber.value = manifest.unNumber
        remark.value = manifest.remark

        // 设置下拉框选中值
        agent.value = manifest.agentCode
        specialCode.value = manifest.spCode
        packageType.value = manifest.packageType
        businessType.value = manifest.businessType
        goodsType.value = manifest.cargoType
        waybillType.value = manifest.awbType
    }

    /**
     * 保存点击
     */
    fun onSaveClick(view: View) {
        if ((waybillNo.value.verifyNullOrEmpty("请输入运单号")
                    || agent.value.verifyNullOrEmpty("请选择代理")
                    || waybillNum.value.verifyNullOrEmpty("请输入运单件数")
                    || actualNum.value.verifyNullOrEmpty("请输入实到数量")
                    || goodsNameEn.value.verifyNullOrEmpty("请输入品名(英)")
                    || actualWeight.value.verifyNullOrEmpty("请输入实到重量")
                    || packageType.value.verifyNullOrEmpty("请选择包装类型")
                    )
        ) {
            return
        }

        val params = mapOf(
            "mfId" to if (pageType.value == DetailsPageType.Modify) mfId else null,
            "fid" to fid,
            "wbNo" to waybillNo.value,
            "agent" to agent.value,
            "spCode" to specialCode.value,
            "businessType" to businessType.value,
            "awbpc" to waybillNum.value,
            "pc" to actualNum.value,
            "weight" to actualWeight.value,
            "planweight" to billingWeight.value,
            "packagecode" to packageType.value,
            "dep" to departure.value,
            "origin" to departure.value,
            "dest" to destination.value,
            "goods" to goodsNameEn.value,
            "goodsCn" to goodsNameCn.value,
            "awbType" to waybillType.value,
            "cargoType" to goodsType.value,
            "unNumber" to unNumber.value,
            "remark" to remark.value,
        ).toRequestBody(removeEmptyOrNull = true)

        launchLoadingCollect({
            if (pageType.value == DetailsPageType.Modify) {
                NetApply.api.gjjManifestUpdate(params)
            } else {
                NetApply.api.gjjManifestInsert(params)
            }
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    val successMsg = if (pageType.value == DetailsPageType.Modify) "修改成功" else "保存成功"
                    showToast(successMsg)

                    // 发送刷新事件
                    viewModelScope.launch {
                        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                    }

                    view.context.finish()
                } else {
                    showToast(it.msg.noNull("保存失败"))
                }
            }
        }
    }

    /**
     * 取消点击
     */
    fun onCancelClick(view: View) {
        view.context.finish()
    }

}