package com.aiosman.riderpro

import android.content.Context
import android.content.Intent
import android.icu.util.Calendar
import android.icu.util.TimeZone
import android.util.Log
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UserAuth
import com.aiosman.riderpro.ui.favourite.FavouriteListViewModel
import com.aiosman.riderpro.ui.favourite.FavouriteNoticeViewModel
import com.aiosman.riderpro.ui.follower.FollowerNoticeViewModel
import com.aiosman.riderpro.ui.follower.FollowingListViewModel
import com.aiosman.riderpro.ui.index.IndexViewModel
import com.aiosman.riderpro.ui.index.tabs.message.MessageListViewModel
import com.aiosman.riderpro.ui.index.tabs.moment.MomentViewModel
import com.aiosman.riderpro.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.riderpro.ui.index.tabs.search.DiscoverViewModel
import com.aiosman.riderpro.ui.index.tabs.search.SearchViewModel
import com.aiosman.riderpro.ui.like.LikeNoticeViewModel
import com.aiosman.riderpro.utils.Utils
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMLogListener
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMSDKConfig
import com.tencent.imsdk.v2.V2TIMUserFullInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.coroutines.suspendCoroutine


object AppState {
    var UserId: Int? = null

    suspend fun initWithAccount(scope: CoroutineScope, context: Context) {
        Log.d("AppState", "initWithAccount")
        val accountService: AccountService = AccountServiceImpl()
        // Declare resp outside the try-catch block
        var resp: UserAuth? = null
        // 获取用户认证信息
        // 在 IO 线程池中异步执行 getAccount()
        withContext(Dispatchers.IO) {
            try {
                resp = accountService.getMyAccount()
                // 账户有效 - No need to explicitly set a flag here
            } catch (e: Exception) {
                // 处理异常，例如记录日志、显示错误信息等
                // 账户无效 - resp will remain null
            }
        }

        // 根据 isAccountValidate 的值来决定后续操作
        if (resp != null) {
            AppStore.updateLoginState(true)
            // ... 账户有效时的操作，例如更新用户信息、注册 JPush 等 ...
            // 更新必要的用户信息
            val calendar: Calendar = Calendar.getInstance()
            val tz: TimeZone = calendar.timeZone
            val offsetInMillis: Int = tz.rawOffset
            accountService.updateUserExtra(
                Utils.getCurrentLanguage(),
                // 时区偏移量单位是秒
                offsetInMillis / 1000,
                tz.displayName
            )
            // 设置当前登录用户 ID
            UserId = resp?.id // Access id from the userAuth parameter

            // 初始化 JPushManager
            JPushManager.init(context)

            // 注册 JPush
            Messaging.registerDevice(scope, context)
            // 注册 Trtc
            val config = V2TIMSDKConfig()

            config.logLevel = V2TIMSDKConfig.V2TIM_LOG_INFO

            config.logListener = object : V2TIMLogListener() {
                override fun onLog(logLevel: Int, logContent: String) {
                    Log.d("V2TIMLogListener", logContent)
                }
            }
            val appConfig = accountService.getAppConfig()
            V2TIMManager.getInstance().initSDK(context, appConfig.trtcAppId, config)
            try {
                val sign = accountService.getMyTrtcSign()
                loginToTrtc(sign.userId, sign.sig)
                updateTrtcUserProfile()
                // 登录成功后，启动TrtcService
                context.startService(
                    Intent(context, TrtcService::class.java)
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            // ... 账户无效时的操作 ...
            AppStore.updateLoginState(false)
        }
    }

    suspend fun loginToTrtc(userId: String, userSig: String): Boolean {
        return suspendCoroutine { continuation ->
            V2TIMManager.getInstance().login(userId, userSig, object : V2TIMCallback {
                override fun onError(code: Int, desc: String?) {
                    continuation.resumeWith(Result.failure(Exception("Login failed: $code, $desc")))
                }

                override fun onSuccess() {
                    continuation.resumeWith(Result.success(true))
                }
            })
        }
    }

    suspend fun updateTrtcUserProfile() {
        val accountService: AccountService = AccountServiceImpl()
        val profile = accountService.getMyAccountProfile()
        val info = V2TIMUserFullInfo()
        info.setNickname(profile.nickName)
        info.faceUrl = profile.avatar
        info.selfSignature = profile.bio
        return suspendCoroutine { continuation ->
            V2TIMManager.getInstance().setSelfInfo(info, object : V2TIMCallback {
                override fun onError(code: Int, desc: String?) {
                    continuation.resumeWith(Result.failure(Exception("Update user profile failed: $code, $desc")))
                }

                override fun onSuccess() {
                    continuation.resumeWith(Result.success(Unit))
                }
            })
        }
    }

    fun ReloadAppState(context: Context) {
        // 重置动态列表页面
        MomentViewModel.ResetModel()
        // 重置我的页面
        MyProfileViewModel.ResetModel()
        // 重置发现页面
        DiscoverViewModel.ResetModel()
        // 重置搜索页面
        SearchViewModel.ResetModel()
        // 重置消息页面
        MessageListViewModel.ResetModel()
        // 重置点赞通知页面
        LikeNoticeViewModel.ResetModel()
        // 重置收藏页面
        FavouriteListViewModel.ResetModel()
        // 重置收藏通知页面
        FavouriteNoticeViewModel.ResetModel()
        // 重置粉丝通知页面
        FollowerNoticeViewModel.ResetModel()
        // 重置关注列表页面
        FollowingListViewModel.ResetModel()
        // 重置关注通知页面
        IndexViewModel.ResetModel()
        UserId = null

        // 关闭 TrtcService
        val trtcService = Intent(
            context,
            TrtcService::class.java
        )
        context.stopService(trtcService)
    }
}