package com.adealink.weparty.im.list.viewmodel

import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.im.constant.OFFICIAL_UID
import com.adealink.weparty.im.list.adapter.SessionListAdapter
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserConfigType
import com.adealink.weparty.module.profile.data.UserConfigType.Companion.NECESSARY_USER_ATTR_SET
import com.tencent.qcloud.tuikit.tuiconversation.bean.ConversationInfo
import com.tencent.qcloud.tuikit.tuiconversation.presenter.ConversationPresenter
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class SessionListViewModel : BaseViewModel() {

    private var presenter: ConversationPresenter? = null

    private var adapter: SessionListAdapter? = null

    fun setPresenter(presenter: ConversationPresenter?) {
        this.presenter = presenter
    }

    fun setAdapter(adapter: SessionListAdapter) {
        this.adapter = adapter
    }

    fun clearMessage() {
        viewModelScope.launch {
            presenter?.clearAllUnreadMessage()
        }
    }

    fun loadConversationUserInfo(dataSource: List<ConversationInfo?>?) {
        dataSource ?: return
        viewModelScope.launch {
            for (info in dataSource) {
                info ?: continue
            }
            val userIds =
                dataSource.mapNotNull { it?.id }.filter { it != OFFICIAL_UID }.distinct().toSet()

            loadUserInfo(userIds)
            loadUserOnline(userIds)
            loadUserNote(userIds)
        }
    }

    private fun loadUserInfo(uids: Set<String>){
        viewModelScope.launch {
            val userInfoRlt = ProfileModule.getUsersInfoByUid(
                uids, attrSet = setOf(
                    *NECESSARY_USER_ATTR_SET.toTypedArray(),
                    UserConfigType.USER_NOTE
                )
            )
            when (userInfoRlt) {
                is Rlt.Failed -> {

                }
                is Rlt.Success -> {
                    adapter?.onViewNeedRefresh()
                }
            }
        }
    }

    private fun loadUserOnline(uids: Set<String>){
        viewModelScope.launch {
            val userNoteRlt = ProfileModule.isUserOnline(uids)
            when (userNoteRlt) {
                is Rlt.Failed -> {

                }
                is Rlt.Success -> {
                    adapter?.onViewNeedRefresh()
                }
            }
        }
    }

    private fun loadUserNote(uids: Set<String>){
        viewModelScope.launch {
            val userNoteRlt = ProfileModule.getUserNoteBy(uids)
            when (userNoteRlt) {
                is Rlt.Failed -> {

                }
                is Rlt.Success -> {
                    adapter?.onViewNeedRefresh()
                }
            }
        }
    }

}