package com.lukouguoji.gjj.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.lukouguoji.module_base.base.BaseViewModel
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.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 IntImpLoadingListEditViewModel : BaseViewModel() {

    val dataBean = MutableLiveData(GjjManifest())

    // 可编辑数值字段（String 用于双向绑定）
    val location = MutableLiveData("")
    val totalPcStr = MutableLiveData("")
    val pcStr = MutableLiveData("")
    val weightStr = MutableLiveData("")
    val cashWeightStr = MutableLiveData("")

    fun initOnCreated(intent: Intent) {
        val jsonData = intent.getStringExtra(Constant.Key.DATA) ?: ""
        if (jsonData.isNotEmpty()) {
            try {
                val bean = Gson().fromJson(jsonData, GjjManifest::class.java)
                dataBean.value = bean
                // 初始化可编辑字段
                location.value = bean.locationTally
                totalPcStr.value = bean.totalPc.toString()
                pcStr.value = bean.pc.toString()
                weightStr.value = bean.weight.toString()
                cashWeightStr.value = bean.cashWeight.toString()
            } catch (e: Exception) {
                showToast("数据解析失败")
                getTopActivity().finish()
            }
        } else {
            showToast("未接收到数据")
            getTopActivity().finish()
        }
    }

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

        // 同步可编辑字段回 bean
        bean.totalPc = totalPcStr.value?.toLongOrNull() ?: 0
        bean.pc = pcStr.value?.toLongOrNull() ?: 0
        bean.weight = weightStr.value?.toDoubleOrNull() ?: 0.0
        bean.cashWeight = cashWeightStr.value?.toDoubleOrNull() ?: 0.0

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

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