package com.example.myapplication.ui.shop

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.themeStyle
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class ShopViewModel : ViewModel() {

    // styleId -> list
    private val _styleData = MutableStateFlow<Map<Int, List<themeStyle>>>(emptyMap())
    val styleData: StateFlow<Map<Int, List<themeStyle>>> = _styleData

    private val inFlight = mutableSetOf<Int>()

    fun getCached(styleId: Int): List<themeStyle> = _styleData.value[styleId].orEmpty()

    fun loadStyleIfNeeded(styleId: Int) {
        if (_styleData.value.containsKey(styleId)) return
        if (!inFlight.add(styleId)) return

        viewModelScope.launch {
            try {
                val resp = RetrofitClient.apiService.themeListByStyle(styleId)
                val list = resp.data ?: emptyList()
                _styleData.update { old -> old + (styleId to list) }
                Log.d("1314520-ShopVM", "style=$styleId size=${list.size}")
            } catch (e: Exception) {
                Log.e("1314520-ShopVM", "按风格查询主题失败", e)
            } finally {
                inFlight.remove(styleId)
            }
        }
    }

    /**
     * 清除缓存数据，用于下拉刷新
     */
    fun clearCache() {
        // 使用 update 方法确保触发数据流更新
        _styleData.update { emptyMap() }
        inFlight.clear()
        Log.d("1314520-ShopVM", "缓存已清除")
    }

    /**
     * 强制重新加载指定风格的数据，忽略缓存
     */
    fun forceLoadStyle(styleId: Int) {
        // 清除该 styleId 的 inFlight 状态，确保可以重新加载
        inFlight.remove(styleId)
        
        viewModelScope.launch {
            try {
                val resp = RetrofitClient.apiService.themeListByStyle(styleId)
                val list = resp.data ?: emptyList()
                _styleData.update { old -> old + (styleId to list) }
                Log.d("1314520-ShopVM", "强制重新加载 style=$styleId size=${list.size}")
            } catch (e: Exception) {
                Log.e("1314520-ShopVM", "强制重新加载主题失败", e)
            } finally {
                inFlight.remove(styleId)
            }
        }
    }
}
