package com.gh.gamecenter.video.detail

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.OrientationHelper
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureListener
import com.gh.common.util.BbsReportHelper
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.LogUtils
import com.gh.common.videolog.VideoRecordUtils
import com.gh.download.DownloadManager
import com.gh.download.cache.ExoCacheManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseLazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.NormalShareEntity
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.eventbus.EBShare
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.vertical_recycler.OnPagerListener
import com.gh.gamecenter.common.view.vertical_recycler.PagerLayoutManager
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.FragmentVideoDetailContainerBinding
import com.gh.gamecenter.entity.MenuItemEntity
import com.gh.gamecenter.entity.VideoEntity
import com.gh.gamecenter.eventbus.EBCommentSuccess
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserViewModel
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.comment.NewCommentFragment
import com.gh.gamecenter.qa.dialog.MoreFunctionPanelDialog
import com.halo.assistant.HaloApp
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import com.lightgame.listeners.OnBackPressedListener
import com.lightgame.utils.AppManager
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VideoDetailContainerFragment : BaseLazyFragment(), OnBackPressedListener {

    private lateinit var mViewModel: VideoDetailContainerViewModel
    private lateinit var mAdapter: VideoAdapter
    private lateinit var mInitialVideoId: String
    private lateinit var mLocation: String
    private lateinit var mUserViewModel: UserViewModel
    private lateinit var mBinding: FragmentVideoDetailContainerBinding

    private var mIsFirstIn = true
    private val mOldList = ArrayList<VideoEntity>()
    private var mLastPosition = -1
    private var mIsHomeVideo = false//是否是视频总入口
    private var mBrowseTimer: Disposable? = null//视频浏览计时器
    private var mBrowseDuration = 0L//浏览总时长
    private var mReferer: String = ""
    private var mToastDisposable: Disposable? = null
    private var mExposureListener: ExposureListener? = null
    val viewPagerLayoutManager = PagerLayoutManager(context, OrientationHelper.VERTICAL)

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            if (::mAdapter.isInitialized) {
                mAdapter.notifyItemByDownload(downloadEntity)
            }
        }
    }

    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout(): View {
        return FragmentVideoDetailContainerBinding.inflate(LayoutInflater.from(requireContext()), null, false).apply {
            mBinding = this
        }.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mInitialVideoId = arguments?.getString(EntranceConsts.KEY_ID) ?: ""
        mLocation = arguments?.getString(EntranceConsts.KEY_LOCATION) ?: ""
        mReferer = arguments?.getString(EntranceConsts.KEY_REFERER) ?: ""

        mUserViewModel = viewModelProviderFromParent(UserViewModel.Factory(HaloApp.getInstance().application))
        mViewModel = viewModelProvider()
        mViewModel.path = arguments?.getString(EntranceConsts.KEY_PATH) ?: ""
        mViewModel.entrance = arguments?.getString(EntranceConsts.KEY_ENTRANCE) ?: ""
        mViewModel.entranceDetail = arguments?.getString(EntranceConsts.KEY_REFERER) ?: ""
        mViewModel.uuid = arguments?.getString(EntranceConsts.KEY_UUID) ?: ""
        mViewModel.gameId = arguments?.getString(EntranceConsts.KEY_GAMEID) ?: ""
        mViewModel.type = arguments?.getString(EntranceConsts.KEY_TYPE) ?: ""
        mViewModel.act = arguments?.getString(EntranceConsts.KEY_ACTIVITY_NAME) ?: ""
        mViewModel.paginationType = arguments?.getString(EntranceConsts.KEY_PAGINATION_TYPE)
            ?: "type"
        mViewModel.fieldId = arguments?.getString(EntranceConsts.KEY_FIELD_ID) ?: ""
        mViewModel.sectionName = arguments?.getString(EntranceConsts.KEY_SECTION_NAME) ?: ""
        mIsHomeVideo = arguments?.getBoolean(EntranceConsts.KEY_IS_HOME_VIDEO) ?: false
        mViewModel.showComment = arguments?.getBoolean(EntranceConsts.KEY_SHOW_COMMENT) ?: false
        mViewModel.location = mLocation
        mViewModel.isHomeVideo = mIsHomeVideo
        mViewModel.isPauseVideo = true

        ClassicsFooter.REFRESH_FOOTER_NOTHING = "没有内容了"
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        mViewModel.setRecyclerView(mBinding.recyclerview)
        initListener()
        if (!mIsHomeVideo) {
            mBinding.toolbar.setNavigationIcon(R.drawable.ic_toolbar_back_white)
            mBinding.toolbar.setNavigationOnClickListener { requireActivity().finish() }
            mBinding.refresh.isEnabled = false
        }
        mBinding.smartRefreshLayout.setNoMoreData(true)
        mBinding.refresh.setProgressViewOffset(
            false,
            0,
            50F.dip2px() + DisplayUtils.getStatusBarHeight(requireContext().resources)
        )

        observeData()

        if (mLocation != VideoDetailContainerViewModel.Location.VIDEO_ATTENTION.value) {
            mViewModel.getVideoDetailList(mInitialVideoId, mLocation, isLoadNext = true)
        }

        mBinding.loginBtn.setOnClickListener {
            CheckLoginUtils.checkLogin(requireContext(), "视频流-关注", null)
        }
    }

    private fun observeData() {
        mViewModel.videoList.observeNonNull(this) {
            hideNetworkErrorView()
            mBinding.recyclerview.visibility = View.VISIBLE
            mBinding.attentionNoDataContainer.visibility = View.GONE
            if (!::mAdapter.isInitialized) {
                mAdapter = VideoAdapter(this, mBinding.recyclerview, mBinding.refresh, mViewModel)
                mExposureListener = ExposureListener(this, mAdapter)
                mBinding.recyclerview.addOnScrollListener(mExposureListener!!)
                mBinding.recyclerview.adapter = mAdapter
                mBinding.recyclerview.layoutManager = viewPagerLayoutManager

//                if (it.isNotEmpty()) {
//                    val isShowSlide = SPUtils.getBoolean(Constants.SP_SHOW_SLIDE_GUIDE)
//                    if (!isShowSlide) {
//                        showSlideGuide()
//                    }
//                }
            }

            mAdapter.videoList = it

            if (mIsFirstIn) {
                mAdapter.isVisible = isSupportVisible
                mViewModel.currentDisplayingVideo = it[mViewModel.startPosition]
                mBinding.recyclerview.scrollToPosition(mViewModel.startPosition)
                LogUtils.uploadVideoStreamingEnter(
                    mViewModel.path,
                    mReferer,
                    mViewModel.currentDisplayingVideo?.id,
                    mViewModel.uuid
                )
                mIsFirstIn = false
            }

            //下拉刷新
            if (mBinding.refresh.isRefreshing) {
                mBinding.refresh.isRefreshing = false
                showRefreshSuccessToast()
                clearPlayerViewInfo(findVisibleVideoViewByPosition())
                ExoCacheManager.cancelAll()
                CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
                mOldList.clear()
            }

            if (mOldList.isNullOrEmpty()) {
                mAdapter.notifyDataSetChanged()
            } else {
                val indexOf = it.indexOf(mOldList.first())

                if (indexOf != 0) {
                    mAdapter.notifyItemRangeInserted(0, indexOf)
                }
            }

            mOldList.clear()
            mOldList.addAll(it)
        }

        mViewModel.networkError.observeNonNull(this) {
            if (it) {
                showNetworkErrorView()
                toast("网络异常")
            }
        }

        mViewModel.noDataError.observeNonNull(this) {
            if (it) {
                if (mLocation == VideoDetailContainerViewModel.Location.VIDEO_ATTENTION.value) {
                    CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
                    mBinding.attentionNoDataContainer.visibility = View.VISIBLE
                    mBinding.attentionNoLoginContainer.visibility = View.GONE
                    mBinding.recyclerview.visibility = View.GONE
                    mBinding.refresh.isRefreshing = false
                    if (::mAdapter.isInitialized) {
                        mAdapter.videoList.clear()
                        mAdapter.notifyDataSetChanged()
                    }
                } else {
                    showNoDataErrorView()
                    toast("内容可能已被删除")
                }
            }
        }

        mViewModel.needToUpdateVideoInfo.observeNonNull(this) {
            findVisibleVideoViewByPosition()?.updateViewDetail(it)
        }
        mViewModel.followVideoInfo.observeNonNull(this) {
            updateAllFollowDatas(it.user.id ?: "", it.me.isFollower)
        }
        mViewModel.refreshFinish.observeNonNull(this) {
            if (it) {
                mBinding.refresh.isRefreshing = false
            }
        }
        mUserViewModel.loginObsUserinfo.observe(requireActivity(), Observer {
            if (mLocation == VideoDetailContainerViewModel.Location.VIDEO_ATTENTION.value) {
                mBinding.refresh.isEnabled = it != null
                if (it != null) {
                    mBinding.attentionNoLoginContainer.visibility = View.GONE
                    mViewModel.getVideoDetailList(mInitialVideoId, mLocation, isLoadNext = false)
                } else {
                    if (::mAdapter.isInitialized) {
                        mBinding.recyclerview.visibility = View.GONE
                        mIsFirstIn = true
                        mViewModel.reset()
                        mAdapter.videoList.clear()
                        mAdapter.notifyDataSetChanged()
                    }
                    mBinding.errorContainer.visibility = View.GONE
                    mBinding.attentionNoLoginContainer.visibility = View.VISIBLE
                    mBinding.attentionNoDataContainer.visibility = View.GONE
                }
            }
        })
    }


    private fun showRefreshSuccessToast() {
        mToastDisposable?.dispose()
        mBinding.toastTv.alpha = 0f
        mBinding.toastTv.animate().alpha(1f).setDuration(200).setStartDelay(150).start()
        mToastDisposable = rxTimer(1) {
            if (it >= 2000) {
                mBinding.toastTv.animate().alpha(0f).setDuration(200).start()
                mToastDisposable?.dispose()
            }
        }
    }

    private fun initListener() {
        // 根据闪退反馈，离开页面一段时间以后，有时候这里的 recyclerview 会为空
        if (mBinding.recyclerview == null) return

        mBinding.recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val (itemHeight, distance) = getDistance()
                if (itemHeight <= 0) return
                val offsetY = distance % itemHeight
                val alpha = 1 - offsetY.toFloat() / itemHeight
                val homeVideoFragment = this@VideoDetailContainerFragment.parentFragment as? HomeVideoFragment
                homeVideoFragment?.let {
                    it.changeAdAlpha(alpha)
                }
            }
        })

        mBinding.refresh.setOnRefreshListener {
            mToastDisposable?.dispose()
            mBinding.toastTv.alpha = 0f
            mIsFirstIn = true
            mViewModel.getVideoDetailList(
                mViewModel.currentDisplayingVideo?.id
                    ?: "", mLocation, isLoadNext = false
            )
            findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("视频流刷新")
        }

        viewPagerLayoutManager.setOnViewPagerListener(object : OnPagerListener {
            override fun onInitComplete() {

            }

            override fun onPageRelease(isNext: Boolean, position: Int) {
                val video = mViewModel.videoList.value?.safelyGetInRelease(position)

                video?.let {
                    ExoCacheManager.cancel(video.url)
                    val titleAndId = StringUtils.combineTwoString(video.title, video.id)
                    video.videoIsMuted = false
                    if (isNext) {
                        MtaHelper.onEvent("视频详情", "下滑", titleAndId)
                        if (position + 1 < mViewModel.videoList.value?.size ?: 0) {
                            LogUtils.uploadVideoStreamingPlaying(
                                "开始播放-下滑",
                                "",
                                mViewModel.path,
                                mViewModel.entranceDetail,
                                mViewModel.videoList.value?.get(position + 1)?.id,
                                mViewModel.uuid,
                                0.0,
                                0,
                                0,
                                "play"
                            )
                        }
                    } else {
                        MtaHelper.onEvent("视频详情", "上滑", titleAndId)
                        if (position - 1 >= 0) {
                            LogUtils.uploadVideoStreamingPlaying(
                                "开始播放-上滑",
                                "",
                                mViewModel.path,
                                mViewModel.entranceDetail,
                                mViewModel.videoList.value?.get(position - 1)?.id,
                                mViewModel.uuid,
                                0.0,
                                0,
                                0,
                                "play"
                            )
                        }
                    }
                    val detailPlayerView =
                        mBinding.recyclerview.findViewHolderForAdapterPosition(position)?.itemView as? DetailPlayerView
                    clearPlayerViewInfo(detailPlayerView)
                }
            }

            override fun onPageSelected(position: Int, isBottom: Boolean) {
                val isNoMoreData =
                    isBottom && mLocation != VideoDetailContainerViewModel.Location.VIDEO_CHOICENESS.value
                mBinding.smartRefreshLayout.isEnableLoadMore = isNoMoreData
                mBinding.smartRefreshLayout.setNoMoreData(isNoMoreData)
//                val isShowClick = SPUtils.getBoolean(Constants.SP_SHOW_CLICK_GUIDE)
//                if (!isShowClick) {
//                    showClickGuide()
//                }
//                var visitCount = SPUtils.getInt(Constants.SP_SHOW_DOUBLE_CLICK_GUIDE, 0)
//                visitCount++
//                if (visitCount == 5) {
//                    showDoubleClickGuide()
//                }
//                SPUtils.setInt(Constants.SP_SHOW_DOUBLE_CLICK_GUIDE, visitCount)
//                SPUtils.setBoolean(Constants.SP_SHOW_SLIDE_GUIDE, true)
//                SPUtils.setBoolean(Constants.SP_SHOW_CLICK_GUIDE, true)

                playVideo()
            }
        })

        mBinding.guideRl.setOnTouchListener { _, _ ->
            mBinding.slideGuideAnimation.cancelAnimation()
            mBinding.guideRl.visibility = View.GONE
            false
        }

    }

    private fun playVideo() {
        val pos = findVisibleItemPosition()
        if (pos == -1) return
        val videoView = findVisibleVideoViewByPosition()
        videoView?.observeVolume(requireActivity() as AppCompatActivity)
        if (isSupportVisible) {
            if (pos + 2 <= mAdapter.videoList.size - 1) {//预加载视频
                ExoCacheManager.preload(mAdapter.videoList[pos + 1].url)
                ExoCacheManager.preload(mAdapter.videoList[pos + 2].url)
                ImageUtils.picasso.load(mAdapter.videoList[pos + 1].getThumb()).fetch()
                ImageUtils.picasso.load(mAdapter.videoList[pos + 2].getThumb()).fetch()
            } else if (pos + 1 <= mAdapter.videoList.size - 1) {
                ExoCacheManager.preload(mAdapter.videoList[pos + 1].url)
                ImageUtils.picasso.load(mAdapter.videoList[pos + 1].getThumb()).fetch()
            }
            if (mLastPosition != pos /*&& videoView?.isInPlayingState != true*/) {
                ExoCacheManager.cancel(mAdapter.videoList[pos].url)
                CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
                videoView?.startButton?.performClick()
                mBaseHandler.postDelayed({
                    videoView?.updateMuteStatus()
                }, 500)
            }
            mLastPosition = pos
            mViewModel.addHistoryRecord(mAdapter.videoList[pos])
            VideoRecordUtils.log(mAdapter.videoList[pos].id)
        }

        mViewModel.videoList.value?.apply {
            if (pos > mViewModel.startPosition) {//向上滑动
                val videoId =
                    if (mLocation == VideoDetailContainerViewModel.Location.VIDEO_CHOICENESS.value || mLocation == VideoDetailContainerViewModel.Location.VIDEO_HOT.value) {
                        mInitialVideoId
                    } else {
                        this[size - 1].id
                    }
                if (pos == size - 5) {//获取下面的视频
                    mViewModel.getVideoDetailList(videoId, mLocation, isLoadNext = true)
                }
                //防止视频流分页获取的数据为空不会触发循环
                if (pos == size - 1 && (mLocation == VideoDetailContainerViewModel.Location.VIDEO_CHOICENESS.value ||
                            mLocation == VideoDetailContainerViewModel.Location.VIDEO_ATTENTION.value)
                ) {
                    mViewModel.getVideoDetailList(videoId, mLocation, isLoadNext = true)
                }
                val homeVideoFragment = this@VideoDetailContainerFragment.parentFragment as? HomeVideoFragment
                homeVideoFragment?.let {
                    it.changePosition(pos)
                }
            } else {//向下滑动
                if (pos == 4) {//获取上面的视频
                    mViewModel.getVideoDetailList(this[0].id, mLocation, isLoadNext = false)
                }
            }

            mViewModel.startPosition = pos
            mViewModel.currentDisplayingVideo = mAdapter.videoList[mViewModel.startPosition]
        }
    }

    //显示滑动引导
    private fun showSlideGuide() {
        mBaseHandler.postDelayed({
            mBinding.guideRl.visibility = View.VISIBLE
            mBinding.guideTitle.text = "上滑查看下一个视频"
            val heightPixels = requireContext().resources.displayMetrics.heightPixels

            val layoutParams = mBinding.slideGuideAnimation.layoutParams as RelativeLayout.LayoutParams
            layoutParams.height = DisplayUtils.dip2px(195f)

            layoutParams.topMargin = heightPixels / 2 - DisplayUtils.dip2px(195f) / 2
            mBinding.slideGuideAnimation.layoutParams = layoutParams

            val guideTitleLayoutParams = mBinding.guideTitle.layoutParams as RelativeLayout.LayoutParams
            guideTitleLayoutParams.topMargin = layoutParams.topMargin + DisplayUtils.dip2px(195f)
            mBinding.guideTitle.gravity = Gravity.CENTER
            mBinding.guideTitle.layoutParams = guideTitleLayoutParams

            mBinding.slideGuideAnimation.setAnimation("lottie/slide_guide.json")
            mBinding.slideGuideAnimation.playAnimation()
            mBinding.slideGuideAnimation.doOnAnimationEnd {
                mBinding.guideRl.visibility = View.GONE
            }
        }, 200)
    }

    //显示点击引导
    private fun showClickGuide() {
        mBaseHandler.postDelayed({
            val pos = findVisibleItemPosition()
            if (pos != mLastPosition) return@postDelayed
            mBinding.guideRl.visibility = View.VISIBLE
            mBinding.guideTitle.text = "点击查看更多视频"
            val gameTitleY = findVisibleVideoViewByPosition()?.getGameTitleY() ?: 0

            val layoutParams = mBinding.slideGuideAnimation.layoutParams as RelativeLayout.LayoutParams
            layoutParams.height = DisplayUtils.dip2px(68f)

            val topMargin = gameTitleY - DisplayUtils.dip2px(68f) / 5
            layoutParams.topMargin = topMargin
            mBinding.slideGuideAnimation.layoutParams = layoutParams

            val guideTitleLayoutParams = mBinding.guideTitle.layoutParams as RelativeLayout.LayoutParams
            val guideTitleBottomMargin = layoutParams.topMargin - DisplayUtils.dip2px(30f)
            guideTitleLayoutParams.topMargin = guideTitleBottomMargin
            mBinding.guideTitle.gravity = Gravity.LEFT
            mBinding.guideTitle.layoutParams = guideTitleLayoutParams

            mBinding.slideGuideAnimation.setAnimation("lottie/click_guide.json")
            mBinding.slideGuideAnimation.playAnimation()
            mBinding.slideGuideAnimation.doOnAnimationEnd {
                mBinding.guideRl.visibility = View.GONE
            }
        }, 200)
    }

    //显示双击点赞引导
    private fun showDoubleClickGuide() {
        mBaseHandler.postDelayed({
            val pos = findVisibleItemPosition()
            if (pos != mLastPosition) return@postDelayed
            mBinding.guideRl.visibility = View.VISIBLE
            mBinding.guideTitle.text = "双击点个赞"
            val heightPixels = requireContext().resources.displayMetrics.heightPixels

            val layoutParams = mBinding.slideGuideAnimation.layoutParams as RelativeLayout.LayoutParams
            layoutParams.height = DisplayUtils.dip2px(68f)

            layoutParams.topMargin = heightPixels / 2 - DisplayUtils.dip2px(68f) / 2
            mBinding.slideGuideAnimation.layoutParams = layoutParams

            val guideTitleLayoutParams = mBinding.guideTitle.layoutParams as RelativeLayout.LayoutParams
            guideTitleLayoutParams.topMargin =
                layoutParams.topMargin + DisplayUtils.dip2px(68f) + DisplayUtils.dip2px(16f)
            mBinding.guideTitle.gravity = Gravity.CENTER
            mBinding.guideTitle.layoutParams = guideTitleLayoutParams

            mBinding.slideGuideAnimation.setAnimation("lottie/double_click_guide.json")
            mBinding.slideGuideAnimation.playAnimation()
            mBinding.slideGuideAnimation.doOnAnimationEnd {
                mBinding.guideRl.visibility = View.GONE
            }

        }, 200)
    }


    //获取RecyclerView滑动距离
    private fun getDistance(): Pair<Int, Int> {
        val position = viewPagerLayoutManager.findFirstVisibleItemPosition()
        val firstVisiableChildView = viewPagerLayoutManager.findViewByPosition(position)
        val itemHeight = firstVisiableChildView?.height ?: 0
        val itemTop = firstVisiableChildView?.top ?: 0
        val iposition = position * itemHeight
        return Pair(itemHeight, iposition - itemTop)
    }

    override fun onFragmentResume() {
        findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("恢复页面")
        DownloadManager.getInstance().addObserver(dataWatcher)
        if (mViewModel.isPauseVideo) {
            val videoView = findVisibleVideoViewByPosition()
            videoView?.run {
                if (videoView.isInPlayingState) {
                    videoView.onVideoResume(false)
                } else {//快速切换视频后再切换页面可能没有播放
                    videoView.startButton?.performClick()
                }
            }
        } else {
            mViewModel.isPauseVideo = true
        }

        if (mIsHomeVideo) {
            postDelayedRunnable({
                //这里设置不兼容低版本MIUI，否则可能导致TextureView被销毁，出现有声音无画面的情况
                DisplayUtils.setLightStatusBar(requireActivity(), false, false)
            }, 100)
        }
        super.onFragmentResume()
        startBrowseTimer()
    }

    override fun onFragmentPause() {
        DownloadManager.getInstance().removeObserver(dataWatcher)
        val videoView = findVisibleVideoViewByPosition()
        videoView?.run {
            videoView.uploadVideoStreamingPlaying("暂停页面")
            if (mViewModel.isPauseVideo) {
                if (videoView.isInPlayingState) {
                    videoView.onVideoPause()
                } else {
                    CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
                }
            }
        } ?: CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
        if (mBinding.slideGuideAnimation.isAnimating) {
            mBinding.slideGuideAnimation.cancelAnimation()
            mBinding.guideRl.visibility = View.GONE
        }
        super.onFragmentPause()
        ExoCacheManager.cancelAll()
        stopBrowseTimer()
    }

    override fun onDestroyView() {
        findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("退出页面")
        CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
        mBaseHandler.postDelayed({
            CustomManager.releaseAllVideos("detail_${mViewModel.uuid}")
        }, 500)
        super.onDestroyView()
        ExoCacheManager.cancelAll()
    }

    fun findVisibleVideoViewByPosition(): DetailPlayerView? {
        // 页面被销毁重建时，旧 fragment 可能会收到 onActivityResult 的 callback ，这时 mBinding 为未初始化状态
        return if (::mBinding.isInitialized) {
            val pos = findVisibleItemPosition()
            val holder = mBinding.recyclerview?.findViewHolderForAdapterPosition(pos)
            holder?.itemView as? DetailPlayerView
        } else {
            null
        }
    }

    private fun findVisibleItemPosition(): Int {
        var pos = viewPagerLayoutManager.findLastCompletelyVisibleItemPosition()
        if (pos == -1) {
            pos = if (viewPagerLayoutManager.isSlideDown) {
                viewPagerLayoutManager.findLastVisibleItemPosition()
            } else {
                viewPagerLayoutManager.findFirstVisibleItemPosition()
            }

        }
        return pos
    }

    private fun showNetworkErrorView() {
        if (!mIsHomeVideo) {
            mBinding.toolbar.setNavigationIcon(R.drawable.ic_bar_back)
        }
        mBinding.errorContainer.visibility = View.VISIBLE
        mBinding.reuseNoConnection.root.visibility = View.VISIBLE
        mBinding.reuseNoConnection.root.setOnClickListener {
            mViewModel.getVideoDetailList(mInitialVideoId, mLocation, isLoadNext = true)
        }
    }

    private fun showNoDataErrorView() {
        if (!mIsHomeVideo) {
            mBinding.toolbar.setNavigationIcon(R.drawable.ic_bar_back)
        }
        mBinding.errorContainer.visibility = View.VISIBLE
        mBinding.reuseNoneData.root.visibility = View.VISIBLE
    }

    private fun hideNetworkErrorView() {
        if (!mIsHomeVideo) {
            mBinding.toolbar.setNavigationIcon(R.drawable.ic_toolbar_back_white)
        }
        mBinding.errorContainer.visibility = View.GONE
        mBinding.reuseNoConnection.root.visibility = View.GONE
    }

    fun showMoreMenuDialog() {
        if (::mViewModel.isInitialized) {
            mViewModel.currentDisplayingVideo?.let { video ->
                val entities = ArrayList<MenuItemEntity>()
                if (!video.me.isVideoFavorite) {
                    entities.add(MenuItemEntity("收藏", R.drawable.icon_function_collect))
                } else {
                    entities.add(MenuItemEntity("取消收藏", R.drawable.icon_function_collected))
                }
                entities.add(MenuItemEntity("投诉", R.drawable.icon_gamedetail_copyright))
                val shareEntity = getShareEntity() ?: return
                MoreFunctionPanelDialog.getMoreDialog(
                    entities,
                    shareEntity.shareTitle,
                    shareEntity,
                    "",
                    tag ?: ""
                ).show(childFragmentManager, MoreFunctionPanelDialog::class.java.name)
            }
        }
    }

    private fun getItemClickCallback(videoEntity: VideoEntity): (menuItem: MenuItemEntity?) -> Unit {
        return {
            val combinedTitleAndId = StringUtils.combineTwoString(videoEntity.gameName, videoEntity.id)
            when (it?.text) {
                "收藏" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        MtaHelper.onEvent("视频详情", "更多-收藏", combinedTitleAndId)
                        findVisibleVideoViewByPosition()?.let { playerView ->
                            playerView.recordMta("更多-收藏")
                            playerView.uploadVideoStreamingPlaying("更多-收藏")
                        }
                        mViewModel.collect()
                    } else {
                        findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("更多-收藏-跳转登录")
                        CheckLoginUtils.checkLogin(context, "(视频详情)") {}
                    }
                }
                "取消收藏" -> {
                    if (UserManager.getInstance().isLoggedIn) {
                        MtaHelper.onEvent("视频详情", "更多-取消收藏", combinedTitleAndId)
                        findVisibleVideoViewByPosition()?.let { playerView ->
                            playerView.recordMta("更多-取消收藏")
                            playerView.uploadVideoStreamingPlaying("更多-取消收藏")
                        }
                        mViewModel.undoCollect()
                    } else {
                        findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("更多-收藏-跳转登录")
                        CheckLoginUtils.checkLogin(context, "(视频详情)") {}
                    }
                }
                "投诉" -> {
                    ifLogin("视频详情") {
                        BbsReportHelper.showReportDialog(videoEntity.id)
                    }
                }
            }
        }
    }

    private fun getShareEntity(): NormalShareEntity? {
        val videoEntity = mViewModel.currentDisplayingVideo
        if (videoEntity != null) {
            return NormalShareEntity(
                id = videoEntity.id,
                shareUrl = requireContext().getString(R.string.share_community_video_url, videoEntity.shortId),
                shareIcon = videoEntity.poster,
                shareTitle = videoEntity.title,
                shareSummary = "@${videoEntity.user.name} 在光环助手发布了游戏小视频，快点开看看吧",
                shareEntrance = ShareUtils.ShareEntrance.video
            )
        }
        return null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            if (requestCode == CommentActivity.REQUEST_CODE) {
                val commentCount = data.getIntExtra(CommentActivity.COMMENT_COUNT, -1)
                if (::mAdapter.isInitialized && commentCount >= 0) {
                    val videoEntity = mAdapter.videoList[mViewModel.startPosition]
                    videoEntity.commentCount = commentCount
                    findVisibleVideoViewByPosition()?.updateViewDetail(videoEntity)

                    if (mViewModel.entrance.contains(EntranceConsts.ENTRANCE_WELCOME)
                        && mViewModel.entrance.countOccurrences("+") <= 1
                    ) {
                        LogUtils.uploadCommentFromWelcomeDialog()
                    }
                }
                findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("关闭评论弹窗")
            } else if (requestCode == MoreFunctionPanelDialog.REQUEST_CODE) {
                mViewModel.currentDisplayingVideo?.let {
                    getItemClickCallback(it).invoke(data.getParcelableExtra(EntranceConsts.KEY_DATA))
                }
            }
        }
    }

    //评论成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(commentSuccess: EBCommentSuccess) {
        findVisibleVideoViewByPosition()?.uploadVideoStreamingPlaying("提交评论")
    }

    //下载被删除事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBDownloadStatus) {
        if ("delete" == status.status && ::mAdapter.isInitialized) {
            mAdapter.notifyItemAndRemoveDownload(status)
        }
    }

    //安装、卸载事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(busFour: EBPackage) {
        val data = mAdapter.getGameEntityByPackage(busFour.packageName)
        for (gameAndPosition in data) {
            if (::mAdapter.isInitialized) {
                mAdapter.notifyItemByDownload(gameAndPosition.position)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBReuse) {
        val videoView = findVisibleVideoViewByPosition()
        //处理打开评论页面，按手机Home键回到桌面，还会听到视频的声音
        if (NewCommentFragment.COMMENT_PAUSE == status.type) {
            val haveMoreElementCount = AppManager.getInstance().haveMoreElementCount(requireActivity())

            if (!HaloApp.getInstance().isRunningForeground || haveMoreElementCount > 1) {
                videoView?.onVideoPause()
            }
        }
        //产品没说回到前台需要继续恢复播放，先注释掉
        /*else if (NewCommentFragment.COMMENT_RESUME == status.type) {
            val activityStack = AppManager.getInstance().activityStack
            var i = activityStack.size - 1
            while (i >= 0) {
                val activity = activityStack[i]
                if (activity is VideoDetailActivity || activity is MainActivity) {
                    if (requireActivity().componentName == activity.componentName) {
                        videoView?.onVideoResume(false)
                    }
                    break
                }
                i--
            }
        }*/
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(follow: EBUserFollow?) {
        if (follow != null) {
            updateAllFollowDatas(follow.userId, follow.isFollow)
        }

    }

    //遍历更新所有数据的中的用户关注状态
    private fun updateAllFollowDatas(userId: String, isFollow: Boolean) {
        mAdapter.videoList.forEachIndexed { index, videoEntity ->
            if (userId == videoEntity.user.id) {
                videoEntity.me.isFollower = isFollow
                val detailPlayerView =
                    mBinding.recyclerview.findViewHolderForAdapterPosition(index)?.itemView as? DetailPlayerView
                if (mViewModel.currentDisplayingVideo == videoEntity) {
                    detailPlayerView?.updateViewDetail(videoEntity)
                } else {
                    mAdapter.notifyItemChanged(index)
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(share: EBShare?) {
        postDelayedRunnable({
            if (share != null && share.shareEntrance == ShareUtils.ShareEntrance.video && isSupportVisible) {
                mViewModel.shareVideoStatistics(mViewModel.currentDisplayingVideo)
                findVisibleVideoViewByPosition()?.removeAnimation()
            }
        }, 200)
    }

    private fun startBrowseTimer() {
        mBrowseTimer?.dispose()
        mBrowseDuration = 0
        mBrowseTimer = countUpTimer(0) {
            mBrowseDuration = it
        }
    }

    private fun stopBrowseTimer() {
        mBrowseTimer?.dispose()
        mBrowseTimer = null
        if (mBrowseDuration == 0L) return
        VideoRecordUtils.uploadVideoRecord(mBrowseDuration / 1000)
        mBrowseTimer?.dispose()
        mBrowseDuration = 0
    }

    private fun clearPlayerViewInfo(detailPlayerView: DetailPlayerView?) {
        detailPlayerView?.repeatPlayCount = 0
        detailPlayerView?.unObserveVolume(requireActivity() as AppCompatActivity)
        detailPlayerView?.removeAnimation()
        detailPlayerView?.watchedContainer?.visibility = View.GONE
    }

    override fun onHandleBackPressed(): Boolean {
        if (::mAdapter.isInitialized) {
            return mAdapter.onBackPressed(findVisibleVideoViewByPosition())
        }
        return false
    }

}