package com.lukouguoji.gjj.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.activity.IntImpManifestSubEditActivity
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GjjHaWb
import com.lukouguoji.module_base.bean.GjjManifest
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.launchLoadingCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import kotlinx.coroutines.launch

/**
 * 国际进港舱单-分单编辑 ViewModel
 */
class IntImpManifestSubEditViewModel : BaseViewModel() {

    // 页面类型
    val pageType = MutableLiveData(DetailsPageType.Add)

    // 分单ID（编辑时使用）
    var hawbId: Long = 0

    // 主单ID
    var mfId: Long = 0

    // 运单号前缀和编号（从主单获取，保存时需传给接口）
    var prefix: String = ""
    var no: String = ""

    // 表单字段
    val waybillNo = MutableLiveData("")       // 运单号（只读）
    val mainSubCheck = MutableLiveData("")    // 主分校验（只读）
    val subNo = MutableLiveData("")           // 分单号
    val pc = MutableLiveData("")              // 件数
    val weight = MutableLiveData("")          // 重量
    val goodsCn = MutableLiveData("")         // 品名(中)

    // 主单件数/重量
    private var mainPc: Long = 0
    private var mainWeight: Double = 0.0

    // 其他分单件数/重量之和（不含当前编辑的分单）
    private var otherSubPc: Long = 0
    private var otherSubWeight: Double = 0.0

    // 主分校验是否通过（true=绿色允许保存，false=红色不允许保存）
    val isCheckValid = MutableLiveData(true)

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

        // 获取主单信息
        val manifest = intent.getSerializableExtra(Constant.Key.BEAN) as? GjjManifest
        if (manifest != null) {
            mfId = manifest.mfId
            prefix = manifest.prefix
            no = manifest.no
            waybillNo.value = manifest.getWaybillNo()
        }

        // 获取主分校验参数
        mainPc = intent.getLongExtra(IntImpManifestSubEditActivity.KEY_MAIN_PC, 0)
        mainWeight = intent.getDoubleExtra(IntImpManifestSubEditActivity.KEY_MAIN_WEIGHT, 0.0)
        otherSubPc = intent.getLongExtra(IntImpManifestSubEditActivity.KEY_OTHER_SUB_PC, 0)
        otherSubWeight = intent.getDoubleExtra(IntImpManifestSubEditActivity.KEY_OTHER_SUB_WEIGHT, 0.0)

        // 编辑模式：回填分单数据
        if (pageType.value == DetailsPageType.Modify) {
            val haWb = intent.getSerializableExtra("haWb") as? GjjHaWb
            if (haWb != null) {
                hawbId = haWb.hawbId
                subNo.value = haWb.hno
                pc.value = if (haWb.pc > 0) haWb.pc.toString() else ""
                weight.value = if (haWb.weight > 0) haWb.weight.toString() else ""
                goodsCn.value = haWb.goodsCn.ifEmpty { haWb.goods }
            }
        }

        // 计算主分校验
        updateMainSubCheck()
    }

    /**
     * 件数输入完成回调
     */
    fun onPcInputComplete() {
        updateMainSubCheck()
    }

    /**
     * 重量输入完成回调
     */
    fun onWeightInputComplete() {
        updateMainSubCheck()
    }

    /**
     * 实时计算主分校验
     * 格式：分单之和件数/主单件数 分单之和重量/主单重量KG
     * 颜色：分单之和 > 主单 → 红色（不允许保存），否则 → 绿色
     */
    private fun updateMainSubCheck() {
        val currentPc = pc.value?.toLongOrNull() ?: 0
        val currentWeight = weight.value?.toDoubleOrNull() ?: 0.0

        val totalSubPc = otherSubPc + currentPc
        val totalSubWeight = otherSubWeight + currentWeight

        mainSubCheck.value = "${totalSubPc}/${mainPc}    ${formatWeight(totalSubWeight)}/${formatWeight(mainWeight)}KG"

        // 件数或重量任一超过主单则校验不通过
        isCheckValid.value = totalSubPc <= mainPc && totalSubWeight <= mainWeight
    }

    /**
     * 格式化重量显示（整数不显示小数位）
     */
    private fun formatWeight(value: Double): String {
        return if (value % 1.0 == 0.0) {
            value.toLong().toString()
        } else {
            value.toString()
        }
    }

    /**
     * 保存
     */
    fun onSaveClick() {
        // 主分校验不通过时禁止保存
        if (isCheckValid.value == false) {
            showToast("分单之和超过主单，不允许保存")
            return
        }

        val params = mutableMapOf<String, Any?>(
            "mfId" to mfId,
            "prefix" to prefix,
            "no" to no,
            "hno" to subNo.value,
            "pc" to pc.value?.toLongOrNull(),
            "weight" to weight.value?.toDoubleOrNull(),
            "goodsCn" to goodsCn.value,
            "goods" to goodsCn.value
        )

        if (pageType.value == DetailsPageType.Modify) {
            params["hawbId"] = hawbId
        }

        launchLoadingCollect({
            if (pageType.value == DetailsPageType.Modify) {
                NetApply.api.intImpManifestModifyHaWb(params.toRequestBody())
            } else {
                NetApply.api.intImpManifestAddHaWb(params.toRequestBody())
            }
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    val msg = if (pageType.value == DetailsPageType.Modify) "修改成功" else "新增成功"
                    showToast(msg)
                    viewModelScope.launch {
                        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                    }
                    getTopActivity().finish()
                } else {
                    showToast(it.msg.noNull("保存失败"))
                }
            }
        }
    }

    /**
     * 取消
     */
    fun onCancelClick() {
        getTopActivity().finish()
    }
}
