package com.aiosman.ravenow.ui.index.tabs.moment.tabs.hot

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentServiceImpl
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch


object HotMomentViewModel : ViewModel() {
    private val momentService: MomentService = MomentServiceImpl()
    private val _discoverMoments = MutableStateFlow<List<MomentEntity>>(emptyList())
    val discoverMoments = _discoverMoments.asStateFlow()
    
    private val _isLoading = MutableStateFlow(false)
    val isLoading = _isLoading.asStateFlow()
    
    private val _isRefreshing = MutableStateFlow(false)
    val isRefreshing = _isRefreshing.asStateFlow()
    
    private var currentPage = 1
    private var hasMoreData = true
    private val pageSize = 20
    
    fun loadMoments() {
        if (_isLoading.value || !hasMoreData) return
        
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val response = momentService.getMoments(
                    pageNumber = currentPage,
                    trend = true
                )
                
                if (response.list.isNotEmpty()) {
                    if (currentPage == 1) {
                        _discoverMoments.value = response.list
                    } else {
                        _discoverMoments.value = _discoverMoments.value + response.list
                    }
                    currentPage++
                    hasMoreData = response.list.size >= response.pageSize
                } else {
                    hasMoreData = false
                }
            } catch (e: Exception) {
                // 处理错误
                e.printStackTrace()
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    fun refreshMoments() {
        viewModelScope.launch {
            _isRefreshing.value = true
            currentPage = 1
            hasMoreData = true
            try {
                val response = momentService.getMoments(
                    pageNumber = 1,
                    trend = true
                )
                _discoverMoments.value = response.list
                currentPage = 2
                hasMoreData = response.list.size >= response.pageSize
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                _isRefreshing.value = false
            }
        }
    }
    
    fun resetModel() {
        currentPage = 1
        hasMoreData = true
        _discoverMoments.value = emptyList()
        _isLoading.value = false
        _isRefreshing.value = false
    }
}