package com.lukouguoji.gjc.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.GjcMaWb
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 com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import kotlinx.coroutines.launch

/**
 * 国际出港运单修改 ViewModel
 */
class GjcQueryEditViewModel : BaseViewModel() {

    // 数据Bean
    val dataBean = MutableLiveData(GjcMaWb())

    /**
     * 初始化数据
     */
    fun initOnCreated(intent: Intent) {
        val jsonData = intent.getStringExtra(Constant.Key.DATA) ?: ""
        if (jsonData.isNotEmpty()) {
            try {
                dataBean.value = Gson().fromJson(jsonData, GjcMaWb::class.java)
            } catch (e: Exception) {
                showToast("数据解析失败")
                getTopActivity().finish()
            }
        } else {
            showToast("未接收到数据")
            getTopActivity().finish()
        }
    }

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

        // 字段校验
        if (bean.wbNo.verifyNullOrEmpty("运单号不能为空")) return

        // 调用更新接口
        launchLoadingCollect({
            NetApply.api.updateGjcMaWb(Gson().toJson(bean).toRequestBody())
        }) {
            onSuccess = {
                showToast("修改成功")
                // 发送刷新事件
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                getTopActivity().finish()
            }
        }
    }

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