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

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.narutohuo.xindazhou.socketio.factory.SocketIORepositoryFactory
import com.narutohuo.xindazhou.socketio.model.SocketIOResponse
import com.narutohuo.xindazhou.socketio.repository.SocketIORepository
import com.narutohuo.xindazhou.common.config.ServerConfigManager
import com.narutohuo.xindazhou.user.datasource.local.TokenManager
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 连接状态、日志列表、报警消息等业务逻辑
 */
class UserViewModel(
    application: Application,
    private val socketIORepository: SocketIORepository
) : 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()
    
    init {
        // 先初始化连接状态（同步获取当前状态）
        updateConnectionStatus()
        // 然后观察连接状态变化（异步监听）
        observeConnectionState()
        // 观察日志消息
        observeLogMessage()
        // 观察车辆控制响应
        observeVehicleControlResponse()
        // 观察车辆报警
        observeVehicleAlarm()
    }
    
    /**
     * 连接 SocketIO
     */
    fun connect() {
        viewModelScope.launch {
            addLog("正在连接SocketIO服务器...")
            val socketUrl = ServerConfigManager.getSocketIOUrl()
            val token = TokenManager.getAccessToken()
            
            if (token.isNullOrEmpty()) {
                val errorMsg = "未登录，无法获取Token"
                addLog(errorMsg)
                _errorMessage.value = errorMsg
                return@launch
            }
            
            socketIORepository.connect(socketUrl, token)
                .onSuccess {
                    addLog("连接请求已发送")
                }
                .onFailure { e ->
                    val errorMsg = "连接失败：${e.message}"
                    addLog(errorMsg)
                    addLog("异常详情：${e.javaClass.simpleName}")
                    _errorMessage.value = errorMsg
                }
        }
    }
    
    /**
     * 断开 SocketIO 连接
     */
    fun disconnect() {
        viewModelScope.launch {
            socketIORepository.disconnect()
                .onSuccess {
                    addLog("已断开连接")
                }
                .onFailure { e ->
                    val errorMsg = "断开连接失败：${e.message}"
                    addLog(errorMsg)
                    _errorMessage.value = errorMsg
                }
            updateConnectionStatus()
        }
    }
    
    /**
     * 发送寻车指令
     */
    fun sendFindVehicleCommand() {
        viewModelScope.launch {
            socketIORepository.sendVehicleControl("find_vehicle", 1L)
                .onSuccess {
                    addLog("📤 发送寻车指令：command=find_vehicle")
                }
                .onFailure { e ->
                    val errorMsg = e.message ?: "发送失败"
                    addLog("错误：$errorMsg")
                    _errorMessage.value = errorMsg
                }
        }
    }
    
    /**
     * 观察连接状态
     */
    private fun observeConnectionState() {
        viewModelScope.launch {
            socketIORepository.connectionState.collect { isConnected ->
                _uiState.value = _uiState.value.copy(isConnected = isConnected)
            }
        }
    }
    
    /**
     * 观察日志消息
     */
    private fun observeLogMessage() {
        viewModelScope.launch {
            socketIORepository.logMessage.collect { message ->
                addLog(message)
            }
        }
    }
    
    /**
     * 观察车辆控制响应
     */
    private fun observeVehicleControlResponse() {
        viewModelScope.launch {
            socketIORepository.vehicleControlResponse.collect { response ->
                // 响应已在 logMessage 中处理，这里可以添加其他业务逻辑
            }
        }
    }
    
    /**
     * 观察车辆报警
     */
    private fun observeVehicleAlarm() {
        viewModelScope.launch {
            socketIORepository.vehicleAlarm.collect { response ->
                val time = dateFormat.format(Date(response.timestamp))
                addLog("   时间: $time")
                _alarmMessage.value = response
            }
        }
    }
    
    /**
     * 更新连接状态
     */
    private fun updateConnectionStatus() {
        _uiState.value = _uiState.value.copy(
            isConnected = socketIORepository.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
        )
    }
    
    /**
     * 清除错误消息
     */
    fun clearErrorMessage() {
        _errorMessage.value = null
    }
}
