package com.adealink.weparty.im.session.comp.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.module.order.OrderModule
import com.adealink.weparty.module.order.data.OrderDetailInfo
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserPlaymateSkill
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo
import kotlinx.coroutines.async
import kotlinx.coroutines.launch


data class SessionTopData(
    val skillList: List<UserPlaymateSkill>? = null,
    val pendingOrder: OrderDetailInfo? = null
)

class SessionOrderTopViewModel : BaseViewModel() {

    val topInfoLD = MutableLiveData<SessionTopData>()

    private var chatInfo: ChatInfo? = null

    private var skillList: List<UserPlaymateSkill> = emptyList()
    private var pendingOrder: OrderDetailInfo? = null

    fun setChatInfo(chatInfo: ChatInfo?) {
        this.chatInfo = chatInfo
    }

    fun getChatInfo(): ChatInfo? {
        return chatInfo
    }

    fun loadTopInfo() {
        viewModelScope.launch {
            val uid = chatInfo?.id
            if (uid.isNullOrEmpty()) {
                topInfoLD.send(null)
                return@launch
            }
            val userInfoDef = async { ProfileModule.getUserInfoByUid(uid) }
            val orderDef = async { OrderModule.queryUnCompleteOrder(uid) }
            val userInfo = (userInfoDef.await() as? Rlt.Success)?.data
            val orderInfo = (orderDef.await() as? Rlt.Success)?.data

            notifySessionTopDataUpdate(
                userInfo?.skills ?: emptyList(),
                orderInfo?.firstOrNull()
            )
        }
    }

    fun onReceiveOder(order: OrderDetailInfo) {
        notifySessionTopDataUpdate(
            pendingOrder = order
        )
    }

    private fun notifySessionTopDataUpdate(
        skillList: List<UserPlaymateSkill>? = null,
        pendingOrder: OrderDetailInfo? = null
    ) {
        skillList?.let {
            this@SessionOrderTopViewModel.skillList = it
        }
        this@SessionOrderTopViewModel.pendingOrder = pendingOrder
        topInfoLD.send(
            SessionTopData(
                this@SessionOrderTopViewModel.skillList,
                this@SessionOrderTopViewModel.pendingOrder
            )
        )
    }


}