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())

    // ==================== 5.5寸手机版专属（展示用，平板布局不绑定） ====================
    // 入库件数/入库重量 = warehouseList 各批次求和（设计稿「件重信息」区块）
    val inPcTotal = MutableLiveData("--")
    val inWeightTotal = MutableLiveData("--")

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

    // ==================== 5.5寸手机版取值帮助方法（布局绑定用） ====================
    // 表达式里必须把 map（maWbData）作为参数传入，DataBinding 才能追踪依赖并在数据到达后刷新

    /**
     * 从详情 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 的展示值（如 agentName 优先于 agentCode）
     */
    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 (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

                // 手机版「入库件数/入库重量」= 各批次求和（Gson 反序列化数字均为 Double）
                if (whList.isNotEmpty()) {
                    val pcSum = whList.sumOf { (it["pc"] as? Double) ?: 0.0 }
                    val weightSum = whList.sumOf { (it["weight"] as? Double) ?: 0.0 }
                    inPcTotal.value = pcSum.toLong().toString()
                    inWeightTotal.value = weightSum.toString()
                } else {
                    inPcTotal.value = "--"
                    inWeightTotal.value = "--"
                }

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