package com.gh.gamecenter.qa.video.detail

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import com.ethanhua.skeleton.Skeleton
import com.ethanhua.skeleton.ViewSkeletonScreen
import com.gh.common.browse.ValueBrowseTimer
import com.gh.common.browse.asObserver
import com.gh.common.browse.withLifecycle
import com.gh.common.databind.BindingAdapters
import com.gh.common.exposure.ExposureManager
import com.gh.common.util.BbsReportHelper
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.NewLogUtils
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.download.DownloadManager
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.fragment.BaseLazyTabFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.AdditionalParamsEntity
import com.gh.gamecenter.common.entity.NormalShareEntity
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.mvvm.Resource
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.FragmentForumVideoDetailBinding
import com.gh.gamecenter.entity.ActivityLabelEntity
import com.gh.gamecenter.entity.MenuItemEntity
import com.gh.gamecenter.eventbus.EBDeleteDetail
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.eventbus.EBTopCommunityChanged
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.Permissions
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.forum.home.ForumScrollCalculatorHelper
import com.gh.gamecenter.gamecollection.detail.GameCollectionDetailFragment
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.detail.TopCommunityCategoryDialog
import com.gh.gamecenter.qa.dialog.ChooseActivityDialogFragment
import com.gh.gamecenter.qa.dialog.MoreFunctionPanelDialog
import com.gh.gamecenter.qa.video.detail.comment.VideoCommentFragment
import com.gh.gamecenter.qa.video.detail.desc.VideoDescFragment
import com.gh.gamecenter.qa.video.publish.VideoPublishActivity
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

class ForumVideoDetailFragment : BaseLazyTabFragment() {
    private lateinit var mBinding: FragmentForumVideoDetailBinding
    private lateinit var mViewModel: ForumVideoDetailViewModel
    private var mOrientationUtils: OrientationUtils? = null
    private var mSkeleton: ViewSkeletonScreen? = null
    private var mCommentCountTv: TextView? = null
    private var mMoreMenuItem: MenuItem? = null
    private var mForumVideoEntity: ForumVideoEntity? = null
    private var mVideoId = ""
    private var mBbsId = ""
    private var mTopCommentId = ""
    private var mVideoDescFragment: VideoDescFragment? = null
    private var mVideoCommentFragment: VideoCommentFragment? = null
    private var mIsPortrait = false
    private var mVideoHeight = 0
    private var mLastOffset = 0
    private var sourceEntrance: String = ""
    private lateinit var mBasicExposureSourceList: ArrayList<ExposureSource>

    private val browserTimer = ValueBrowseTimer<Resource<ForumVideoEntity>>()
        .withLifecycle(this)
        .withStart {
            SensorsBridge.trackArticleDetailsBrowsing(
                bbsId = it?.data?.bbs?.id ?: "",
                bbsType = if (it?.data?.bbs?.type == "official_bbs") "综合论坛" else "游戏论坛",
                customerType = it?.data?.user?.auth?.text ?: "",
                gameForumType = it?.data?.bbs?.game?.categoryChinese ?: "",
                activityTag = it?.data?.tagActivityName ?: "",
                articleType = "视频贴",
                articleId = it?.data?.id ?: "",
                sourceEntrance = sourceEntrance
            )
        }
        .withResult { detail, time ->
            SensorsBridge.trackArticleBrowsingDuration(
                bbsId = detail?.data?.bbs?.id ?: "",
                bbsType = if (detail?.data?.bbs?.type == "official_bbs") "综合论坛" else "游戏论坛",
                customerType = detail?.data?.user?.auth?.text ?: "",
                gameForumType = detail?.data?.bbs?.game?.categoryChinese ?: "",
                activityTag = detail?.data?.tagActivityName ?: "",
                articleId = detail?.data?.id ?: "",
                articleType = "视频贴",
                stayLength = time / 1000.0,
                sourceEntrance = sourceEntrance
            )
        }

    private val dataWatcher = object : DataWatcher() {
        override fun onDataChanged(downloadEntity: DownloadEntity) {
            setDownloadButton(mForumVideoEntity?.game)
        }

        override fun onDataInit(downloadEntity: DownloadEntity) {
            onDataChanged(downloadEntity)
        }
    }

    override fun getLayoutId(): Int = 0

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

