package com.lukouguoji.aerologic.page.log.detail

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.LogBean
import com.lukouguoji.module_base.bean.StatusLogBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.toRequestBody
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

data class StepInfo(val code: String, val name: String)

class LogDetailViewModel : BaseViewModel() {

    val waybillNo = MutableLiveData("")
    val waybillType = MutableLiveData("")

    val statusLogList = MutableLiveData<List<StatusLogBean>>(emptyList())

    // 流转状态步骤（根据运单类型动态设置）
    val allSteps = MutableLiveData<List<StepInfo>>(emptyList())

    // 操作详情中出现的步骤 code 集合
    val activeStepCodes = MutableLiveData<Set<String>>(emptySet())

    // 最新步骤的 code
    val latestStepCode = MutableLiveData("")

    // 当前完成到哪一步（索引），用于线条着色
    val currentStepIndex = MutableLiveData(-1)

    private var awbType = ""

    // 国际出港步骤（来自 AwbGjcStatus.java）
    private val gjcSteps = listOf(
        StepInfo("1", "预录入"), StepInfo("2", "收运完成"),
        StepInfo("3", "运抵申报"), StepInfo("4", "海关放行"),
        StepInfo("5", "组装完成"), StepInfo("6", "复磅完成"),
        StepInfo("7", "装载申报"), StepInfo("8", "航班关闭"),
        StepInfo("9", "理货申报")
    )

    // 国际进港步骤（来自 AwbGjjStatus.java）
    private val gjjSteps = listOf(
        StepInfo("1", "原始舱单"), StepInfo("2", "分拣理货"),
        StepInfo("3", "理货申报"), StepInfo("4", "海关放行"),
        StepInfo("5", "柜台办结"), StepInfo("6", "提取出库")
    )

    fun initOnCreated(intent: Intent) {
        // 优先从 ARouter 参数获取
        val key = intent.getStringExtra(Constant.Key.KEY) ?: ""
        awbType = intent.getStringExtra(Constant.Key.AWB_TYPE) ?: ""

        // 如果没有 ARouter 参数，尝试从 LogBean 解析
        if (key.isEmpty()) {
            val json = intent.getStringExtra(Constant.Key.DATA) ?: ""
            if (json.isNotEmpty()) {
                val bean = Gson().fromJson(json, LogBean::class.java)
                waybillNo.value = bean.key
                awbType = bean.logType
            }
        } else {
            waybillNo.value = key
        }

        waybillType.value = getAwbTypeName(awbType)
        allSteps.value = if (awbType == "II") gjjSteps else gjcSteps

        if (waybillNo.value?.isNotEmpty() == true) {
            loadStatusList(waybillNo.value!!, awbType)
        }
    }

    private fun loadStatusList(key: String, logType: String) {
        viewModelScope.launch {
            try {
                // 注意：SelfLoginInterceptor 会把裸数组 [...] 包装成 {"data": [...]}
                // 所以 API 返回类型必须是 BaseResultBean，从 .data 取实际列表
                val result = withContext(Dispatchers.IO) {
                    NetApply.api.getLogStatusList(
                        mapOf(
                            "key" to key,
                            "awbType" to logType
                        ).toRequestBody()
                    )
                }

                val list = result.data ?: emptyList()
                statusLogList.value = list

                if (list.isNotEmpty()) {
                    // 提取所有出现的 status code（用 status 字段匹配）
                    val codes = list.mapNotNull { item ->
                        item.status.ifEmpty { null }
                    }.toSet()
                    activeStepCodes.value = codes

                    // 最新节点 = 列表最后一条的 status
                    val latestCode = list.last().status
                    latestStepCode.value = latestCode

                    // 计算最新节点在步骤列表中的索引
                    val steps = allSteps.value ?: emptyList()
                    val index = steps.indexOfFirst { step -> step.code == latestCode }
                    currentStepIndex.value = if (index >= 0) index else -1
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun getAwbTypeName(logType: String): String {
        return when (logType) {
            "CI" -> "国内进港"
            "CO" -> "国内出港"
            "II" -> "国际进港"
            "IO" -> "国际出港"
            else -> logType
        }
    }
}
