package com.aiosman.ravenow.ui.index.tabs.moment

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
// import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentLoader
import com.aiosman.ravenow.entity.MomentLoaderExtraArgs
import com.aiosman.ravenow.entity.MomentServiceImpl
import com.aiosman.ravenow.event.FollowChangeEvent
import com.aiosman.ravenow.event.MomentAddEvent
import com.aiosman.ravenow.event.MomentFavouriteChangeEvent
import com.aiosman.ravenow.event.MomentLikeChangeEvent
import com.aiosman.ravenow.event.MomentRemoveEvent
import com.aiosman.ravenow.ui.follower.FollowerNoticeViewModel
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

open class BaseMomentModel :ViewModel(){
    private val momentService: MomentService = MomentServiceImpl()
    private val userService = UserServiceImpl()


    val momentLoader = MomentLoader().apply {
        onListChanged = {
            // 使用新实例触发 Compose 重组
            moments = it.toList()
        }
    }
    var refreshing by mutableStateOf(false)
    var isFirstLoad = true
    var moments by mutableStateOf<List<MomentEntity>>(listOf())
    open fun extraArgs(): MomentLoaderExtraArgs {
        return MomentLoaderExtraArgs()
    }
    fun refreshPager(pullRefresh: Boolean = false) {
        if (!isFirstLoad && !pullRefresh) {
            return
        }
        isFirstLoad = false
        momentLoader.clear()
        viewModelScope.launch {
            momentLoader.loadData(extraArgs())
        }
    }

    fun loadMore() {
        viewModelScope.launch {
            momentLoader.loadMore(extraArgs())
            // 使用新实例触发 Compose 重组
            moments = momentLoader.list.toList()
        }
    }


    @Subscribe
    fun onMomentLikeChangeEvent(event: MomentLikeChangeEvent) {
        momentLoader.updateMomentLike(event.postId, event.isLike)
    }
    suspend fun likeMoment(id: Int) {
        momentService.likeMoment(id)
        momentLoader.updateMomentLike(id, true)
    }
    suspend fun dislikeMoment(id: Int) {
        momentService.dislikeMoment(id)
        momentLoader.updateMomentLike(id, false)
    }


    fun onAddComment(id: Int) {
        momentLoader.updateCommentCount(id, +1)
    }

    fun onDeleteComment(id: Int) {
        momentLoader.updateCommentCount(id, -1)
    }



    @Subscribe
    fun onMomentFavoriteChangeEvent(event: MomentFavouriteChangeEvent) {
        momentLoader.updateFavoriteCount(event.postId, event.isFavourite)
    }

    suspend fun favoriteMoment(id: Int) {
        momentService.favoriteMoment(id)
        momentLoader.updateFavoriteCount(id, true)
    }


    suspend fun unfavoriteMoment(id: Int) {
        momentService.unfavoriteMoment(id)
        momentLoader.updateFavoriteCount(id, false)

    }

    @Subscribe
    fun onRemoveMomentEvent(event: MomentRemoveEvent) {
        momentLoader.removeMoment(event.postId)
    }

    @Subscribe
    fun onAddMomentEvent(event: MomentAddEvent) {
        momentLoader.addMoment(event.moment)
    }

    @Subscribe
    fun onFollowChangeEvent(event: FollowChangeEvent) {
        momentLoader.updateFollowStatus(event.userId, event.isFollow)
    }


    fun followAction(moment: MomentEntity) {
        viewModelScope.launch {
            try {
                if (moment.followStatus) {
                    userService.unFollowUser(moment.authorId.toString())
                    EventBus.getDefault().post(FollowChangeEvent(moment.authorId, false))
                } else {
                    // 调用 FollowerNoticeViewModel.followUser() 实现与 FollowerNotice.kt 相同的效果
                    // 该方法内部会调用 userService.followUser() 并发布 FollowChangeEvent 事件
                    FollowerNoticeViewModel.followUser(moment.authorId)
                }
            }  catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun ResetModel() {
        momentLoader.clear()
        isFirstLoad = true
    }

    override fun onCleared() {
        super.onCleared()
        EventBus.getDefault().unregister(this)
    }
}