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

import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.fastLazy
import com.adealink.frame.dot.NumDot
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.frame.mvvm.viewmodel.activityViewModels
import com.adealink.frame.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.im.R
import com.adealink.weparty.im.databinding.LayoutSessionTopBarBinding
import com.adealink.weparty.im.session.comp.viewmodel.SessionOrderTopViewModel
import com.adealink.weparty.im.session.dialog.SessionSettingDialog
import com.adealink.weparty.module.call.CallModule
import com.adealink.weparty.module.im.dot.messageDot
import com.adealink.weparty.module.order.Order
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserInfo
import com.adealink.weparty.module.profile.data.UserNote
import com.adealink.weparty.module.profile.data.isFollowed
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo
import com.adealink.weparty.R as APP_R

class SessionTopComp(
    lifecycleOwner: LifecycleOwner,
    val topBar: LayoutSessionTopBarBinding,
    val chatInfo: ChatInfo?
) : ViewComponent(lifecycleOwner) {

    private val orderTopViewModel by activityViewModels<SessionOrderTopViewModel>()

    private val profileViewModel by fastLazy { ProfileModule.getProfileViewModel(viewModelStoreOwner) }
    private val followViewModel by fastLazy { ProfileModule.getFollowViewModel(viewModelStoreOwner) }

    private var chatUserInfo: UserInfo? = null
    private var chatUserNote: UserNote? = null

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

    private fun initView() {
        topBar.ivBack.onClick {
            activity?.finish()
        }
        messageDot.dotLD.observe(viewLifecycleOwner) { dot ->
            topBar.tvUnRead.show(dot.show)
            (dot as? NumDot)?.let {
                topBar.tvUnRead.text = if (it.num > 99) "99+" else dot.num.toString()
            }
        }
        topBar.ivAvatar.onClick {
            goProfile()
        }
        topBar.tvUserName.onClick {
            goProfile()
        }
        topBar.tvUserOnline.onClick {
            goProfile()
        }
        topBar.btnFollow.onClick {
            clickFollow()
        }
        topBar.btnSetting.onClick {
            clickSetting()
        }
        topBar.btnCall.onClick {
            clickCall()
        }
    }

    private fun observeViewModel() {
        profileViewModel?.userInfoLD?.observe(viewLifecycleOwner) {
            this@SessionTopComp.chatUserInfo = it
            updateUserInfo()
            updateCallButton()
        }

        profileViewModel?.userNoteLD?.observe(viewLifecycleOwner) {
            this@SessionTopComp.chatUserNote = it
            updateUserInfo()
        }

        chatInfo?.let { chatInfo ->
            ProfileModule.observeUserOnline(chatInfo.id).observe(viewLifecycleOwner) { online ->
                updateUserOnline(online)
            }
        }

        followViewModel?.isFollowLD?.observe(viewLifecycleOwner) {
            val uid = chatInfo?.id ?: return@observe
            updateFollow(it[uid]?.isFollowed() ?: false)
        }
    }

    private fun loadData() {
        val chatInfo = chatInfo ?: return
        chatUserInfo = profileViewModel?.getUserInfoBy(chatInfo.id)
        chatUserNote = profileViewModel?.getUserNoteBy(chatInfo.id)
        updateUserInfo()
    }

    override fun onResume() {
        super.onResume()
        chatInfo?.id?.let { uid ->
            profileViewModel?.pullUserInfoBy(uid, false)
            profileViewModel?.pullUserNoteBy(uid, false)
            profileViewModel?.isUserOnline(uid)?.observe(viewLifecycleOwner) { online ->
                updateUserOnline(online)
            }
            followViewModel?.isFollow(uid)
        }
    }

    private fun updateCallButton() {
        val chatUserInfo = this@SessionTopComp.chatUserInfo
        if (chatUserInfo == null) {
            topBar.btnCall.gone()
            return
        }
        //通话按钮展示条件, 至少有一个陪玩师
        val hasPlaymate =
            chatUserInfo.isPlaymate() || ProfileModule.getMyUserInfo()?.isPlaymate() == true
        topBar.btnCall.show(hasPlaymate)
    }

    private fun updateUserInfo() {
        this@SessionTopComp.chatUserInfo
        val note = this@SessionTopComp.chatUserNote?.note
        topBar.ivAvatar.setImageUrl(chatUserInfo?.avatar)
        if (note.isNullOrEmpty()) {
            topBar.tvUserName.text = chatUserInfo?.getUserNoteName()
        } else {
            topBar.tvUserName.text = note
        }
    }

    private fun updateUserOnline(online: Boolean) {
        if (online) {
            topBar.tvUserOnline.text = getCompatString(APP_R.string.common_online)
        } else {
            topBar.tvUserOnline.text = getCompatString(APP_R.string.common_offline)
        }
    }

    private fun updateFollow(isFollowed: Boolean) {
        if (isFollowed) {
            topBar.btnFollow.gone()
        } else {
            topBar.btnFollow.show()
        }
    }

    private fun goProfile() {
        val uid = chatInfo?.id ?: return
        val act = activity ?: return
        Router.build(act, Profile.UserProfile.PATH)
            .putExtra(Profile.Common.EXTRA_UID, uid)
            .start()
    }

    private fun clickFollow() {
        val uid = chatInfo?.id ?: return
        followViewModel?.follow(uid)?.observe(viewLifecycleOwner) {
            showFailedToast(it)
        }
    }

    private fun clickSetting() {
        SessionSettingDialog()
            .setChatInfo(chatInfo)
            .show(fragmentManager, "SessionSettingDialog")
    }

    private fun clickCall() {
        val otherUid = chatInfo?.id ?: return
        val otherUserInfo = profileViewModel?.userInfoLD?.value
        val topInfo = orderTopViewModel.topInfoLD.value
        if (topInfo == null || topInfo.pendingOrder == null || !topInfo.pendingOrder.isInService()) {
            //当前没有订单
            if (otherUserInfo?.isPlaymate() == true) {
                //对方是陪玩师, 提示需要下单
                Router.getRouterInstance<BottomDialogFragment>(Order.CreateFromCategory.PATH)?.let {
                    it.arguments = Bundle().apply {
                        putString(
                            Order.CreateFromCategory.EXTRA_TITLE,
                            getCompatString(R.string.im_create_order_title)
                        )
                        putString(Order.CreateFromCategory.EXTRA_PLAYMATE_UID, otherUid)
                    }
                    it.show(this@SessionTopComp.fragmentManager)
                }
            } else {
                showToast(getCompatString(R.string.im_call_return_by_no_in_service))
            }
            return
        }
        CallModule.call(otherUid)
    }


}