package com.lukouguoji.gjj.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.IntImpPickUpRecordBean
import com.lukouguoji.module_base.common.Constant
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.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import kotlinx.coroutines.launch

/**
 * 国际进港费用修改 ViewModel
 */
class IntImpPickUpChargeEditViewModel : BaseViewModel() {

    val dataBean = MutableLiveData(IntImpPickUpRecordBean())

    // 可编辑费用字段（String 用于双向绑定）
    val tranChargeStr = MutableLiveData("")       // 信息费
    val whsChargeStr = MutableLiveData("")        // 仓储费
    val drawBillChargeStr = MutableLiveData("")   // 文件处理费
    val svlChargeStr = MutableLiveData("")        // 叉车费
    val tallyChargeStr = MutableLiveData("")      // 理货费
    val pipFeeStr = MutableLiveData("")             // 精密仪器处理费
    val lapFeeStr = MutableLiveData("")             // 活体动物处理费
    val totalAmountStr = MutableLiveData("")      // 总费用（实时计算）

    // 总费用计算观察者
    private val totalCalculator = Observer<String> { calculateTotal() }

    private fun calculateTotal() {
        val total = (tranChargeStr.value?.toDoubleOrNull() ?: 0.0) +
                (whsChargeStr.value?.toDoubleOrNull() ?: 0.0) +
                (drawBillChargeStr.value?.toDoubleOrNull() ?: 0.0) +
                (svlChargeStr.value?.toDoubleOrNull() ?: 0.0) +
                (tallyChargeStr.value?.toDoubleOrNull() ?: 0.0) +
                (dataBean.value?.optCharge ?: 0.0) +
                (pipFeeStr.value?.toDoubleOrNull() ?: 0.0) +
                (lapFeeStr.value?.toDoubleOrNull() ?: 0.0)
        totalAmountStr.value = if (total != 0.0) total.toString() else ""
    }

    fun initOnCreated(intent: Intent) {
        val jsonData = intent.getStringExtra(Constant.Key.DATA) ?: ""
        if (jsonData.isNotEmpty()) {
            try {
                val bean = Gson().fromJson(jsonData, IntImpPickUpRecordBean::class.java)
                dataBean.value = bean
                // 初始化可编辑费用字段
                tranChargeStr.value = if (bean.tranCharge != 0.0) bean.tranCharge.toString() else ""
                whsChargeStr.value = if (bean.whsCharge != 0.0) bean.whsCharge.toString() else ""
                drawBillChargeStr.value = if (bean.drawBillCharge != 0.0) bean.drawBillCharge.toString() else ""
                svlChargeStr.value = if (bean.svlCharge != 0.0) bean.svlCharge.toString() else ""
                tallyChargeStr.value = if (bean.tallyCharge != 0.0) bean.tallyCharge.toString() else ""
                pipFeeStr.value = if (bean.pipFee != 0.0) bean.pipFee.toString() else ""
                lapFeeStr.value = if (bean.lapFee != 0.0) bean.lapFee.toString() else ""

                // 注册总费用实时计算
                tranChargeStr.observeForever(totalCalculator)
                whsChargeStr.observeForever(totalCalculator)
                drawBillChargeStr.observeForever(totalCalculator)
                svlChargeStr.observeForever(totalCalculator)
                tallyChargeStr.observeForever(totalCalculator)
                pipFeeStr.observeForever(totalCalculator)
                lapFeeStr.observeForever(totalCalculator)

                // 初始计算一次
                calculateTotal()
            } catch (e: Exception) {
                showToast("数据解析失败")
                getTopActivity().finish()
            }
        } else {
            showToast("未接收到数据")
            getTopActivity().finish()
        }
    }

    /**
     * 保存修改
     */
    fun submit() {
        val bean = dataBean.value ?: return

        // 同步可编辑费用字段回 bean
        bean.tranCharge = tranChargeStr.value?.toDoubleOrNull() ?: 0.0
        bean.whsCharge = whsChargeStr.value?.toDoubleOrNull() ?: 0.0
        bean.drawBillCharge = drawBillChargeStr.value?.toDoubleOrNull() ?: 0.0
        bean.svlCharge = svlChargeStr.value?.toDoubleOrNull() ?: 0.0
        bean.tallyCharge = tallyChargeStr.value?.toDoubleOrNull() ?: 0.0
        bean.pipFee = pipFeeStr.value?.toDoubleOrNull() ?: 0.0
        bean.lapFee = lapFeeStr.value?.toDoubleOrNull() ?: 0.0
        bean.amount = totalAmountStr.value?.toDoubleOrNull() ?: 0.0

        launchLoadingCollect({
            NetApply.api.modifyIntImpPickUpCharge(bean.toRequestBody())
        }) {
            onSuccess = {
                showToast("修改成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                getTopActivity().finish()
            }
        }
    }

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

    override fun onCleared() {
        super.onCleared()
        tranChargeStr.removeObserver(totalCalculator)
        whsChargeStr.removeObserver(totalCalculator)
        drawBillChargeStr.removeObserver(totalCalculator)
        svlChargeStr.removeObserver(totalCalculator)
        tallyChargeStr.removeObserver(totalCalculator)
        pipFeeStr.removeObserver(totalCalculator)
        lapFeeStr.removeObserver(totalCalculator)
    }
}
