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

import androidx.fragment.app.FragmentContainerView
import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.frame.mvvm.viewmodel.activityViewModels
import com.adealink.frame.mvvm.viewmodel.viewModels
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.im.session.comp.fragment.OrderTopBarFragment
import com.adealink.weparty.im.session.comp.viewmodel.SessionOrderTopViewModel
import com.adealink.weparty.im.session.mesasge.PlaymateOrderMessageBean
import com.adealink.weparty.im.session.viewmodel.SessionViewModel
import com.adealink.weparty.module.order.data.OrderDetailInfo
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo

class SessionOrderTopBarComp(
    lifecycleOwner: LifecycleOwner,
    val topBar: FragmentContainerView,
    val chatInfo: ChatInfo?
) : ViewComponent(lifecycleOwner) {

    private val orderTopViewModel by activityViewModels<SessionOrderTopViewModel>()
    private val topFragment by fastLazy { OrderTopBarFragment() }

    private val sessionViewModel by viewModels<SessionViewModel>()

    override fun onCreate() {
        super.onCreate()
        initView()
        observeViewModel()
        loadData()
    }

    override fun onResume() {
        super.onResume()
        orderTopViewModel.loadTopInfo()
    }

    private fun initView() {
        fragmentManager.beginTransaction()
            .replace(topBar.id, topFragment, "OrderTopBarFragment")
            .commitAllowingStateLoss()
    }

    private fun loadData() {
        orderTopViewModel.setChatInfo(chatInfo)
    }

    private fun observeViewModel() {
        orderTopViewModel.topInfoLD.observe(viewLifecycleOwner) {
            if (it == null
                || (it.pendingOrder == null && it.skillList.isNullOrEmpty())
            ) {
                topBar.gone()
                return@observe
            }
            topBar.show()
        }

        sessionViewModel.onRecvNewMessageLD.observeWithoutCache(viewLifecycleOwner) {
            if (it is PlaymateOrderMessageBean) {
                val order = it.data ?: return@observeWithoutCache
                onReceiveOder(order)
            }
        }
    }

    private fun onReceiveOder(order: OrderDetailInfo) {
        orderTopViewModel.onReceiveOder(order)
    }

}