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.MsgReceivePool
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 IntArrTelegramDetailsViewModel : BaseViewModel() {

    private var fid = ""
    private var msgBean: MsgReceivePool? = null

    // 电报内容（双向绑定）
    val telegramContent = MutableLiveData("")

    // 是否可编辑（未生成时可编辑）
    val isEditable = MutableLiveData(false)

    fun initOnCreated(intent: Intent) {
        fid = intent.getStringExtra("fid") ?: ""
        val json = intent.getStringExtra(Constant.Key.DATA) ?: ""
        if (json.isNotEmpty()) {
            val bean = Gson().fromJson(json, MsgReceivePool::class.java)
            msgBean = bean
            telegramContent.value = bean.teleContent
            isEditable.value = !bean.isGenerated()
        }
    }

    /**
     * 修改报文按钮点击 — 调用报文生成接口
     */
    fun onModifyClick() {
        val bean = msgBean ?: return
        val content = telegramContent.value ?: ""
        if (content.isEmpty()) {
            showToast("报文内容不能为空")
            return
        }

        // 更新报文内容
        bean.teleContent = content

        val requestData = mapOf(
            "fid" to fid.toLongOrNull(),
            "msgList" to listOf(bean)
        ).toRequestBody()

        launchLoadingCollect({ NetApply.api.analyseMsg(requestData) }) {
            onSuccess = {
                showToast("报文生成成功")
                // 更新状态为已生成
                bean.anaStatus = "1"
                isEditable.value = false
                // 通知列表刷新
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
            }
        }
    }
}
