package com.lukouguoji.gjc.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjc.fragment.GjcQueryStorageFragment
import com.lukouguoji.gjc.fragment.GjcQueryWarehouseFragment
import com.lukouguoji.gjc.fragment.GjcQueryWaybillFragment
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast

/**
 * 国际出港查询详情-ViewModel
 */
class GjcQueryDetailsViewModel : BaseViewModel() {

    // ==================== 基础数据 ====================
    var maWbId: String = ""  // 运单主键ID

    // ==================== Tab管理 ====================
    val currentTab = MutableLiveData(0)  // 当前Tab索引 (0/1/2)

    // ==================== 详情数据 ====================
    val detailData = MutableLiveData<Map<String, Any>>(emptyMap())

    // 运单信息 (maWb)
    val maWbData = MutableLiveData<Map<String, Any>>(emptyMap())

    // 仓库列表 (warehouseList)
    val warehouseList = MutableLiveData<List<Map<String, Any>>>(emptyList())

    // 库位列表 (storageUseList)
    val storageUseList = MutableLiveData<List<Map<String, Any>>>(emptyList())

    // ==================== Fragment列表 ====================
    val fragmentList by lazy {
        listOf(
            GjcQueryWaybillFragment.newInstance(this),      // 运单信息
            GjcQueryWarehouseFragment.newInstance(this),    // 仓库信息
            GjcQueryStorageFragment.newInstance(this)       // 库位信息
        )
    }

    // ==================== 方法区 ====================

    /**
     * 初始化(从Intent获取maWbId)
     */
    fun initOnCreated(intent: Intent) {
        maWbId = intent.getStringExtra(Constant.Key.ID) ?: ""
    }

    /**
     * Tab点击事件
     */
    fun onTabClick(index: Int) {
        currentTab.value = index
    }

    /**
     * 加载详情数据
     */
    fun loadDetails() {
        if (maWbId.isEmpty()) {
            showToast("运单ID为空")
            return
        }

        val maWbIdValue = maWbId.toLongOrNull()
        if (maWbIdValue == null) {
            showToast("运单ID格式错误")
            return
        }

        launchLoadingCollect({ NetApply.api.getGjcQueryDetails(maWbIdValue) }) {
            onSuccess = { result ->
                val data = result.data ?: emptyMap()
                detailData.value = data

                // 解析 maWb 对象
                @Suppress("UNCHECKED_CAST")
                val maWb = data["maWb"] as? Map<String, Any> ?: emptyMap()

                // 解析 maWbM 对象 (包含海关报文等信息)
                @Suppress("UNCHECKED_CAST")
                val maWbM = data["maWbM"] as? Map<String, Any> ?: emptyMap()

                // 合并 maWb 和 maWbM 的数据，并添加组合字段
                val mergedData = mutableMapOf<String, Any>()
                mergedData.putAll(maWb)
                mergedData.putAll(maWbM)

                // 添加组合字段: wbNo = prefix + no
                val prefix = maWb["prefix"] as? String ?: ""
                val no = maWb["no"] as? String ?: ""
                if (prefix.isNotEmpty() || no.isNotEmpty()) {
                    mergedData["wbNo"] = "$prefix$no"
                }

                // 字段映射: cmdStatus -> customsCommand
                maWbM["cmdStatus"]?.let {
                    mergedData["customsCommand"] = it
                }

                maWbData.value = mergedData

                // 解析 warehouseList 列表
                @Suppress("UNCHECKED_CAST")
                val whList = data["warehouseList"] as? List<Map<String, Any>> ?: emptyList()
                warehouseList.value = whList

                // 解析 storageUseList 列表
                @Suppress("UNCHECKED_CAST")
                val suList = data["storageUseList"] as? List<Map<String, Any>> ?: emptyList()
                storageUseList.value = suList
            }
        }
    }
}
