package com.paperapp.lenscape.element

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.paperapp.lenscape.DApp
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: ElementRepository by lazy {
        val dao = AppDataBase.getDatabase(application).elementDao()
        ElementRepository(dao)
    }

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

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

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

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

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

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

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

    val likeElements: LiveData<List<Element>> get() = repository.getLikes()

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

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

    fun updateElement(paper: Element) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateElement(paper)
        }
    }

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

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

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

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

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

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

            _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: Element) {
        viewModelScope.launch(Dispatchers.IO) {
            val updateElement = paper.copy(isLike = !paper.isLike)
            repository.updateElement(updateElement)
            Log.d("setlike status",updateElement.isLike.toString())
            _isLiked.postValue(updateElement.isLike)
        }
    }
}