    override fun initFragmentList(fragments: MutableList<Fragment>) {
        fragments.add(VideoDescFragment().apply {
            arguments = bundleOf(EntranceConsts.KEY_VIDEO_ID to mVideoId)
            mVideoDescFragment = this
        })
        fragments.add(VideoCommentFragment().apply {
            arguments =
                bundleOf(
                    EntranceConsts.KEY_VIDEO_ID to mVideoId,
                    EntranceConsts.KEY_BBS_ID to mBbsId,
                    EntranceConsts.KEY_TOP_COMMENT_ID to mTopCommentId
                )
            mVideoCommentFragment = this
        })
    }

    override fun initTabTitleList(tabTitleList: MutableList<String>) {
        tabTitleList.add("详情")
        tabTitleList.add("评论")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mVideoId = arguments?.getString(EntranceConsts.KEY_VIDEO_ID) ?: ""
        mBbsId = arguments?.getString(EntranceConsts.KEY_BBS_ID) ?: ""
        mTopCommentId = arguments?.getString(EntranceConsts.KEY_TOP_COMMENT_ID) ?: ""
        mBasicExposureSourceList = arguments?.getParcelableArrayList(EntranceConsts.KEY_EXPOSURE_SOURCE_LIST) ?: arrayListOf()
        sourceEntrance = arguments?.getString(EntranceConsts.KEY_SOURCE_ENTRANCE) ?: ""
        super.onCreate(savedInstanceState)
        NewLogUtils.logVideoDetailClick("view_video_detail")
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        mBinding.toolbar.inflateMenu(R.menu.menu_forum_video_detail)
        mMoreMenuItem = mBinding.toolbar.menu.findItem(R.id.menu_more)
        if (!mIsFromTabWrapper) {
            ViewCompat.setOnApplyWindowInsetsListener(mBinding.appbar) { _, insets ->
                (mBinding.toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin =
                    insets.getInsets(WindowInsetsCompat.Type.systemBars()).top
                WindowInsetsCompat.CONSUMED
            }
        }
        if (mIsFromMainWrapper) {
            (mBinding.toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin = DisplayUtils.getStatusBarHeight(requireContext().resources)
        }
        mViewModel = viewModelProviderFromParent(
            ForumVideoDetailViewModel.Factory(
                mVideoId,
                arguments?.getString(EntranceConsts.KEY_RECOMMEND_ID) ?: ""
            )
        )
        mBinding.root.setBackgroundColor(Color.WHITE)
        mSkeleton = Skeleton.bind(mBinding.skeleton)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(com.gh.gamecenter.common.R.color.ui_skeleton_highlight)
            .duration(Constants.SHIMMER_DURATION)
            .maskWidth(Constants.MASK_WIDTH)
            .gradientCenterColorWidth(Constants.GRADIENT_CENTER_COLOR_WIDTH)
            .load(R.layout.fragment_video_detail_skeleton)
            .show()
        mBinding.toolbar.setNavigationOnClickListener { requireActivity().finish() }
        mOrientationUtils = OrientationUtils(requireActivity(), mBinding.topVideoView)
        mOrientationUtils?.isEnable = false

        mBinding.appbar.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            val absVerticalOffset = abs(verticalOffset)
            val total = appBarLayout.totalScrollRange
            if (absVerticalOffset > total / 2) {
                updateToolbarStyle(isToolbarWhite = true)
            } else {
                updateToolbarStyle(isToolbarWhite = false)
            }
            updateVideoViewParams(absVerticalOffset)
        }
        mViewPager.doOnPageSelected {
            if (it == 0) {
                NewLogUtils.logVideoDetailClick("click_detail_tab")
            } else {
                NewLogUtils.logVideoDetailClick("click_comment_tab")
            }
        }

        mMoreMenuItem?.setOnMenuItemClickListener {
            consume {
                mForumVideoEntity?.let {
                    showMoreItemDialog()
                    NewLogUtils.logVideoDetailClick("click_more")
                    NewLogUtils.logShareEnter("视频帖详情页")
                }
            }
        }
        mBinding.reuseNoConnection.root.setOnClickListener {
            mViewModel.getVideoDetail()
            mBinding.reuseNoConnection.root.visibility = View.GONE
            mBinding.reuseLoading.root.visibility = View.VISIBLE
            mBinding.skeletonMask.visibility = View.VISIBLE
            mSkeleton?.show()
        }
        mBinding.replyTv.setOnClickListener {
            mVideoCommentFragment?.startCommentActivity()
        }
        observeData()
    }

    private fun updateVideoViewParams(absVerticalOffset: Int) {
        if (mIsPortrait && mVideoHeight > 0 && mLastOffset != absVerticalOffset) {
            (mBinding.placeView.layoutParams as LinearLayout.LayoutParams).apply {
                height = absVerticalOffset
                mBinding.placeView.layoutParams = this
            }
            (mBinding.topVideoView.layoutParams as ConstraintLayout.LayoutParams).apply {
                height = mVideoHeight - absVerticalOffset
                mBinding.topVideoView.layoutParams = this
            }
            mLastOffset = absVerticalOffset
        }
    }


    override fun onPageSelected(position: Int) {
        mBinding.bottomContainer.goneIf(position != 1)
    }

    private fun observeData() {
        mViewModel.detailLiveData.observeNonNull(this) {
            mSkeleton?.hide()
            mBinding.skeletonMask.visibility = View.GONE
            if (it.status == Status.SUCCESS) {
                val entity = it.data as ForumVideoEntity
                mForumVideoEntity = entity
                mCommentCountTv?.text = entity.count.comment.toString()
                mBinding.topVideoView.setForumVideoEntity(mForumVideoEntity)
                updateVideoParams()
                setUpTopVideo(entity)
                setGameInfo(entity)
                mBinding.container.visibility = View.VISIBLE
                mBinding.reuseNoneData.root.visibility = View.GONE
                mBinding.reuseNoConnection.root.visibility = View.GONE
                if (!mIsPortrait) {
                    (mBinding.collapsingToolbar.layoutParams as AppBarLayout.LayoutParams).apply {
                        scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL
                        mBinding.collapsingToolbar.layoutParams = this
                    }
                    updateToolbarParams(0)
                } else {
                    updateToolbarParams(mVideoHeight / 2)
                    if (arguments?.getInt(PAGE_INDEX) == 1) {
                        mBinding.appbar.setExpanded(false)
                    }
                }
                mViewModel.addHistoryRecord(entity)
            } else {
                mBinding.container.visibility = View.GONE
                if (it.exception != null && it.exception!!.code() == 404) {
                    mBinding.reuseDataException.root.visibility = View.VISIBLE
                } else {
                    mBinding.reuseNoConnection.root.visibility = View.VISIBLE
                }
            }
            mBinding.reuseLoading.root.visibility = View.GONE
        }
        mViewModel.deleteLiveData.observe(viewLifecycleOwner) {
            mForumVideoEntity?.run {
                if (me.isModerator) {
                    if (me.moderatorPermissions.hideVideo == Permissions.REPORTER) {
                        toast("提交成功")
                    } else {
                        ToastUtils.showToast("已隐藏")
                        EventBus.getDefault().post(EBDeleteDetail(mViewModel.videoId))
                    }
                } else {
                    ToastUtils.showToast("已删除")
                    EventBus.getDefault().post(EBDeleteDetail(mViewModel.videoId))
                }
                requireActivity().finish()
            }
        }
        mViewModel.updateDetailLiveData.observeNonNull(this) {
            mForumVideoEntity = it
            mCommentCountTv?.text = it.count.comment.toString()
            setGameInfo(it)
        }
        mViewModel.highlight.observeNonNull(this) { isHighlighted ->
            if (isHighlighted) {
                if (mForumVideoEntity!!.me.moderatorPermissions.highlightVideo == Permissions.REPORTER) {
                    toast("提交成功")
                    mForumVideoEntity?.choicenessStatus = "apply"
                } else {
                    toast("操作成功")
                    mForumVideoEntity?.choicenessStatus = "pass"
                    mViewModel.updateDetailLiveData.postValue(mForumVideoEntity)
                }
            }
        }
        mViewModel.cancelHighlight.observeNonNull(this) {
            if (it) {
                if (mForumVideoEntity!!.me.moderatorPermissions.cancelHighlightVideo == Permissions.REPORTER) {
                    toast("提交成功")
                } else {
                    toast("操作成功")
                    mForumVideoEntity?.choicenessStatus = "cancel"
                    mViewModel.updateDetailLiveData.postValue(mForumVideoEntity)
                }
            }
        }
        mViewModel.applyHighlight.observeNonNull(this) {
            if (it) {
                toast("提交成功")
                mForumVideoEntity?.choicenessStatus = "apply"
            } else {
                toast("提交失败")
            }
        }
        mViewModel.top.observeNonNull(this) { top ->
            val topSuccessToast = if (top) {
                R.string.article_detail_top_success_toast
            } else {
                R.string.article_detail_cancel_top_success_toast
            }
            toast(getString(topSuccessToast))
            mForumVideoEntity?.let {
                EventBus.getDefault().post(
                    EBTopCommunityChanged(
                        it.bbsId
                    )
                )
            }
        }
        mViewModel.detailLiveData.observe(viewLifecycleOwner, browserTimer.asObserver())
    }

    private fun setGameInfo(entity: ForumVideoEntity) {
        val gameEntity = entity.game
        if (gameEntity == null) {
            mBinding.gameInfoContainer.visibility = View.GONE
            return
        }
        mBinding.gameIconView.displayGameIcon(gameEntity)
        mBinding.gameNameTv.text = gameEntity.name
        mBinding.gameScoreTv.text = gameEntity.star.toString()
        BindingAdapters.setVideoDetailGameTags(mBinding.gameTagsContainer, gameEntity)

        val exposureEvent = ExposureEvent.createEventWithSourceConcat(
            gameEntity,
            mBasicExposureSourceList,
            listOf(ExposureSource("其他"), ExposureSource("视频详情"))
        )
        gameEntity.exposureEvent = exposureEvent
        ExposureManager.log(exposureEvent)

        mBinding.gameInfoContainer.setOnClickListener {
            NewLogUtils.logVideoDetailGameClick(
                "click_game",
                gameEntity.id,
                gameEntity.category ?: "",
                mForumVideoEntity?.bbs?.id ?: "",
                mForumVideoEntity?.id ?: "",
                ""
            )
            GameDetailActivity.startGameDetailActivity(
                requireContext(),
                gameEntity,
                "视频详情",
                traceEvent = exposureEvent
            )
        }
        setDownloadButton(gameEntity)
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun updateToolbarParams(margin: Int) {
        (mBinding.toolbar.layoutParams as CollapsingToolbarLayout.LayoutParams).apply {
            bottomMargin = margin
            mBinding.toolbar.layoutParams = this
        }
    }

    private fun updateToolbarStyle(isToolbarWhite: Boolean) {
        if (isToolbarWhite == mViewModel.currentToolbarStatus) return
        mViewModel.currentToolbarStatus = isToolbarWhite

        if (!mIsFromMainWrapper && !mIsFromTabWrapper) {
            mBinding.toolbar.setNavigationIcon(com.gh.gamecenter.common.R.drawable.ic_bar_back_light)
        } else {
            mBinding.toolbar.navigationIcon = null
        }
        mMoreMenuItem?.setIcon(R.drawable.ic_menu_more_light)
        mBinding.toolbar.setBackgroundColor(
            ContextCompat.getColor(
                requireContext(),
                com.gh.gamecenter.common.R.color.transparent
            )
        )
    }

    private fun updateVideoParams() {
        if (mForumVideoEntity == null) return
        val videoInfo = mForumVideoEntity!!.videoInfo
        val ratio = if (videoInfo.width < videoInfo.height) {
            3 / 4f //竖屏
        } else {
            180 / 101f //横屏
        }
        val updateWidth = DisplayUtils.getScreenWidth()
        val updateHeight = updateWidth / ratio
        mIsPortrait = videoInfo.width < videoInfo.height
        mVideoHeight = updateHeight.toInt()
        (mBinding.topVideoView.layoutParams as ConstraintLayout.LayoutParams).apply {
            width = updateWidth
            height = updateHeight.toInt()
            mBinding.topVideoView.layoutParams = this
        }
    }

    private fun setUpTopVideo(entity: ForumVideoEntity) {
        GSYVideoOptionBuilder()
            .setIsTouchWigetFull(false)
            .setIsTouchWiget(false)
            .setRotateViewAuto(false)
            .setShowFullAnimation(false)
            .setSeekRatio(1f)
            .setUrl(entity.url)
            .setCacheWithPlay(true)
            .setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                    mOrientationUtils?.backToProtVideo()
                    mBinding.topVideoView.uploadVideoStreamingPlaying("退出全屏")
                }
            })
            .build(mBinding.topVideoView)

