package com.adealink.weparty.im.session

import android.view.MotionEvent
import android.view.View
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.base.fastLazy
import com.adealink.frame.ext.safeSubList
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.fitSystemWindows
import com.adealink.weparty.commonui.ext.onWindowInsets
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.im.R
import com.adealink.weparty.im.databinding.FragmentOfficialSessionBinding
import com.adealink.weparty.im.session.adapter.SessionAdapter
import com.adealink.weparty.module.im.data.TAG_IM_SESSION
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuicore.TUICore
import com.tencent.qcloud.tuikit.timcommon.bean.TUIMessageBean
import com.tencent.qcloud.tuikit.timcommon.component.interfaces.IUIKitCallback
import com.tencent.qcloud.tuikit.timcommon.interfaces.OnItemClickListener
import com.tencent.qcloud.tuikit.tuichat.TUIChatConstants
import com.tencent.qcloud.tuikit.tuichat.bean.C2CChatInfo
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo
import com.tencent.qcloud.tuikit.tuichat.bean.GroupChatInfo
import com.tencent.qcloud.tuikit.tuichat.component.audio.AudioPlayer
import com.tencent.qcloud.tuikit.tuichat.component.audio.AudioRecorder
import com.tencent.qcloud.tuikit.tuichat.interfaces.OnGestureScrollListener
import com.tencent.qcloud.tuikit.tuichat.presenter.C2CChatPresenter
import com.tencent.qcloud.tuikit.tuichat.presenter.ChatPresenter
import com.tencent.qcloud.tuikit.tuichat.presenter.GroupChatPresenter

class OfficialSessionFragment : BaseFragment(R.layout.fragment_official_session) {

    private var chatInfo: ChatInfo? = null

    private val binding by viewBinding(FragmentOfficialSessionBinding::bind)

    private val sessionAdapter: SessionAdapter by fastLazy { SessionAdapter() }
    private var sessionPresenter: ChatPresenter? = null

    private var scrollDirection = 0

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

