package com.remax.visualnovel.manager.login

import com.pengxr.modular.eventbus.generated.events.EventDefineOfUserEvents
import com.remax.visualnovel.api.factory.ServiceFactory
import com.remax.visualnovel.entity.response.User
import com.remax.visualnovel.event.model.OnLoginEvent
import com.remax.visualnovel.event.model.tab.MainTab
import com.remax.visualnovel.manager.nim.NimManager
import com.remax.visualnovel.repository.api.MessageRepository
import com.remax.visualnovel.utils.Routers
import com.remax.visualnovel.ui.main.MainActivity
import com.remax.visualnovel.ui.wallet.manager.WalletManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by HJW on 2025/7/11
 */
object LoginManager {

    private val loginInfoSave by lazy {
        LoginInfoSave()
    }

    var user: User? = null
        set(value) {
            loginInfoSave.putUser(value)
            field = value
            WalletManager.refreshWallet()
        }

    var token: String? = null
        set(value) {
            loginInfoSave.putToken(value)
            field = value
        }

    val isLogin: Boolean
        get() = user != null

    val isVip: Boolean
        get() = user?.isMember == true

    fun isMyself(userId: String?): Boolean {
        return isLogin && userId == user?.userId
    }

    fun init() {
        user = loginInfoSave.getUser()
        token = loginInfoSave.getToken()
    }

    /**
     * 退出登录
     */
    fun logout() {
        user = null
        token = null
        EventDefineOfUserEvents.onLoginStatusChanged().post(OnLoginEvent(OnLoginEvent.LOGOUT))
        MainActivity.start(MainTab.TAB_BOOKS)
        NimManager.logout()
    }

    /**
     * 检查登录状态
     */
    fun checkLogin(callback: (() -> Unit)? = null) {
        if (isLogin) {
            callback?.invoke()
        } else {
            // 未登录授权 总是去登录页面
            Routers.navigation(Routers.LOGIN)
        }
    }

    fun putUser(user: User?) {
        this.user = user
    }

    fun putToken(token: String?) {
        this.token = token
    }

    var contactUnreadCount: Int = 0
        set(value) {
            field = value
            EventDefineOfUserEvents.onUserUnReadChanged().post(null)
        }
        get() {
            return field + if (NimManager.isLogin) NimManager.totalUnreadCount else 0
        }

    private val messageRepository by lazy {
        MessageRepository(ServiceFactory.createService())
    }

    fun refreshUnreadCount() {
        CoroutineScope(Dispatchers.Main).launch {
            messageRepository.getMessageStat()
        }
    }
}