        mBinding.topVideoView.viewModel = mViewModel
        mBinding.topVideoView.updateThumb(entity.poster)

        mBinding.topVideoView.setVideoStatus(entity.status)
        if (entity.status == "pass" && NetworkUtils.isWifiConnected(requireContext())) {
            if (mViewModel.isTopVideoPartlyCached(entity.url)) {
                mBinding.topVideoView.startPlayLogic(isAutoPlay = true)
            } else {
                // 未有缓存时，为避免影响页面加载，延迟自动播放视频
                postDelayedRunnable({
                    if (activity != null && activity?.isFinishing != true) {
                        mBinding.topVideoView.startPlayLogic(isAutoPlay = true)
                    }
                }, GameCollectionDetailFragment.INITIAL_DELAY)
            }
        }

        mBinding.topVideoView.fullscreenButton.setOnClickListener {
            val horizontalVideoView = mBinding.topVideoView.startWindowFullscreen(
                requireContext(),
                true,
                true
            ) as? ForumTopVideoView
            if (horizontalVideoView == null) {
                toastInInternalRelease("全屏失败，请向技术人员提供具体的操作步骤")
                return@setOnClickListener
            }
            mOrientationUtils?.resolveByClick()
            horizontalVideoView.uuid = mBinding.topVideoView.uuid
            horizontalVideoView.viewModel = mViewModel
            horizontalVideoView.setForumVideoEntity(mForumVideoEntity)
            horizontalVideoView.updateThumb(entity.poster)
            horizontalVideoView.violenceUpdateMuteStatus()
            mBinding.topVideoView.uploadVideoStreamingPlaying("开始播放")
            mBinding.topVideoView.uploadVideoStreamingPlaying("点击全屏")
        }

