package com.design.zenspace.entity

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.design.zenspace.DApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch

class MainViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: FeatureRepository by lazy {
        val dao = AppDataBase.getDatabase(application).featureDao()
        FeatureRepository(dao)
    }

    // 防抖控制
    private var lastSearchTime = 0L
    private var lastQuery: String? = null
    private val searchDebounceTime = 500L

    // LiveData 统一暴露
    private val _paperResult = MutableLiveData<Feature?>() // id查询结果
    val paperResult: LiveData<Feature?> get() = _paperResult

    private val _classificationList = MutableLiveData<List<Feature>>(emptyList()) // 类别列表
    val classificationList: LiveData<List<Feature>> get() = _classificationList

    private val _coverMap = MutableLiveData<Map<String, List<Feature>>>(emptyMap()) // 封面分类映射
    val coverMap: LiveData<Map<String, List<Feature>>> get() = _coverMap

    private val _loadingState = MutableLiveData(false) // 加载状态
    val loadingState: LiveData<Boolean> get() = _loadingState

    private val _searchList = MutableLiveData<List<Feature>>(emptyList()) // 搜索结果
    val searchList: LiveData<List<Feature>> get() = _searchList

    private val _isLiked = MutableLiveData<Boolean?>() // 是否收藏
    val isLiked: LiveData<Boolean?> get() = _isLiked

    val likeFeatures: LiveData<List<Feature>> get() = repository.getLikes()

    // 添加标题存储
    var currentTitleName: String? = null

    fun debugDatabase() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val feature = repository.allFeature()
                Log.d("DB_DEBUG", "总记录数: ${feature.size}")
                feature.take(5).forEach { paper ->
                    Log.d("DB_DEBUG", "Feature[${paper.id}]: " +
                            "cat=${paper.classificationName}, " +
                            "imId=${paper.imId}, " +
                            "desc=${paper.description.take(10)}...")
                }
            } catch (e: Exception) {
                Log.e("DB_DEBUG", "查询失败", e)
            }
        }
    }

    fun updateFeature(paper: Feature) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateFeature(paper)
        }
    }

    fun getFeatureResult(id: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _paperResult.postValue(repository.getFeatureById(id))
        }
    }

    fun getClassificationList(name: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _classificationList.postValue(repository.getFeatureByClassification(name))
        }
    }

    fun loadAllClassificationCovers() {
        if (_loadingState.value == true) return

        viewModelScope.launch(Dispatchers.IO) {
            _loadingState.postValue(true)
            val classificationList = DApplication.classificationList
            val resultMap = mutableMapOf<String, List<Feature>>()

            val deferredList = classificationList.map { classification ->
                async {
                    try {
                        classification to repository.getClassificationCover(classification)
                    } catch (e: Exception) {
                        Log.e("BatchLoad", "加载分类[$classification]失败: ${e.message}")
                        classification to emptyList<Feature>()
                    }
                }
            }

            deferredList.awaitAll().forEach { (classification, feature) ->
                resultMap[classification] = feature
            }

            _coverMap.postValue(resultMap)
            _loadingState.postValue(false)
            Log.d("BatchLoad", "所有分类封面数据加载完成")
        }
    }

    fun getSearchList(query: String) {
        val currentTime = System.currentTimeMillis()
        if (query == lastQuery && (currentTime - lastSearchTime) < searchDebounceTime) {
            return
        }
        lastQuery = query
        lastSearchTime = currentTime

        viewModelScope.launch(Dispatchers.IO) {
            try {
                _searchList.postValue(repository.searchByKey(query))
            } catch (e: Exception) {
                _searchList.postValue(emptyList())
                Log.e("Search", "Search failed", e)
            }
        }
    }

    fun checkLike(id: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _isLiked.postValue(repository.isLike(id))
        }
    }

    fun setLike(paper: Feature) {
        viewModelScope.launch(Dispatchers.IO) {
            val updateFeature = paper.copy(isLike = !paper.isLike)
            repository.updateFeature(updateFeature)
            Log.d("setlike status",updateFeature.isLike.toString())
            _isLiked.postValue(updateFeature.isLike)
        }
    }
}