package com.aiosman.ravenow.ui.points

import android.util.Log
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.AppStore
import com.aiosman.ravenow.data.PointService
import com.aiosman.ravenow.data.api.PointsChangeLog
import kotlinx.coroutines.launch

object PointsViewModel : ViewModel() {
    val balance = PointService.pointsBalance
    var logs by mutableStateOf<List<PointsChangeLog>>(emptyList())
    var page by mutableStateOf(1)
    var hasNext by mutableStateOf(true)
    var loading by mutableStateOf(false)

    fun initLoad() {
        if (loading) return
        viewModelScope.launch {
            try {
                loading = true
                // 并行预加载积分定价表和群聊人数限制（不影响UI）
                launch {
                    try {
                        PointService.refreshPointsRules()
                        PointService.refreshRoomMaxMembers()
                    } catch (e: Exception) {
                        Log.e("PointsViewModel", "refresh rules error", e)
                    }
                }
                if (!AppStore.isGuest) {
                    PointService.refreshMyPointsBalance()
                }
                val r = PointService.getMyPointsChangeLogs(page = 1, pageSize = 20)
                logs = r.list
                hasNext = (r.page * r.pageSize) < r.total
                page = r.page + 1
            } catch (e: Exception) {
                Log.e("PointsViewModel", "initLoad error", e)
            } finally {
                loading = false
            }
        }
    }

    fun loadMore() {
        if (!hasNext || loading) return
        viewModelScope.launch {
            try {
                loading = true
                val r = PointService.getMyPointsChangeLogs(page = page, pageSize = 20)
                logs = logs + r.list
                hasNext = (r.page * r.pageSize) < r.total
                page = r.page + 1
            } catch (e: Exception) {
                Log.e("PointsViewModel", "loadMore error", e)
            } finally {
                loading = false
            }
        }
    }
}