        mBinding.topVideoView.observeVolume(this)
    }

    override fun provideTabView(position: Int, title: String?): View {
        val view = LayoutInflater.from(requireContext())
            .inflate(R.layout.tab_item_forum_video_detail, null)
        val tabTitle = view.findViewById<View>(R.id.tab_title)
        val tabCount = view.findViewById<TextView>(R.id.tab_count)
        if (tabTitle is CheckedTextView) {
            tabTitle.text = title
        }
        if (position == 1) {
            tabCount.visibility = View.VISIBLE
            tabCount.text = "0"
            mCommentCountTv = tabCount
        }
        return view
    }

    private fun setDownloadButton(gameEntity: GameEntity?) {
        if (gameEntity == null) return
        DownloadItemUtils.setOnClickListener(
            requireContext(), mBinding.downloadBtn,
            gameEntity, 0, null,
            mEntrance,
            location = "视频详情",
            traceEvent = gameEntity.exposureEvent,
            clickCallback = {
                NewLogUtils.logVideoDetailGameClick(
                    "click_game_status",
                    gameEntity.id,
                    gameEntity.category ?: "",
                    mForumVideoEntity?.bbs?.id ?: "",
                    mForumVideoEntity?.id ?: "",
                    mBinding.downloadBtn.text.toString()
                )
            },
            refreshCallback = { setDownloadButton(gameEntity) },
            allStateClickCallback = null
        )
        DownloadItemUtils.updateItem(
            requireContext(),
            gameEntity,
            GameViewHolder(mBinding.gameInfoContainer).apply {
                gameDownloadBtn = mBinding.downloadBtn
                gameDownloadTips = mBinding.downloadTipsLottie
                multiVersionDownloadTv = mBinding.multiVersionDownloadTv
            }
        )
    }

    private fun showMoreItemDialog() {
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) || mForumVideoEntity != null) {
            val entities = ArrayList<MenuItemEntity>()
            if (mForumVideoEntity?.user?.id == UserManager.getInstance().userId && !mForumVideoEntity?.me!!.isModerator && mForumVideoEntity?.status == "pass") {
                val isEnable =
                    mForumVideoEntity?.getSimplifyChoicenessStatus() != "pass"
                entities.add(
                    MenuItemEntity(
                        "申请加精", if (isEnable)
                            R.drawable.icon_more_panel_essence else R.drawable.icon_more_panel_essence_unenable,
                        isEnable = isEnable
                    )
                )
            }
            if (mForumVideoEntity?.user?.id == UserManager.getInstance().userId && mForumVideoEntity?.status == "pass") {
                entities.add(MenuItemEntity("修改", R.drawable.icon_more_panel_edit))
            }
            if (mForumVideoEntity?.user?.id != UserManager.getInstance().userId) {
                entities.add(MenuItemEntity("投诉", R.drawable.icon_gamedetail_copyright))
            }
            val moderatorPermissions = mForumVideoEntity?.me?.moderatorPermissions
            if (mForumVideoEntity?.me?.isModerator == true && mForumVideoEntity?.status == "pass") {
                if (mForumVideoEntity?.getSimplifyChoicenessStatus() == "pass") {
                    if ((moderatorPermissions?.cancelHighlightVideo
                            ?: Permissions.GUEST) > Permissions.GUEST
                    ) {
                        entities.add(MenuItemEntity("取消精选", R.drawable.icon_more_panel_essence_cancel))
                    }
                } else {
                    if ((moderatorPermissions?.highlightVideo
                            ?: Permissions.GUEST) > Permissions.GUEST
                    ) {
                        entities.add(MenuItemEntity("加精选", R.drawable.icon_more_panel_essence))
                    }
                }
            }
            if (mForumVideoEntity?.me?.isModerator == true &&
                (moderatorPermissions?.updateVideoActivityTag
                    ?: Permissions.GUEST) > Permissions.GUEST &&
                mForumVideoEntity?.status == "pass"
            ) {
                entities.add(MenuItemEntity("修改活动标签", R.drawable.icon_more_panel_modify_label))
            }
            if (mForumVideoEntity?.me?.isModerator == true &&
                (moderatorPermissions?.hideVideo ?: Permissions.GUEST) > Permissions.GUEST
            ) {
                entities.add(MenuItemEntity("隐藏", R.drawable.icon_more_panel_delete))
            } else {
                if (mForumVideoEntity?.user?.id == UserManager.getInstance().userId) {
                    entities.add(MenuItemEntity("删除", R.drawable.icon_more_panel_delete))
                }
            }

            // 置顶/取消置顶
            if (mForumVideoEntity?.me?.isModerator == true
                && mForumVideoEntity?.me?.isCommunityTop == false
                && (moderatorPermissions?.topVideo ?: Permissions.GUEST) > Permissions.GUEST
            ) {
                entities.add(
                    MenuItemEntity(
                        getString(R.string.article_detail_more_top_title),
                        R.drawable.icon_more_panel_top
                    )
                )
            } else if (mForumVideoEntity?.me?.isModerator == true
                && mForumVideoEntity?.me?.isCommunityTop == true
                && (moderatorPermissions?.cancelTopVideo ?: Permissions.GUEST) > Permissions.GUEST
            ) {
                entities.add(
                    MenuItemEntity(
                        getString(R.string.article_detail_more_cancel_top_title),
                        R.drawable.icon_more_panel_top_cancel
                    )
                )
            }

            MoreFunctionPanelDialog.showMoreDialog(
                requireActivity() as AppCompatActivity,
                entities, mForumVideoEntity?.title ?: "",
                getShareEntity(),
                mForumVideoEntity?.status ?: "",
                tag ?: ""
            )
        }
    }

    private fun getShareEntity(): NormalShareEntity {
        val params = AdditionalParamsEntity().apply {
            contentType = "视频帖"
            contentId = mForumVideoEntity?.id ?: ""
            bbsId = mForumVideoEntity?.bbs?.id ?: ""
            bbsType = mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛"
            customerType = mForumVideoEntity?.user?.auth?.text ?: ""
            activityTagName = mForumVideoEntity?.tagActivityName ?: ""
            gameForumType = mForumVideoEntity?.bbs?.game?.categoryChinese ?: ""
            refUserId = UserManager.getInstance().userId
        }
        return NormalShareEntity(
            id = mForumVideoEntity?.id ?: "",
            shareUrl = requireContext().getString(
                R.string.share_community_video_url,
                mForumVideoEntity?.shortId
            ),
            shareIcon = if (mForumVideoEntity?.poster?.isNotEmpty() == true) {
                mForumVideoEntity?.poster ?: ""
            } else {
                requireContext().getString(R.string.share_ghzs_logo)
            },
            shareTitle = mForumVideoEntity?.title ?: "",
            shareSummary = mForumVideoEntity?.des ?: "",
            shareEntrance = ShareUtils.ShareEntrance.video,
            additionalParams = params
        )
    }

    private fun getItemClickCallback(): (menuItem: MenuItemEntity?) -> Unit {
        return {
            when (it?.text) {
                "修改" -> {
                    startActivityForResult(
                        VideoPublishActivity.getIntent(
                            requireContext(),
                            mForumVideoEntity!!,
                            mEntrance,
                            "视频详情"
                        ), ForumVideoDetailActivity.VIDEO_PATCH_REQUEST
                    )
                    NewLogUtils.logSharePanelClick(
                        "click_modification",
                        mForumVideoEntity?.user?.id ?: "",
                        "视频帖",
                        mForumVideoEntity?.id ?: "",
                        mForumVideoEntity?.bbs?.id ?: "",
                        mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛"
                    )
                }

                "投诉" -> {
                    BbsReportHelper.showReportDialog(mForumVideoEntity?.id ?: "")
                    NewLogUtils.logSharePanelClick(
                        "click_report",
                        mForumVideoEntity?.user?.id ?: "",
                        "视频帖",
                        mForumVideoEntity?.id ?: "",
                        mForumVideoEntity?.bbs?.id ?: "",
                        mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛"
                    )
                }

                "申请加精" -> {
                    if (mForumVideoEntity?.getSimplifyChoicenessStatus() == "apply") {
                        ToastUtils.showToast("申请加精审核中")
                    } else {
                        mViewModel.doApplyHighlightCommunityVideo(mVideoId)
                        NewLogUtils.logSharePanelClick(
                            "click_apply_essence",
                            mForumVideoEntity?.user?.id ?: "",
                            "视频帖",
                            mForumVideoEntity?.id ?: "",
                            mForumVideoEntity?.bbs?.id ?: "",
                            mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛"
                        )
                    }
                }

                "加精选" -> {
                    if (mForumVideoEntity?.getSimplifyChoicenessStatus() == "apply") {
                        ToastUtils.showToast("加精审核中")
                    } else {
                        showHighlightDialog(true)
                        NewLogUtils.logSharePanelClick(
                            "click_essence",
                            mForumVideoEntity?.user?.id ?: "",
                            "视频帖",
                            mForumVideoEntity?.id ?: "",
                            mForumVideoEntity?.bbs?.id ?: "",
                            mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛"
                        )
                    }
                }
                "取消精选" -> {
                    showHighlightDialog(false)
                }
                "修改活动标签" -> {
                    ChooseActivityDialogFragment.show(
                        requireActivity() as AppCompatActivity,
                        ChooseActivityDialogFragment.ActivityLabelLocation.BBS_VIDEO,
                        mForumVideoEntity?.bbs?.id ?: "",
                        mForumVideoEntity?.tagActivityId,
                        tag ?: ""
                    )
                }
                "删除", "隐藏" -> {
                    DialogHelper.showDialog(
                        requireContext(),
                        "提示",
                        "${it.text}视频后，其中的所有评论及回复都将被${it.text}",
                        it.text,
                        "取消",
                        { mViewModel.deleteVideo(mForumVideoEntity?.id ?: "") },
                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                    NewLogUtils.logSharePanelClick(
                        "click_delete",
                              mForumVideoEntity?.user?.id ?: "",
                        "视频帖",
                        mForumVideoEntity?.id ?: "",
                        mForumVideoEntity?.bbs?.id ?: "",
                        mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛"
                    )
                }

                getString(R.string.article_detail_more_top_title) -> {
                    TopCommunityCategoryDialog.show(
                        childFragmentManager
                    ) { category ->
                        mViewModel.topCommunityVideo(category.id)
                    }
                }
                getString(R.string.article_detail_more_cancel_top_title) -> {
                    DialogHelper.showDialog(
                        requireContext(),
                        getString(R.string.article_detail_cancel_top_dialog_title),
                        getString(R.string.article_detail_cancel_top_dialog_hint),
                        getString(R.string.article_detail_cancel_top_dialog_confirm),
                        getString(R.string.article_detail_cancel_top_dialog_cancel),
                        confirmClickCallback = {
                            mViewModel.cancelTopCommunityVideo()

                        },
                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                }
            }
        }
    }

    private fun getChooseSelectCallback(): (entity: ActivityLabelEntity?) -> Unit {
        return { label ->
            showUpdateLabelDialog(label, mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛")
        }
    }

    private fun showUpdateLabelDialog(label: ActivityLabelEntity?, bbsType: String) {
        if (mForumVideoEntity == null) return
        var hintContent = ""
        val permissions = mForumVideoEntity!!.me.moderatorPermissions
        if (permissions.updateVideoActivityTag > Permissions.GUEST) {
            hintContent =
                if (permissions.updateVideoActivityTag == Permissions.REPORTER) {
                    "你的操作将提交给小编审核，确定提交吗？"
                } else {
                    "你的操作将立即生效，确定提交吗？"
                }
        }
        DialogHelper.showDialog(
            requireContext(),
            "修改活动标签",
            hintContent,
            "确定",
            "取消",
            {
                mViewModel.modifyVideoActivityTag(mForumVideoEntity, label)
                NewLogUtils.logSharePanelClick(
                    "click_modification_activity_tag",
                    mForumVideoEntity?.user?.id ?: "",
                    "视频帖",
                    mForumVideoEntity?.id ?: "",
                    mForumVideoEntity?.bbs?.id ?: "",
                    bbsType
                )
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    private fun showHighlightDialog(isHighlight: Boolean) {
        if (mForumVideoEntity == null) return
        var highlightDialogHintContent = ""
        val permissions = mForumVideoEntity?.me?.moderatorPermissions ?: Permissions()
        if ((isHighlight && permissions.highlightVideo > Permissions.GUEST) ||
            (!isHighlight && permissions.cancelHighlightVideo > Permissions.GUEST)
        ) {
            highlightDialogHintContent =
                if ((isHighlight && permissions.highlightVideo == Permissions.REPORTER) ||
                    (!isHighlight && permissions.cancelHighlightVideo == Permissions.REPORTER)
                ) {
                    "你的操作将提交给小编审核，确定提交吗？"
                } else {
                    "你的操作将立即生效，确定提交吗？"
                }
        }
        val title = if (isHighlight) "加精视频" else "取消精选"
        DialogHelper.showDialog(
            requireContext(),
            title,
            highlightDialogHintContent,
            "确定",
            "取消",
            {
                if (isHighlight) {
                    mViewModel.doHighlightThisVideo(mVideoId)
                } else {
                    mViewModel.cancelHighlightThisVideo(mVideoId)
                }
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        if (requestCode == ForumVideoDetailActivity.VIDEO_PATCH_REQUEST) {
            val entity =
                data.getParcelableExtra<ForumVideoEntity>(ForumVideoEntity::class.java.simpleName)
            mForumVideoEntity?.let {
                it.title = entity?.title ?: ""
                it.des = entity?.des ?: ""
                mViewModel.updateDetailLiveData.postValue(it)
            }
        }

        if (requestCode == MoreFunctionPanelDialog.REQUEST_CODE) {
            getItemClickCallback().invoke(data.getParcelableExtra(EntranceConsts.KEY_DATA))
        }

        if (requestCode == ChooseActivityDialogFragment.REQUEST_CODE) {
            getChooseSelectCallback().invoke(data.getParcelableExtra(EntranceConsts.KEY_DATA))
        }
    }

    //下载被删除事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBDownloadStatus) {
        if ("delete" == status.status) {
            setDownloadButton(mForumVideoEntity?.game)
        }
    }

    //安装、卸载事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(busFour: EBPackage) {
        setDownloadButton(mForumVideoEntity?.game)
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        if (!mIsFromTabWrapper && isSupportVisible) {
            DisplayUtils.transparentStatusBar(requireActivity())
        }
        if (!mBinding.topVideoView.isInPlayingState) {
            mBinding.topVideoView.startPlayLogic(isAutoPlay = true)
        } else {
            mBinding.topVideoView.onVideoResume(false)
        }
        DownloadManager.getInstance().addObserver(dataWatcher)
    }

    override fun onFragmentPause() {
        super.onFragmentPause()
        mBinding.topVideoView.onVideoPause()
        val currentPosition = mBinding.topVideoView.getCurrentPosition()
        mForumVideoEntity?.let {
            ForumScrollCalculatorHelper.savePlaySchedule(
                MD5Utils.getContentMD5(it.url),
                currentPosition
            )
        }
        DownloadManager.getInstance().removeObserver(dataWatcher)
    }

    override fun onStop() {
        super.onStop()
        mBinding.topVideoView.release()
        mBinding.topVideoView.disposableTimer()
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        NewLogUtils.logActivityPause(
            "视频帖详情页",
            "jump_video_detail ",
            stayTime,
            mForumVideoEntity?.bbs?.id ?: "",
            mForumVideoEntity?.bbs?.typeChinese ?: "综合论坛",
            "视频帖",
            mForumVideoEntity?.id ?: ""
        )
    }

    override fun onBackPressed(): Boolean {
        if (SyncDataBetweenPageHelper.setResultAndFinish(requireActivity(), mForumVideoEntity)) {
            return true
        }
        return super.onBackPressed()
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        setDownloadButton(mForumVideoEntity?.game)
    }
}