package com.aiosman.ravenow.ui.chat

import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.ChatState
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.entity.ChatNotification
import io.openim.android.sdk.enums.ConversationType
import io.openim.android.sdk.models.Message
import kotlinx.coroutines.launch


class ChatViewModel(
    val userId: String,
) : BaseChatViewModel() {
    var userProfile by mutableStateOf<AccountProfileEntity?>(null)
    var chatNotification by mutableStateOf<ChatNotification?>(null)
    override fun init(context: Context) {
        // 获取用户信息
        viewModelScope.launch {
            val resp = userService.getUserProfile(userId)
            userProfile = resp
            myProfile = accountService.getMyAccountProfile()

            RegistListener(context)
            
            // 获取会话信息，然后加载历史消息
            getOneConversation {
                fetchHistoryMessage(context)
            }
            
            // 获取通知信息
            val notiStrategy = ChatState.getStrategyByTargetTrtcId(resp.trtcUserId)
            chatNotification = notiStrategy
        }
    }

    override fun getConversationParams(): Triple<String, Int, Boolean> {
        return Triple(userProfile?.trtcUserId ?: userId, ConversationType.SINGLE_CHAT, true)
    }

    override fun getLogTag(): String {
        return "ChatViewModel"
    }

    override fun handleNewMessage(message: Message, context: Context): Boolean {
        // 只处理当前聊天对象的消息
        val currentChatUserId = userProfile?.trtcUserId
        val currentUserId = com.aiosman.ravenow.AppState.profile?.trtcUserId
        
        if (currentChatUserId != null && currentUserId != null) {
            // 检查消息是否来自当前聊天对象，且不是自己发送的消息
            return (message.sendID == currentChatUserId || message.sendID == currentUserId) && 
                   message.sendID != currentUserId
        }
        return false
    }

    override fun getReceiverInfo(): Pair<String?, String?> {
        return Pair(userProfile?.trtcUserId, null) // (recvID, groupID)
    }

    override fun getMessageAvatar(message: Message): String? {
        return if (message.sendID == com.aiosman.ravenow.AppState.profile?.trtcUserId) {
            myProfile?.avatar
        } else {
            userProfile?.avatar
        }
    }

    suspend fun updateNotificationStrategy(strategy: String) {
        userProfile?.let {
            val result = ChatState.updateChatNotification(it.id, strategy)
            chatNotification = result
        }
    }

    val notificationStrategy get() = chatNotification?.strategy ?: "default"
}