    override fun initViews() {
        super.initViews()
        when (chatInfo?.type) {
            ChatInfo.TYPE_C2C -> {
                sessionPresenter = C2CChatPresenter().also {
                    it.initListener()
                    it.chatInfo = chatInfo as C2CChatInfo
                }
            }

            ChatInfo.TYPE_GROUP -> {
                sessionPresenter = GroupChatPresenter().also {
                    it.initListener()
                    it.setGroupInfo(chatInfo as? GroupChatInfo)
                }
            }

            else -> {
                Log.d(TAG_IM_SESSION, "unknown chat info type:${chatInfo?.type}")
            }
        }
        binding.rvMessage.setPresenter(sessionPresenter)
        binding.rvMessage.setAdapter(sessionAdapter)
        sessionAdapter.setOnItemClickListener(onMessageItemClickListener)
        binding.rvMessage.addItemDecoration(VerticalSpaceItemDecoration(8.dp(), 24.dp(), 20.dp()))
        binding.rvMessage.setOnGestureScrollListener(object : OnGestureScrollListener {
            override fun onScroll(
                m1: MotionEvent?,
                m2: MotionEvent?,
                distanceX: Float,
                distanceY: Float
            ) {
                if (distanceY < 0) {
                    scrollDirection = -1
                } else if (distanceY > 0) {
                    scrollDirection = 1
                } else {
                    scrollDirection = 0
                }
            }
        })

        binding.rvMessage.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val linearLayoutManager =
                    binding.rvMessage.layoutManager as LinearLayoutManager? ?: return
                val firstVisiblePosition = linearLayoutManager.findFirstVisibleItemPosition()
                val lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition()
                sendMsgReadReceipt(firstVisiblePosition, lastVisiblePosition)
                notifyMessageDisplayed(firstVisiblePosition, lastVisiblePosition)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (scrollDirection == -1) {
                        if (!binding.rvMessage.canScrollVertically(-1)) {
                            //加载
                            //sessionAdapter.showLoading()
                            loadMessages(TUIChatConstants.GET_MESSAGE_FORWARD)
                        }
                    } else if (scrollDirection == 1) {
                        if (!binding.rvMessage.canScrollVertically(1)) {
                            loadMessages(TUIChatConstants.GET_MESSAGE_BACKWARD)
//                            displayBackToLastMessage(false)
//                            displayBackToNewMessage(false, "", 0)
                            sessionPresenter?.resetCurrentChatUnreadCount()
                        }
                    }
                    scrollDirection = 0

//                    if (binding.rvMessage.isDisplayJumpMessageLayout()) {
//                        displayBackToLastMessage(true)
//                    } else {
//                        displayBackToLastMessage(false)
//                    }
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
//                    hideBackToAtMessages()
                }
            }
        })
        //sessionAdapter.register()
        //对方正在输入中
        ///sessionPresenter.setTypingListener
        sessionPresenter?.setMessageListAdapter(sessionAdapter)
        sessionPresenter?.setMessageRecycleView(binding.rvMessage)

        fitWindow()
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        activity?.window?.fitSystemWindows(false)
        // 内容布局处理键盘
        binding.root.onWindowInsets { view, insets ->
            val ime = insets.getInsets(WindowInsetsCompat.Type.ime())
            val nav = insets.getInsets(WindowInsetsCompat.Type.navigationBars())

            // 键盘显示时使用键盘高度，否则使用导航栏高度
            val bottomInset = if (ime.bottom > 0) ime.bottom else nav.bottom
            view.updatePadding(bottom = bottomInset)
//            binding.svContent.doOnPreDraw {
//                binding.svContent.smoothScrollTo(0, bottomInset)
//            }
            insets
        }
    }

    override fun loadData() {
        super.loadData()
        sessionPresenter?.loadMessage(
            if (chatInfo?.locateMessage == null) {
                TUIChatConstants.GET_MESSAGE_FORWARD
            } else {
                TUIChatConstants.GET_MESSAGE_TWO_WAY
            },
            chatInfo?.locateMessage
        )
    }


    fun loadMessages(lastMessage: TUIMessageBean?, type: Int) {
        sessionPresenter?.loadMessage(type, lastMessage)
    }

    fun loadMessages(type: Int) {
        if (type == TUIChatConstants.GET_MESSAGE_FORWARD) {
            loadMessages(
                sessionAdapter.firstMessageBean,
                type
            )
        } else if (type == TUIChatConstants.GET_MESSAGE_BACKWARD) {
            loadMessages(
                sessionAdapter.lastMessageBean,
                type
            )
        }
    }

    override fun onResume() {
        super.onResume()
        sessionPresenter?.isChatFragmentShow = true
    }

    override fun onPause() {
        super.onPause()
        sessionPresenter?.isChatFragmentShow = false
        AudioPlayer.getInstance().stopPlay()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //收起输入法
        AudioRecorder.cancelRecord()
        AudioPlayer.getInstance().stopPlay()
        sessionPresenter?.markMessageAsRead(chatInfo, false)
    }

    private fun sendMsgReadReceipt(firstPosition: Int, lastPosition: Int) {
        if (sessionPresenter == null) {
            return
        }

        val tuiMessageBeans =
            sessionAdapter.items.safeSubList(firstPosition, lastPosition) as List<TUIMessageBean>
        sessionPresenter?.sendMessageReadReceipt(tuiMessageBeans, object : IUIKitCallback<Void?>() {
            override fun onSuccess(data: Void?) {}

            override fun onError(module: String?, errCode: Int, errMsg: String?) {
//                if (errCode == TUIConstants.BuyingFeature.ERR_SDK_INTERFACE_NOT_SUPPORT) {
//                    showNotSupportDialog()
//                }
            }
        })
    }

    private fun notifyMessageDisplayed(firstPosition: Int, lastPosition: Int) {
        // *******************************

        // *******************************
//        markCallingMsgRead(firstPosition, lastPosition)

        // *******************************
        // *******************************
        if (sessionPresenter == null) {
            return
        }
        for (bean in sessionAdapter.items.safeSubList(firstPosition, lastPosition)) {
            val param: MutableMap<String?, Any?> = HashMap<String?, Any?>()
            param.put(TUIConstants.TUIChat.MESSAGE_BEAN, bean)
            TUICore.notifyEvent(
                TUIConstants.TUIChat.EVENT_KEY_MESSAGE_EVENT,
                TUIConstants.TUIChat.EVENT_SUB_KEY_DISPLAY_MESSAGE_BEAN,
                param
            )
        }
    }

    private val onMessageItemClickListener = object : OnItemClickListener() {
        override fun onMessageLongClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
            onMessageLongClicked(view, messageBean)
        }

        override fun onMessageClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onUserIconClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onUserIconLongClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onReEditRevokeMessage(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onRecallClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onReplyMessageClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onReplyDetailClick(messageBean: TUIMessageBean?) {
            messageBean ?: return
        }

        override fun onSendFailBtnClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onTextSelected(view: View?, position: Int, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }

        override fun onMessageReadStatusClick(view: View?, messageBean: TUIMessageBean?) {
            view ?: return
            messageBean ?: return
        }
    }


    private fun onMessageLongClicked(view: View, message: TUIMessageBean?) {
        //展示长按弹窗
        //chatView.getMessageLayout().showItemPopMenu(message, view)
    }

}