package com.aiosman.ravenow.ui.index.tabs.ai

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.AgentService
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.entity.AgentLoader
import com.aiosman.ravenow.entity.AgentLoaderExtraArgs
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

open class BaseAgentModel :ViewModel(){
   // private val agentService: AgentService = AgentServiceImpl()

    val agentLoader = AgentLoader().apply {
        onListChanged = {
            agentList = it
        }
    }
    var refreshing by mutableStateOf(false)
    var isFirstLoad = true
    var agentList by mutableStateOf<List<AgentEntity>>(listOf())
    
    open fun extraArgs(): AgentLoaderExtraArgs {
        return AgentLoaderExtraArgs()
    }
    
    fun refreshPager(pullRefresh: Boolean = false) {
        if (!isFirstLoad && !pullRefresh) {
            return
        }
        isFirstLoad = false
        agentLoader.clear()
        viewModelScope.launch {
            agentLoader.loadData(extraArgs())
        }
    }

    fun loadMore() {
        viewModelScope.launch {
            agentLoader.loadMore(extraArgs())
            agentList = agentLoader.list
        }
    }

    // 添加智能体到列表顶部，避免重新加载
    fun addAgentToList(agent: AgentEntity) {
        agentList = listOf(agent) + agentList
    }

    fun ResetModel() {
        agentLoader.clear()
        isFirstLoad = true
    }

    override fun onCleared() {
        super.onCleared()
        EventBus.getDefault().unregister(this)
    }
}