package com.lukouguoji.gjj.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.fragment.IntImpQueryStorageFragment
import com.lukouguoji.gjj.fragment.IntImpQueryWarehouseFragment
import com.lukouguoji.gjj.fragment.IntImpQueryWaybillFragment
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody

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

    // ==================== 基础数据 ====================
    var prefix: String = ""  // 运单号前缀
    var no: String = ""      // 运单号主体

    // ==================== 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(
            IntImpQueryWaybillFragment.newInstance(this),      // 运单信息
            IntImpQueryWarehouseFragment.newInstance(this),    // 仓库信息
            IntImpQueryStorageFragment.newInstance(this)       // 库位信息
        )
    }

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

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

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

    // ==================== 5.5寸手机版取值帮助（与出港 GjcQueryDetailsViewModel 同口径） ====================

    /**
     * 从详情 Map 取字符串展示值；数字自动去掉无意义的 .0；空值兜底 "--"
     */
    fun str(map: Map<String, Any>?, key: String): String {
        val v = map?.get(key) ?: return "--"
        val s = when (v) {
            is Double -> if (v % 1.0 == 0.0) v.toLong().toString() else v.toString()
            else -> v.toString()
        }
        return s.ifBlank { "--" }
    }

    /**
     * 依次取第一个非空 key 的展示值（如 by1 优先于 by0）
     */
    fun strOr(map: Map<String, Any>?, key: String, fallbackKey: String): String {
        val first = str(map, key)
        return if (first != "--") first else str(map, fallbackKey)
    }

    /**
     * 取重量类数值（保留小数形式），空值兜底 "--"
     */
    fun dec(map: Map<String, Any>?, key: String): String {
        val v = map?.get(key) ?: return "--"
        return when (v) {
            is Double -> v.toString()
            else -> v.toString().ifBlank { "--" }
        }
    }

    /**
     * 加载详情数据
     */
    fun loadDetails() {
        if (prefix.isEmpty() || no.isEmpty()) {
            showToast("运单号参数为空")
            return
        }

        val params = mapOf("prefix" to prefix, "no" to no).toRequestBody()

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

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

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

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

                // 锁定状态转中文
                val lockState = maWb["lockState"]
                if (lockState != null) {
                    val lockStateInt = when (lockState) {
                        is Double -> lockState.toInt()
                        is Int -> lockState
                        else -> null
                    }
                    mergedData["lockStateText"] = when (lockStateInt) {
                        0 -> "未锁定"
                        1 -> "已锁定"
                        else -> ""
                    }
                }

                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
            }
        }
    }
}
