package com.narutohuo.xindazhou.user.ui.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.narutohuo.xindazhou.common.socketio.SocketIOManager
import com.narutohuo.xindazhou.common.socketio.model.SocketIOResponse
import com.narutohuo.xindazhou.common.socketio.model.SocketIOEvent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

/**
 * 用户页面状态
 */
data class UserUiState(
    val isConnected: Boolean = false,
    val logs: List<String> = emptyList()
)

/**
 * 用户ViewModel
 * 
 * 负责管理 SocketIO 连接状态、日志列表、报警消息等业务逻辑
 * 
 * 注意：SocketIOManager 已经在 AppInitializer 中统一初始化
 * 这里只需要订阅消息即可，不需要再调用 initialize()
 */
class UserViewModel(
    application: Application
) : AndroidViewModel(application) {
    
    private val dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
    
    private val _uiState = MutableStateFlow(UserUiState())
    val uiState: StateFlow<UserUiState> = _uiState
    
    private val _alarmMessage = MutableStateFlow<SocketIOResponse?>(null)
    val alarmMessage: SharedFlow<SocketIOResponse?> = _alarmMessage.asSharedFlow()
    
    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: SharedFlow<String?> = _errorMessage.asSharedFlow()
    
    // 订阅任务（用于管理订阅协程，断开连接时可以取消）
    private val subscriptionJobs = mutableListOf<kotlinx.coroutines.Job>()
    
    init {
        // 先初始化连接状态（同步获取当前状态）
        updateConnectionStatus()
        // 然后观察连接状态变化（异步监听）
        observeConnectionState()
    }
    
    /**
     * 开始订阅消息
     * 
     * 注意：SocketIOManager 已经在 AppInitializer 中统一初始化
     * 这里只需要订阅消息即可，如果未连接，subscribe() 会自动处理连接
     */
    fun connect() {
        viewModelScope.launch {
            addLog("开始订阅 SocketIO 消息...")
            
            // 订阅连接状态变化（已经在 observeConnectionState 中设置，这里确保状态同步）
            updateConnectionStatus()
            
            // 订阅车辆报警事件
            // subscribe() 会自动处理连接（如果未连接会调用 checkAndReconnect）
            val alarmJob = launch {
                SocketIOManager.shared.subscribe(SocketIOEvent.VEHICLE_ALARM).collect { response ->
                    handleVehicleAlarm(response)
                }
            }
            subscriptionJobs.add(alarmJob)
            
            // 订阅车辆控制响应
            val controlJob = launch {
                SocketIOManager.shared.subscribe(SocketIOEvent.VEHICLE_CONTROL_RESPONSE).collect { response ->
                    addLog("📥 收到响应: ${response.data}")
                }
            }
            subscriptionJobs.add(controlJob)
            
            addLog("✅ SocketIO 消息订阅已启动（SocketIOManager 已在 AppInitializer 中初始化）")
        }
    }
    
    /**
     * 断开 SocketIO 连接
     */
    fun disconnect() {
        viewModelScope.launch {
            // 取消所有订阅任务
            subscriptionJobs.forEach { it.cancel() }
            subscriptionJobs.clear()
            
            SocketIOManager.shared.disconnect()
            addLog("已断开连接")
            updateConnectionStatus()
        }
    }
    
    /**
     * 发送寻车指令
     */
    fun sendFindVehicleCommand() {
        viewModelScope.launch {
            if (!SocketIOManager.shared.isConnected()) {
                _errorMessage.value = "未连接，请先连接SocketIO"
                return@launch
            }
            
            val data = mapOf(
                "command" to "find_vehicle",
                "vehicleId" to 1
            )
            
            SocketIOManager.shared.emit(SocketIOEvent.VEHICLE_CONTROL, data)
            addLog("📤 发送寻车指令：command=find_vehicle")
        }
    }
    
    /**
     * 处理车辆报警
     */
    private fun handleVehicleAlarm(response: SocketIOResponse) {
        val time = dateFormat.format(Date(response.timestamp))
        addLog("🚨 收到车辆报警！")
        addLog("   时间: $time")
        addLog("   数据: ${response.data}")
        _alarmMessage.value = response
    }
    
    /**
     * 观察连接状态
     */
    private fun observeConnectionState() {
        viewModelScope.launch {
            SocketIOManager.shared.connectionState.collect { isConnected ->
                _uiState.value = _uiState.value.copy(isConnected = isConnected)
            }
        }
    }
    
    /**
     * 更新连接状态
     */
    private fun updateConnectionStatus() {
        _uiState.value = _uiState.value.copy(
            isConnected = SocketIOManager.shared.isConnected()
        )
    }
    
    /**
     * 添加日志
     */
    private fun addLog(message: String) {
        val time = dateFormat.format(Date())
        val logEntry = "[$time] $message"
        _uiState.value = _uiState.value.copy(
            logs = (_uiState.value.logs + logEntry).takeLast(100) // 限制日志数量，最多保留100条
        )
    }
    
    /**
     * 清除错误消息
     */
    fun clearErrorMessage() {
        _errorMessage.value = null
    }
}
