package com.design.mischiefgo.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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainViewModel(application: Application) : AndroidViewModel(application){
    private val repository: DuplicateRepository by lazy {
        val dao = AppDataBase.getDatabase(application).infoDao()
        DuplicateRepository(dao)
    }
    // 使用LiveData暴露状态
    private val _likeItems = MutableLiveData<List<Duplicate>>()
    var likeItems: LiveData<List<Duplicate>> = _likeItems

    private val _customItems = MutableLiveData<List<Duplicate>>()
    val customItems: LiveData<List<Duplicate>> = _customItems

    private val _randomItems = MutableLiveData<List<Duplicate>>()
    val randomItems: LiveData<List<Duplicate>> = _randomItems

    private val _nonCustomCount = MutableLiveData<Int>()
    val nonCustomCount: LiveData<Int> = _nonCustomCount

    // 加载状态
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    // 错误处理
    private val _errorMessage = MutableLiveData<String>()
    val errorMessage: LiveData<String> = _errorMessage

    init {
        loadInitialData()
    }

    // 初始化加载数据
    private fun loadInitialData() {
        loadLikeItems()
        loadCustomItems()
//        loadRandomItems()
    }
    fun debugDatabase() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val duplicate = repository.getAll()
                Log.d("DB_DEBUG", "总记录数: ${duplicate.size}")
                duplicate.take(5).forEach { infoitem ->
                    Log.d("DB_DEBUG", "Paper[${infoitem.id}]: " +
                            "cat=${infoitem.name}, " +
                            "imId=${infoitem.audioUrl}, ")
                }
            } catch (e: Exception) {
                Log.e("DB_DEBUG", "查询失败", e)
            }
        }
    }

    // 加载随机项目
    fun loadRandomItems() {
        _isLoading.value = true
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val items = repository.getMoreEfficient()
                _randomItems.postValue(items)
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to load random items: ${e.message}")
            } finally {
                _isLoading.postValue(false)
            }
        }
    }
    // 显式加载点赞项（可用于手动刷新）
    fun loadLikeItems() {
        _isLoading.postValue(true)
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val likes = repository.getAllLike()
                _likeItems.postValue(likes)
                Log.d("DB_DEBUG", "点赞记录数: ${likes.size}")
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to load like items: ${e.message}")
            } finally {
                _isLoading.postValue(false)
            }
        }
    }
    // 显式加载上传项（可用于手动刷新）
    fun loadCustomItems() {
        _isLoading.postValue(true)
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val customs = repository.getAllCustomization()
                _customItems.postValue(customs)
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to load customs items: ${e.message}")
            } finally {
                _isLoading.postValue(false)
            }
        }
    }

    // 更新点赞状态
    fun updateLikeStatus(name: String, isLike: Boolean) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.updateLikeStatus(name, isLike)
                // 根据需求刷新相应的列表
                if (isLike) {
                    loadLikeItems() // 如果是点赞，刷新点赞列表
                } else {
                    loadLikeItems() // 如果是取消点赞，也刷新点赞列表
                    // 或者如果当前在某个特定页面，也可以刷新该页面的列表
                }
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to update like status: ${e.message}")
            }
        }
    }


    // 检查是否点赞
    fun checkLikeStatus(name: String, callback: (Boolean) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val isLiked = repository.checkLikeExists(name)
                callback(isLiked)
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to check like status: ${e.message}")
                callback(false)
            }
        }
    }
    // 检查是否已存在
    fun checkSaveStatus(name: String, callback: (Boolean) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.d("DB_DEBUG", "检查是否已存在: $name")
                val isSaved = repository.checkNameExists(name)
                Log.d("DB_DEBUG", "是否已存在: $isSaved")
                callback(isSaved)
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to check save status: ${e.message}")
                callback(false)
            }
        }
    }

    // 插入自定义
    fun insertItem(duplicate: Duplicate) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val itemToInsert = duplicate.copy(isCustomization = true)
                repository.insert(itemToInsert)
                loadCustomItems()
                // 依赖数据库观察者自动更新UI
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to insert item: ${e.message}")
            }
        }
    }

    // 删除自定义
    fun deleteItem(duplicate: Duplicate) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.delete(duplicate)
                loadCustomItems()
                loadLikeItems()
                // 依赖数据库观察者自动更新UI
            } catch (e: Exception) {
                _errorMessage.postValue("Failed to delete item: ${e.message}")
            }
        }
    }
    // 清除错误消息
    fun clearErrorMessage() {
        _errorMessage.value = ""
    }
}