package com.gh.gamecenter.forum.detail

import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
import androidx.core.os.bundleOf
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.viewpager.widget.PagerAdapter
import com.ethanhua.skeleton.Skeleton
import com.ethanhua.skeleton.ViewSkeletonScreen
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.NewsDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.TrackableDialog
import com.gh.gamecenter.common.base.adapter.FragmentStateAdapter
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout
import com.gh.gamecenter.common.base.fragment.BaseLazyTabFragment
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.iinterface.IScrollable
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentForumDetailBinding
import com.gh.gamecenter.databinding.ItemForumSectionBinding
import com.gh.gamecenter.databinding.PopupForumDetailSectionsBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.eventbus.EBForumFollowChange
import com.gh.gamecenter.eventbus.EBTypeChange
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.UserEntity
import com.gh.gamecenter.forum.home.CommunityHomeFragment
import com.gh.gamecenter.forum.moderator.ApplyModeratorActivity
import com.gh.gamecenter.forum.moderator.ModeratorListActivity
import com.gh.gamecenter.forum.search.ForumOrUserSearchActivity
import com.gh.gamecenter.gamedetail.fuli.FuLiFragment
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
import com.gh.gamecenter.qa.questions.edit.QuestionEditActivity
import com.gh.gamecenter.qa.video.publish.VideoPublishActivity
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.halo.assistant.fragment.WebFragment
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

class ForumDetailFragment : BaseLazyTabFragment(), IScrollable {

    private var mAllForumArticleAskListFragment: ForumArticleAskListFragment? = null
    private var mEssenceForumArticleAskListFragment: ForumArticleAskListFragment? = null
    private var mTrendsFragment: Fragment? = null
    private var mAskForumArticleAskListFragment: ForumArticleAskListFragment? = null
    private var mVideoForumArticleAskListFragment: ForumArticleAskListFragment? = null
    private var mBbsId: String = ""
    private var mBbsType: String = ""
    private var mSectionId: String = ""
    private var mViewModel: ForumDetailViewModel? = null
    private var mForumDetail: ForumDetailEntity? = null
    private var mForumSectionAdapter: ForumSectionAdapter? = null
    private var mPopupWindow: PopupWindow? = null
    private lateinit var mBinding: FragmentForumDetailBinding
    private lateinit var mSkeleton: ViewSkeletonScreen

    private var mLastPosition = 0
    private var mAppbarReachTop = true
    private var mIsExpand = false
    private var mStatus: ApplyModeratorStatusEntity = ApplyModeratorStatusEntity()
    private var mIsToolbarWhite = false
    private var mShowSections = false
    private var mShowZone = false

    private var mAskIndex = INDEX_ASK
    private var mVideoIndex = INDEX_VIDEO

    override fun initFragmentList(fragments: MutableList<Fragment>) {
        mAllForumArticleAskListFragment = ForumArticleAskListFragment().with(
            bundleOf(
                EntranceConsts.KEY_ENTRANCE to "论坛详情",
                EntranceConsts.KEY_PATH to "全部", EntranceConsts.KEY_BBS_ID to mBbsId
            )
        ) as ForumArticleAskListFragment?
        mEssenceForumArticleAskListFragment = ForumArticleAskListFragment().with(
            bundleOf(
                EntranceConsts.KEY_ENTRANCE to "论坛详情",
                EntranceConsts.KEY_PATH to "精华", EntranceConsts.KEY_BBS_ID to mBbsId
            )
        ) as ForumArticleAskListFragment?
        mAskForumArticleAskListFragment = ForumArticleAskListFragment().with(
            bundleOf(
                EntranceConsts.KEY_ENTRANCE to "论坛详情",
                EntranceConsts.KEY_PATH to "问答", EntranceConsts.KEY_BBS_ID to mBbsId
            )
        ) as ForumArticleAskListFragment?
        mVideoForumArticleAskListFragment = ForumArticleAskListFragment().with(
            bundleOf(
                EntranceConsts.KEY_ENTRANCE to "论坛详情",
                EntranceConsts.KEY_PATH to "视频", EntranceConsts.KEY_BBS_ID to mBbsId
            )
        ) as ForumArticleAskListFragment?
        fragments.add(mAllForumArticleAskListFragment!!)
        fragments.add(mEssenceForumArticleAskListFragment!!)
        fragments.add(mAskForumArticleAskListFragment!!)
        fragments.add(mVideoForumArticleAskListFragment!!)
    }

    override fun restoreFragment(fragment: Fragment) {
        when (fragment.arguments?.getString(EntranceConsts.KEY_PATH)) {
            "全部" -> {
                mAllForumArticleAskListFragment = fragment as ForumArticleAskListFragment
            }
            "精华" -> {
                mEssenceForumArticleAskListFragment = fragment as ForumArticleAskListFragment
            }
            "专区" -> {
                mTrendsFragment = fragment
            }
            "问答" -> {
                mAskForumArticleAskListFragment = fragment as ForumArticleAskListFragment
            }
            "视频" -> {
                mVideoForumArticleAskListFragment = fragment as ForumArticleAskListFragment
            }
        }
    }

    override fun initTabTitleList(tabTitleList: MutableList<String>) {
        tabTitleList.add(TAB_TITLE_ALL)
        tabTitleList.add(TAB_TITLE_ESSENCE)
        tabTitleList.add(TAB_TITLE_ASK)
        tabTitleList.add(TAB_TITLE_VIDEO)
    }

    override fun providePagerAdapter(): PagerAdapter {
        return FragmentStateAdapter(childFragmentManager, mFragmentsList, mTabTitleList)
    }

    override fun provideIndicatorWidth(): Int = 16

    override fun getInflatedLayout(): View {
        mBinding = FragmentForumDetailBinding.bind(layoutInflater.inflate(R.layout.fragment_forum_detail, null, false))
        return mBinding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBbsId = arguments?.getString(EntranceConsts.KEY_BBS_ID, "") ?: ""
        mSectionId = arguments?.getString(EntranceConsts.KEY_BBS_SECTION_ID, "") ?: ""
        val factory = ForumDetailViewModel.Factory(mBbsId)
        mViewModel = viewModelProvider(factory)
        mViewModel?.forumDetail?.observe(this, Observer {
            mSkeleton.hide()
            mBinding.reuseLoading.reuseLlLoading.visibility = View.GONE
            if (it.status == Status.SUCCESS) {
                mBinding.communityEdit.visibility = View.VISIBLE
                mBinding.forumContainer.visibility = View.VISIBLE
                mBinding.reuseNoConnection.reuseNoConnection.visibility = View.GONE
                if (it.data != null) {
                    mForumDetail = it.data
                    mBbsType = if (it.data!!.type == "official_bbs") "综合论坛" else "游戏论坛"
                    val userId = UserManager.getInstance().userId
                    NewLogUtils.logForumDetailEnterOrClick(
                        "view_forum_detail",
                        mBbsId,
                        mBbsType,
                        userId,
                        entrance = if (mEntrance.contains("游戏详情")) "游戏详情页" else "论坛tab页"
                    )
                    mBaseHandler.postDelayed({
                        SensorsBridge.trackEvent(
                            "ViewForum",
                            "bbs_id",
                            mBbsId,
                            "forum_name",
                            mForumDetail?.name ?: "",
                            "bbs_type",
                            mBbsType
                        )
                    }, 3000)
                    initUI()
                }
            } else {
                mBinding.communityEdit.visibility = View.GONE
                mBinding.forumContainer.visibility = View.GONE
                if (it.exception != null && it.exception!!.code() == 404) {
                    mBinding.reuseNoneData.reuseNoneDataTv.text = "内容不见了~"
                    mBinding.reuseNoneData.reuseNoneDataDescTv.text = "先去看看其它的内容吧"
                    mBinding.reuseNoneData.reuseNoneDataIv.setImageResource(R.drawable.ic_data_load_exception)
                    mBinding.reuseNoneData.reuseNoneData.visibility = View.VISIBLE
                    mBinding.reuseNoConnection.reuseNoConnection.visibility = View.GONE
                    ToastUtils.showToast("内容可能已被删除")
                } else {
                    mBinding.reuseNoneData.reuseNoneData.visibility = View.GONE
                    mBinding.reuseNoConnection.reuseNoConnection.visibility = View.VISIBLE
                }
            }
        })
        mViewModel?.statusEntity?.observeNonNull(this) {
            mStatus = it
        }
        mBinding.refreshLayout.setProgressViewOffset(
            false,
            0,
            DisplayUtils.dip2px(40f) + DisplayUtils.getStatusBarHeight(requireContext().getResources())
        )
        mBinding.appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            mAppbarReachTop = abs(verticalOffset) <= 2
            if (mViewPager.currentItem < mFragmentsList.size) {
                mFragmentsList.safelyGetInRelease(mViewPager.currentItem)?.run {
                    if (this is ForumArticleAskListFragment) {
                        mBinding.refreshLayout.isEnabled = mAppbarReachTop && isListReachTop()
                    } else {
                        mBinding.refreshLayout.isEnabled = false
                    }
                }
            }
        })

        initSection()

        mSkeleton = Skeleton.bind(mBinding.skeletonContainer)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(R.color.skeleton_shimmer_color)
            .duration(Constants.SHIMMER_DURATION)
            .maskWidth(Constants.MASK_WIDTH)
            .gradientCenterColorWidth(Constants.GRADIENT_CENTER_COLOR_WIDTH)
            .load(R.layout.fragment_forum_detail_skeleton)
            .show()
        onViewClick()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel?.answerLiveData?.observeNonNull(viewLifecycleOwner) {
            insertDataToAllTab(it)
        }

        ViewCompat.setOnApplyWindowInsetsListener(mBinding.appbar) { _, insets ->
            (mBinding.toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin = insets.systemWindowInsetTop
            insets.consumeSystemWindowInsets()
        }

        mBinding.toolbar.setNavigationOnClickListener {
            NewLogUtils.logForumDetailEnterOrClick("click_forum_detail_return", mBbsId, mBbsType)
            requireActivity().finish()
        }

        mBinding.forumTopContentRv.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }

        mBinding.appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            if (!isAdded) return@OnOffsetChangedListener

            val absVerticalOffset = abs(verticalOffset)
            val total = appBarLayout.totalScrollRange

            if (absVerticalOffset > total / 2) {
                if (mBinding.titleTv.text.isNullOrEmpty()) {
                    mBinding.titleTv.text = mForumDetail?.name ?: ""
                    mBinding.forumThumbSmall.visibility = View.VISIBLE
                    mIsToolbarWhite = true
                    updateToolbarStyle(isToolbarWhite = true)
                }
            } else {
                if (!mBinding.titleTv.text.isNullOrEmpty()) {
                    mBinding.titleTv.text = ""
                    mBinding.forumThumbSmall.visibility = View.GONE
                    mIsToolbarWhite = false
                    updateToolbarStyle(isToolbarWhite = false)
                }
            }

            if (absVerticalOffset == total) {
                mBinding.toolbar.setTitleTextColor(ContextCompat.getColor(requireContext(), R.color.black))
            }
        })
        mViewPager.doOnPageSelected {
            mBinding.run {
                sectionContainer.goneIf(it != INDEX_ALL || !mShowSections)
            }
            MtaHelper.onEvent("论坛详情", getKeyValue(mLastPosition), getKeyValue(it))
            mLastPosition = it
            if (it < mFragmentsList.size) {
                val fragment = mFragmentsList.safelyGetInRelease(it)
                if (fragment is ForumArticleAskListFragment) {
                    fragment.refreshScrollHelper()
                    mBinding.refreshLayout.isEnabled = mAppbarReachTop && fragment.isListReachTop()
                } else {
                    mBinding.refreshLayout.isEnabled = false
                }
            }
            when {
                it == INDEX_ALL -> NewLogUtils.logForumDetailEnterOrClick(
                    "click_all_tab",
                    mBbsId,
                    mBbsType,
                    "",
                    mAllForumArticleAskListFragment?.filter ?: "回复"
                )
                it == INDEX_ESSENCE -> NewLogUtils.logForumDetailEnterOrClick("click_essence_tab", mBbsId, mBbsType)
                it == mAskIndex -> NewLogUtils.logForumDetailEnterOrClick("click_question_tab", mBbsId, mBbsType)
                it == mVideoIndex -> NewLogUtils.logForumDetailEnterOrClick(
                    "click_video_tab",
                    mBbsId,
                    mBbsType,
                    "",
                    mVideoForumArticleAskListFragment?.videoFilter ?: "推荐"
                )
                it == INDEX_TRENDS && mShowZone -> {
                    val entrance = if (arguments?.getBoolean(
                            EntranceConsts.KEY_SCROLL_TO_TRENDS,
                            false
                        ) == true
                    ) mEntrance else "论坛详情页点击"
                    com.gh.common.util.NewFlatLogUtils.logClickBBSDetailGameZoneTab(
                        mBbsId,
                        entrance,
                        mForumDetail?.zone?.link ?: ""
                    )
                }
            }
        }
        mBinding.refreshLayout.setOnRefreshListener {
            if (mAllForumArticleAskListFragment != null && mViewPager.currentItem == INDEX_ALL) {
                mAllForumArticleAskListFragment?.refresh()
            }
            if (mEssenceForumArticleAskListFragment != null && mViewPager.currentItem == INDEX_ESSENCE) {
                mEssenceForumArticleAskListFragment?.refresh()
            }
            if (mAskForumArticleAskListFragment != null && mViewPager.currentItem == mAskIndex) {
                mAskForumArticleAskListFragment?.refresh()
            }
            if (mVideoForumArticleAskListFragment != null && mViewPager.currentItem == mVideoIndex) {
                mVideoForumArticleAskListFragment?.refresh()
            }
        }
        LogUtils.uploadAccessToBbs(mBbsId, "论坛详情")
    }

    override fun onFragmentFirstVisible() {
        mTabTitleList.clear()
        mFragmentsList.clear()

        initTabTitleList(mTabTitleList)
        mFragmentsList.addAll(restoreFragments())
        if (mFragmentsList.isEmpty() || mFragmentsList.size != mTabTitleList.size) {
            mFragmentsList.clear()
            initFragmentList(mFragmentsList)
        }

        mViewPager.offscreenPageLimit = mFragmentsList.size
        mViewPager.addOnPageChangeListener(this)
        mViewPager.adapter = providePagerAdapter()
        mViewPager.currentItem = mCheckedIndex
        mTabLayout.setupWithViewPager(mViewPager)
        mTabIndicatorView.setupWithTabLayout(mTabLayout)
        mTabIndicatorView.setupWithViewPager(mViewPager)
        mTabIndicatorView.setIndicatorWidth(provideIndicatorWidth())
        initTabLayout()
        mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                updateTabStyle(tab, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                updateTabStyle(tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                updateTabStyle(tab, true)
            }
        })
    }

    private fun initTabLayout() {
        for (i in 0 until mTabLayout.tabCount) {
            val tab = mTabLayout.getTabAt(i)
            if (tab != null) {
                tab.customView =
                    BaseFragment_TabLayout.createDefaultTabCustomView(requireContext(), tab.text.toString())
                updateTabStyle(tab, i == mViewPager.currentItem)
            }
        }
    }

    private fun updateTabStyle(tab: TabLayout.Tab, isChecked: Boolean) {
        tab.customView?.findViewById<TextView>(R.id.tab_title)?.run {
            if (mShowZone && text == mTabTitleList[INDEX_TRENDS]) {
                compoundDrawablePadding = 2F.dip2px()
                setDrawableStart(
                    AppCompatResources.getDrawable(
                        requireContext(),
                        if (isChecked) R.drawable.icon_raiders_selected else R.drawable.icon_raiders_default
                    )
                )
            }
            textSize = 16F
            setTextColor(
                if (isChecked) R.color.text_title.toColor(requireContext()) else R.color.text_subtitle.toColor(
                    requireContext()
                )
            )
            typeface = if (isChecked) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
        }
    }

    private fun initSection() {
        val sectionLayoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        mForumSectionAdapter = ForumSectionAdapter(requireContext(), mViewModel!!) {
            setSection(it)
        }
        mBinding.sectionRv.run {
            layoutManager = sectionLayoutManager
            adapter = mForumSectionAdapter
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            addOnScrollListener(object : OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                        com.gh.common.util.NewFlatLogUtils.logSlideSection()
                    }
                }
            })
        }
        mViewModel?.sectionListLiveData?.observe(this) {
            if (!it.isNullOrEmpty() && it.size >= 2) {
                mShowSections = true
                mBinding.sectionContainer.goneIf(mViewPager.currentItem != INDEX_ALL)
                if (mSectionId.isNotEmpty()) {
                    it.forEachIndexed { index, section ->
                        if (section.id == mSectionId) {
                            mViewModel?.selectedSection = section
                            setSection(index)
                            mForumSectionAdapter?.submitList(it)
                            mBinding.sectionRv.scrollToPosition(index)
                        }
                    }
                } else {
                    mForumSectionAdapter?.submitList(it)
                }
                mBinding.sectionRv.post {
                    mBinding.sectionMoreIv.isVisible =
                        sectionLayoutManager.findLastCompletelyVisibleItemPosition() != sectionLayoutManager.itemCount - 1
                    mBinding.sectionMoreBackground.isVisible =
                        sectionLayoutManager.findLastCompletelyVisibleItemPosition() != sectionLayoutManager.itemCount - 1
                }
            } else {
                mShowSections = false
                mBinding.sectionContainer.visibility = View.GONE
            }
        }
    }

    private fun setSection(position: Int) {
        com.gh.common.util.NewFlatLogUtils.logClickSection(mViewModel?.selectedSection?.id ?: "", mBbsId, position)
        mAllForumArticleAskListFragment?.setSection(
            mViewModel?.selectedSection ?: ForumDetailEntity.Section(
                "",
                "全部"
            )
        )
    }

    fun hideRefreshingLayout() {
        mBinding.refreshLayout.isRefreshing = false
    }

    fun setRefreshingLayoutEnable(listReachTop: Boolean) {
        mBinding.refreshLayout.isEnabled = mAppbarReachTop && listReachTop
    }

    private fun getKeyValue(position: Int): String {
        return when (position) {
            INDEX_ALL -> "全部Tab"
            INDEX_ESSENCE -> "精华Tab"
            mAskIndex -> "问答Tab"
            mVideoIndex -> "视频Tab"
            else -> "专区Tab"
        }
    }

    private fun initUI() {
        mForumDetail?.apply {
            mBinding.forumTopMaskContainer.goneIf(background.isEmpty())
            mBinding.forumDefaultBackground.goneIf(background.isNotEmpty())
            mBinding.forumMaskDefaultView.goneIf(background.isNotEmpty())
            mBinding.moderatorContainer.visibleIf(moderator.isNotEmpty())
            mBinding.gameDetailTv.goneIf(!game.active)
            mBinding.forumNameTv.text = name
            mBinding.followTv.text = if (me.isFollower) "已关注" else "关注"
            mBinding.titleTv.text = name
            mBinding.dividerLine.goneIf(topLink.isEmpty())
            mBinding.moderatorTv.text = if (moderator.isNotEmpty()) "版主成员" else "暂无版主，申请成为版主"
            if (type == "official_bbs") {
                mBinding.forumThumbSmall.displayGameIcon(icon, null)
                mBinding.forumThumbBig.displayGameIcon(icon, null)
            } else {
                mBinding.forumThumbSmall.displayGameIcon(game.getIcon(), game.iconSubscript, game.iconFloat)
                mBinding.forumThumbBig.displayGameIcon(game.getIcon(), game.iconSubscript, game.iconFloat)
            }
            mBinding.toolbar.setNavigationIcon(if (!mIsDarkModeOn) R.drawable.ic_bar_back else R.drawable.ic_bar_back_light)
            mBinding.searchIv.setImageDrawable(
                if (!mIsDarkModeOn) R.drawable.ic_forum_detail_search.toDrawable(requireContext()) else R.drawable.ic_forum_detail_search_light.toDrawable(
                    requireContext()
                )
            )
            initModeratorHeadView(moderator)
            if (topLink.isNotEmpty()) {
                mBinding.forumTopContentContainer.visibility = View.VISIBLE
                mBinding.forumTopContentArrowContainer.goneIf(topLink.size <= TOP_CONTENT_EXPAND_LIMIT_COUNT)
                mBinding.forumTopContentRv.apply {
                    layoutParams = layoutParams.apply {
                        height = if (topLink.size > TOP_CONTENT_EXPAND_LIMIT_COUNT) {
                            TOP_CONTENT_ITEM_HEIGHT * TOP_CONTENT_EXPAND_LIMIT_COUNT + TOP_CONTENT_TOP_MARGIN
                        } else {
                            ViewGroup.LayoutParams.WRAP_CONTENT
                        }
                    }
                    layoutManager = LinearLayoutManager(requireContext())
                    adapter = ForumTopLinkAdapter(
                        requireContext(),
                        topLink,
                        mViewModel?.bbsId ?: "",
                        mForumDetail?.type ?: ""
                    )
                }
            } else {
                mBinding.forumTopContentContainer.visibility = View.GONE
                val params = mBinding.tabContainer.layoutParams as LinearLayout.LayoutParams
                params.topMargin = DisplayUtils.dip2px(-8f)
                mBinding.tabContainer.layoutParams = params
                mBinding.tabContainer.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.background_shape_white_radius_5_top_only)
            }

            if (background.isEmpty()) {
                ImageUtils.getBitmap(if (type == "official_bbs") icon else game.getIcon(),
                    object : BiCallback<Bitmap, Boolean> {
                        @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
                        override fun onFirst(first: Bitmap) {
                            val blurBitmap = BitmapUtils.doBlur(first, 100)
                            runOnUiThread {
                                mBinding.forumDefaultBackground.setImageBitmap(blurBitmap)
                            }
                        }

                        override fun onSecond(second: Boolean) {}
                    })
            } else {
                ImageUtils.display(mBinding.forumBackground, background)
            }
            mBinding.followTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    if (me.isFollower) R.color.text_subtitleDesc else R.color.white
                )
            )
            mBinding.followTv.background =
                ContextCompat.getDrawable(
                    requireContext(),
                    if (me.isFollower) R.drawable.button_round_gray_light else R.drawable.download_button_normal_style
                )

            showModeratorGuide()

            if (backgroundLayerColor.isNotEmpty()) {
                val colorRGBList =
                    backgroundLayerColor.substring(4, backgroundLayerColor.length - 1).split(",").map { it.toInt() }
                val colorHSV = colorRGBList.colorRGBToHSV().apply {
                    this[2] *= 0.6F
                }
                val startColor = Color.HSVToColor(colorHSV)
                val endColor = ColorUtils.setAlphaComponent(startColor, 0)

                mBinding.forumTopMaskContainer.background = GradientDrawable().apply {
                    gradientType = GradientDrawable.LINEAR_GRADIENT
                    orientation = GradientDrawable.Orientation.BOTTOM_TOP
                    colors = intArrayOf(startColor, endColor)
                }
            }

            mBinding.forumHeatTv.text = "热度值：${NumberUtils.transSimpleCount(hot)}"
            mBinding.forumHeatTv.setDrawableEnd(
                if (hotRank <= 20) AppCompatResources.getDrawable(
                    requireContext(),
                    R.drawable.icon_heat
                ) else null
            )
            mBinding.sectionMoreIv.setOnClickListener {
                com.gh.common.util.NewFlatLogUtils.logClickMoreSection()
                showSectionsPopupWindow()
            }

            zone?.let {
                mShowZone = true
                mTabTitleList.add(INDEX_TRENDS, it.customName.ifEmpty { TAB_TRENDS })
                if (it.style == "link") {//显示web页面
                    val webFragment = childFragmentManager.findFragmentByTag("${tag}$INDEX_TRENDS") ?: WebFragment()
                    val webBundle = Bundle()
                    webBundle.putString(EntranceConsts.KEY_ENTRANCE, "游戏专区")
                    webBundle.putString(EntranceConsts.KEY_URL, it.link)
                    webBundle.putBoolean(WebFragment.KEY_OPEN_NATIVE_PAGE, true)
                    webBundle.putString(EntranceConsts.KEY_BBS_ID, mBbsId)
                    webBundle.putString(EntranceConsts.KEY_PATH, TAB_TRENDS)
                    webFragment.arguments = webBundle
                    mTrendsFragment = webFragment
                    mFragmentsList.add(INDEX_TRENDS, webFragment)
                } else {
                    val fuliFragment = childFragmentManager.findFragmentByTag("${tag}$INDEX_TRENDS") ?: FuLiFragment()
                    fuliFragment.arguments = bundleOf(
                        GameEntity.TAG to game.toGameEntity(),
                        EntranceConsts.KEY_ENTRANCE to mEntrance,
                        EntranceConsts.KEY_PATH to TAB_TRENDS
                    )
                    mTrendsFragment = fuliFragment
                    mFragmentsList.add(INDEX_TRENDS, fuliFragment)
                }
                mViewPager.adapter?.notifyDataSetChanged()
                mAskIndex = INDEX_ASK + 1
                mVideoIndex = INDEX_VIDEO + 1
                initTabLayout()

                if (arguments?.getBoolean(EntranceConsts.KEY_SCROLL_TO_TRENDS, false) == true) {
                    mViewPager.currentItem = INDEX_TRENDS
                }
            }
        }
    }

    private fun showModeratorGuide() {
        var time = SPUtils.getInt(Constants.SP_FORUM_DETAIL_MODERATOR_GUIDE)
        if (time >= 2) return

        mBinding.run {
            postDelayedRunnable({
                tryCatchInRelease {
                    val location = IntArray(2)
                    moderatorTv.getLocationOnScreen(location)
                    moderatorGuideContainer.layoutParams =
                        (moderatorGuideContainer.layoutParams as ViewGroup.MarginLayoutParams).apply {
                            leftMargin = location[0] - 16F.dip2px()
                        }
                    moderatorGuideContainer.alpha = 0F
                    moderatorGuideContainer.visibility = View.VISIBLE
                    moderatorGuideContainer.animate().alpha(1F).setDuration(200).start()
                    moderatorGuideClose.setOnClickListener {
                        if (moderatorGuideContainer.visibility != View.GONE) {
                            moderatorGuideContainer.animate().alpha(0F).setDuration(200)
                                .withEndAction { moderatorGuideContainer.visibility = View.GONE }.start()
                        }
                    }

                    postDelayedRunnable({
                        tryCatchInRelease {
                            if (moderatorGuideContainer.visibility != View.GONE) {
                                moderatorGuideContainer.animate().alpha(0F).setDuration(200)
                                    .withEndAction { moderatorGuideContainer.visibility = View.GONE }.start()
                            }
                        }
                    }, 3000)

                    SPUtils.setInt(Constants.SP_FORUM_DETAIL_MODERATOR_GUIDE, ++time)
                }
            }, 1000)
        }
    }

    private fun onViewClick() {
        mBinding.toolbar.setOnClickListener {
            scrollToTop()
        }
        mBinding.searchIv.setOnClickListener {
            NewLogUtils.logForumSearchEnter("论坛详情页搜索按钮")
            NewLogUtils.logForumDetailEnterOrClick("click_forum_detail_search")
            requireContext().startActivity(ForumOrUserSearchActivity.getIntent(requireContext(), mBbsId, "论坛详情"))
        }
        mBinding.forumTopContentArrowContainer.setOnClickListener {
            mForumDetail?.run {
                mBinding.run {
                    val startHeight = forumTopContentRv.height
                    val endHeight = if (mIsExpand) {
                        TOP_CONTENT_ITEM_HEIGHT * TOP_CONTENT_EXPAND_LIMIT_COUNT + TOP_CONTENT_TOP_MARGIN
                    } else {
                        TOP_CONTENT_ITEM_HEIGHT * topLink.size + TOP_CONTENT_TOP_MARGIN
                    }
                    ValueAnimator.ofInt(startHeight, endHeight).apply {
                        duration = TOP_CONTENT_ANIMATION_DURATION
                        addUpdateListener {
                            forumTopContentRv.layoutParams = forumTopContentRv.layoutParams.apply {
                                height = it.animatedValue as Int
                            }
                        }
                    }.start()
                    forumTopContentArrowIv.animate()
                        .rotation(if (mIsExpand) 0F else 180F)
                        .setDuration(TOP_CONTENT_ANIMATION_DURATION)
                        .withEndAction {
                            mIsExpand = !mIsExpand
                        }
                        .start()
                }
            }
        }
        mBinding.communityEdit.setOnClickListener {
            mForumDetail?.run {
                val entrance = if (type == "game_bbs") "游戏论坛详情页" else "综合论坛详情页"
                NewLogUtils.logForumDetailPublishClick(entrance)
            }
            showCommunityEditWindow()
        }
        mBinding.moderatorTv.setOnClickListener {
            NewLogUtils.logForumDetailEnterOrClick("click_forum_member", mBbsId, mBbsType)
            NewLogUtils.logForumModeratorEnter(mBbsId, mBbsType)
            if (mForumDetail?.moderator.isNullOrEmpty()) {
                ifLogin("论坛详情—暂无版主") {
                    val bbsType = if (mBbsType == "game_bbs") "游戏论坛" else "综合论坛"
                    NewLogUtils.logApplyModeratorEnter(mBbsId, bbsType)
                    requireContext().startActivity(
                        ApplyModeratorActivity.getIntent(
                            requireContext(),
                            mBbsId,
                            mStatus
                        )
                    )
                }
            } else {
                requireContext().startActivity(
                    ModeratorListActivity.getIntent(
                        requireContext(),
                        mForumDetail?.id
                            ?: "",
                        mForumDetail?.name ?: "",
                        mForumDetail?.type ?: "",
                        mEntrance,
                        "论坛详情"
                    )
                )
            }
        }
        mBinding.reuseNoConnection.root.setOnClickListener {
            mBinding.reuseLoading.reuseLlLoading.visibility = View.VISIBLE
            mBinding.reuseNoConnection.reuseNoConnection.visibility = View.GONE
            mSkeleton.show()
            mViewModel?.getForumDetail()
            mViewModel?.getModeratorsApplyStatus()
            mViewModel?.getSections()
        }
//        mBinding.gameZoneTv.setOnClickListener {
//            NewLogUtils.logForumDetailEnterOrClick("click_strategy_zone", mBbsId, mBbsType)
//            if (mForumDetail?.zone != null) {
//                MtaHelper.onEvent("论坛详情", "顶部区域", "游戏专区")
//                GameDetailActivity.startGameDetailActivity(
//                    requireContext(), mForumDetail?.game?.id ?: "", mEntrance, GameDetailFragment.INDEX_TRENDES
//                )
//            }
//        }
        mBinding.forumThumbBig.setOnClickListener {
            NewLogUtils.logForumDetailEnterOrClick("click_forum_detail_forum_icon", mBbsId)
            MtaHelper.onEvent("论坛详情", "顶部区域", "游戏图标")
            if (mForumDetail?.game?.active == true) {
                GameDetailActivity.startGameDetailActivity(
                    requireContext(), mForumDetail?.game?.id
                        ?: "", "(论坛详情)"
                )
            }
        }
        mBinding.followTv.setOnClickListener {
            debounceActionWithInterval(R.id.followTv) {
                SensorsBridge.trackEvent(
                    "FollowForumClick",
                    "bbs_id",
                    mBbsId,
                    "forum_name",
                    mForumDetail?.name ?: "",
                    "bbs_type",
                    mBbsType
                )
                ifLogin(mEntrance) {
                    val forumEntity = ForumEntity(
                        id = mForumDetail?.id ?: "",
                        game = mForumDetail?.game!!,
                        name = mForumDetail?.name ?: "",
                        type = mForumDetail?.type ?: "",
                        icon = mForumDetail?.icon ?: "",
                        hot = mForumDetail?.hot ?: 0
                    )

                    if (mForumDetail?.me?.isFollower == true) {
                        mViewModel?.unFollowForum {
                            MtaHelper.onEvent("论坛详情", "顶部区域", "取消关注")
                            mForumDetail?.me?.isFollower = false
                            ToastUtils.showToast("取消成功")
                            initUI()
                            EventBus.getDefault().post(EBForumFollowChange(forumEntity, false))
                        }
                    } else {
                        mViewModel?.followForum {
                            val userId = UserManager.getInstance().userId
                            NewLogUtils.logForumDetailEnterOrClick(
                                "click_forum_detail_follow",
                                mBbsId,
                                mBbsType,
                                userId
                            )
                            MtaHelper.onEvent("论坛详情", "顶部区域", "关注")
                            mForumDetail?.me?.isFollower = true
                            ToastUtils.showToast("关注成功")
                            initUI()
                            EventBus.getDefault().post(EBForumFollowChange(forumEntity, true))
                        }
                    }
                }
            }
        }
        mBinding.forumRuleContainer.setOnClickListener {
            NewLogUtils.logForumDetailEnterOrClick("click_layout_description", mBbsId, mBbsType)
            NewLogUtils.logForumRuleEnter(mBbsId, mBbsType)
            startActivity(
                NewsDetailActivity.getIntentById(
                    requireContext(),
                    Constants.FORUM_REGULATIONS_NEWS_ID,
                    "论坛详情"
                )
            )
        }
        mBinding.gameDetailTv.setOnClickListener {
            com.gh.common.util.NewFlatLogUtils.logClickBBSDetailGameDetail()
            GameDetailActivity.startGameDetailActivity(
                requireContext(), mForumDetail?.game?.id
                    ?: "", "(论坛详情)"
            )
        }
    }

    private fun updateToolbarStyle(isToolbarWhite: Boolean) {
        if (!mIsDarkModeOn) {
            mBinding.titleTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    if (isToolbarWhite) R.color.black else R.color.transparent
                )
            )
            mBinding.toolbar.setBackgroundColor(
                ContextCompat.getColor(
                    requireContext(),
                    if (isToolbarWhite) R.color.white else R.color.transparent
                )
            )
            DisplayUtils.setStatusBarColor(
                requireActivity(),
                if (isToolbarWhite) R.color.white else R.color.transparent
            )
            if (isToolbarWhite) {
                DisplayUtils.setLightStatusBar(requireActivity(), true)
                mBinding.toolbar.setNavigationIcon(R.drawable.ic_bar_back)
                mBinding.searchIv.setImageDrawable(
                    ContextCompat.getDrawable(
                        requireContext(),
                        R.drawable.ic_forum_detail_search
                    )
                )
            } else {
                DisplayUtils.setLightStatusBar(requireActivity(), false)
                mBinding.toolbar.setNavigationIcon(R.drawable.ic_bar_back_light)
                mBinding.searchIv.setImageDrawable(
                    ContextCompat.getDrawable(
                        requireContext(),
                        R.drawable.ic_forum_detail_search_light
                    )
                )
            }
        } else {
            mBinding.titleTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    if (isToolbarWhite) R.color.white else R.color.transparent
                )
            )
            mBinding.toolbar.setBackgroundColor(
                ContextCompat.getColor(
                    requireContext(),
                    if (isToolbarWhite) R.color.black else R.color.transparent
                )
            )
            DisplayUtils.setStatusBarColor(
                requireActivity(),
                if (isToolbarWhite) R.color.black else R.color.transparent
            )
            mBinding.toolbar.setNavigationIcon(R.drawable.ic_bar_back_light)
            mBinding.searchIv.setImageDrawable(
                ContextCompat.getDrawable(
                    requireContext(),
                    R.drawable.ic_forum_detail_search_light
                )
            )
        }

    }

    private fun initModeratorHeadView(datas: List<UserEntity>) {
        mBinding.moderatorContainer.removeAllViews()
        datas.take(3).forEachIndexed { index, user ->
            val params = LinearLayout.LayoutParams(20F.dip2px(), 20F.dip2px())
            val headView = SimpleDraweeView(requireContext())
            val roundingParams = RoundingParams().apply {
                roundAsCircle = true
                setBorder(ContextCompat.getColor(requireContext(), R.color.white), 1F.dip2px().toFloat())
            }
            headView.hierarchy = GenericDraweeHierarchyBuilder(resources)
                .setFadeDuration(500)
                .setRoundingParams(roundingParams)
                .setPressedStateOverlay(ColorDrawable(ContextCompat.getColor(requireContext(), R.color.pressed_bg)))
                .setPlaceholderImage(R.drawable.occupy2, ScalingUtils.ScaleType.CENTER)
                .setBackground(ColorDrawable(ContextCompat.getColor(requireContext(), R.color.placeholder_bg)))
                .setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)
                .build()
            headView.layoutParams = params
            if (index != 0) {
                params.leftMargin = (-8f).dip2px()
            }
            ImageUtils.display(headView, user.icon)
            headView.setOnClickListener {
                MtaHelper.onEvent("论坛详情", "顶部区域", "版主头像")
                mBinding.moderatorTv.performClick()
            }
            mBinding.moderatorContainer.addView(headView)
        }

        val params = LinearLayout.LayoutParams(20F.dip2px(), 20F.dip2px())
        params.leftMargin = (-8F).dip2px()
        mBinding.moderatorContainer.addView(ImageView(requireContext()).apply {
            layoutParams = params
            setImageResource(R.drawable.icon_moderator_more)
            setOnClickListener {
                MtaHelper.onEvent("论坛详情", "顶部区域", "版主头像")
                mBinding.moderatorTv.performClick()
            }
        })
    }

    private fun showCommunityEditWindow() {
        val contentView = LayoutInflater.from(context).inflate(R.layout.community_edit_window, null)
        val params = ViewGroup.LayoutParams(resources.displayMetrics.widthPixels, ViewGroup.LayoutParams.WRAP_CONTENT)
        val dialog = TrackableDialog(
            requireContext(),
            R.style.DialogWindowTransparent,
            "论坛详情",
            mForumDetail?.name ?: "",
            null,
            "发布-空白",
            "发布-返回",
            false
        )
        val window = dialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.community_publication_animation)
        dialog.setContentView(contentView, params)
        dialog.show()
        val entrance = if (mForumDetail?.type == "game_bbs") "游戏论坛详情页" else "综合论坛详情页"
        NewLogUtils.logBbsPostPanelClick(entrance, mBbsId, mBbsType)
        contentView.findViewById<View>(R.id.community_edit_article_container).setOnClickListener {
            context?.ifLogin("论坛详情-发布-发帖子", action = {
                checkStoragePermissionBeforeAction {
                    MtaHelper.onEvent("论坛详情", "发布", "发帖子")
                    NewLogUtils.logArticleEditEnter(entrance, mBbsId, mBbsType)
                    startActivityForResult(
                        ArticleEditActivity.getIntent(
                            requireContext(), CommunityEntity(
                                mForumDetail?.id
                                    ?: "",
                                mForumDetail?.name
                                    ?: "",
                                icon = mForumDetail?.game?.getIcon(),
                                iconSubscript = mForumDetail?.game?.iconSubscript
                            ), mForumDetail?.type
                                ?: "",
                            "论坛详情页"
                        ),
                        ARTICLE_REQUEST_CODE
                    )
                    dialog.dismiss()
                }
            })
        }
        contentView.findViewById<View>(R.id.community_edit_question_container).setOnClickListener {
            context?.ifLogin("论坛详情-发布-提问", action = {
                checkStoragePermissionBeforeAction {
                    MtaHelper.onEvent("论坛详情", "发布", "提问")
                    NewLogUtils.logQuestionEditEnter(entrance, mBbsId, mBbsType)
                    startActivityForResult(
                        QuestionEditActivity.getIntent(
                            requireContext(), CommunityEntity(
                                mForumDetail?.id
                                    ?: "",
                                mForumDetail?.name
                                    ?: "",
                                icon = mForumDetail?.game?.getIcon(),
                                iconSubscript = mForumDetail?.game?.iconSubscript
                            ), mForumDetail?.type
                                ?: "", "论坛详情页"
                        ),
                        QUESTION_REQUEST_CODE
                    )
                    dialog.dismiss()
                }
            })
        }
        contentView.findViewById<View>(R.id.community_edit_video_container).setOnClickListener {
            context?.ifLogin("论坛详情-发布-视频", action = {
                checkStoragePermissionBeforeAction {
                    MtaHelper.onEvent("论坛详情", "发布", "发视频")
                    NewLogUtils.logPublishVideoEnter(entrance, mBbsId, mBbsType)
                    val communityEntity = CommunityEntity(
                        mForumDetail?.id
                            ?: "",
                        mForumDetail?.name
                            ?: "",
                        icon = mForumDetail?.game?.getIcon(),
                        iconSubscript = mForumDetail?.game?.iconSubscript
                    )
                    startActivityForResult(
                        VideoPublishActivity.getIntent(
                            context = requireContext(),
                            communityEntity = communityEntity,
                            type = mForumDetail?.type ?: "",
                            disableForumSelection = true,
                            entrance = mEntrance,
                            path = "论坛详情"
                        ),
                        VIDEO_REQUEST_CODE
                    )
                    dialog.dismiss()
                }
            })
        }
        contentView.findViewById<View>(R.id.community_edit_close).setOnClickListener {
//            MtaHelper.onEvent("论坛详情", CommunityManager.getInstance().community.name, "发布-关闭")
            NewLogUtils.logBbsPostPanelCloseClick()
            dialog.dismiss()
        }
    }

    private fun showSectionsPopupWindow() {
        val binding = PopupForumDetailSectionsBinding.inflate(LayoutInflater.from(requireContext()), null, false)
        val popupWindow = PopupWindow(
            binding.root,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply { mPopupWindow = this }

        mViewModel?.sectionListLiveData?.value?.forEachIndexed { index, section ->
            val item = getSectionItemView(section)
            binding.flexbox.addView(item)
            item.tag = section.name
            toggleHighlightedView(item, mViewModel?.selectedSection?.id == section.id)
            item.setOnClickListener {
                toggleHighlightedView(item, true)
                mViewModel?.selectedSection = section
                setSection(index)
                mForumSectionAdapter?.run {
                    notifyItemRangeChanged(0, itemCount)
                }
                mBinding.sectionRv.smoothScrollToPosition(index)
                popupWindow.dismiss()
            }
        }

        binding.background.setOnClickListener {
            popupWindow.dismiss()
            mPopupWindow = null
        }
        binding.closeIv.setOnClickListener {
            popupWindow.dismiss()
            mPopupWindow = null
        }
        popupWindow.isTouchable = true
        popupWindow.isFocusable = true
        popupWindow.animationStyle = 0
        popupWindow.showAsDropDown(mBinding.tabContainer, 0, 0)
    }

    private fun toggleHighlightedView(targetView: View, highlightIt: Boolean) {
        val sectionTv = targetView.findViewById<TextView>(R.id.sectionTv)
        if (highlightIt) {
            targetView.background = R.drawable.button_round_primary_light.toDrawable(requireContext())
            sectionTv?.setTextColor(R.color.theme_font.toColor(requireContext()))
        } else {
            targetView.background = R.drawable.button_round_gray_light.toDrawable(requireContext())
            sectionTv?.setTextColor(R.color.text_subtitle.toColor(requireContext()))
        }
    }

    private fun getSectionItemView(entity: ForumDetailEntity.Section): View {
        return ItemForumSectionBinding.bind(
            LayoutInflater.from(requireContext()).inflate(R.layout.item_forum_section, null)
        ).apply {
            iconIv.goneIf(entity.iconType.isEmpty() || entity.iconType == "none")
            when {
                entity.iconType == "url" && entity.icon.isNotEmpty() -> ImageUtils.display(iconIv, entity.icon)
                entity.iconType == "new" -> ImageUtils.display(iconIv, R.drawable.icon_section_newest)
                entity.iconType == "hot" -> ImageUtils.display(iconIv, R.drawable.icon_section_heat)
            }
            sectionTv.text = entity.name
        }.root.apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 24F.dip2px())
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                CommunityHomeFragment.ARTICLE_REQUEST_CODE -> {
                    val articleId = data?.getStringExtra("article_id") ?: return
//                    val communityId = data?.getStringExtra("community_id") ?: return
                    mViewModel?.getArticleData(articleId)
                }

                CommunityHomeFragment.QUESTION_REQUEST_CODE -> {
                    val questionId = data?.getStringExtra("question_id") ?: return
                    mViewModel?.getQuestionDetail(questionId)
                }

                CommunityHomeFragment.VIDEO_REQUEST_CODE -> {
                    val forumVideoEntity =
                        data?.getParcelableExtra<ForumVideoEntity>(ForumVideoEntity::class.java.simpleName)
                            ?: return
                    mViewModel?.getVideoDetail(forumVideoEntity.id)
                }
            }
        }
    }

    private fun insertDataToAllTab(entity: AnswerEntity) {
        mAllForumArticleAskListFragment?.insertDataToFirstIndex(entity)
    }

    override fun onBackPressed(): Boolean {
        NewLogUtils.logForumDetailEnterOrClick("click_forum_detail_return", mBbsId, mBbsType)
        val fragment = mFragmentsList[mBinding.fragmentViewPager.currentItem]
        return if (fragment is ForumArticleAskListFragment) {
            fragment.onBackPressed()
        } else if (fragment is WebFragment && fragment.isAdded) {
            fragment.onBackPressed()
        } else {
            super.onBackPressed()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBTypeChange) {
        if (status.type == EB_SHOW_QUESTION_BUTTON) {
            setPutQuestionButtonStatus(View.VISIBLE)
        } else if (status.type == EB_HIDE_QUESTION_BUTTON) {
            setPutQuestionButtonStatus(View.GONE)
        }
    }

    private fun setPutQuestionButtonStatus(visibility: Int) {
        if (mBinding.communityEdit.visibility == visibility) return
        if (visibility == View.GONE) {
            val animation = AnimationUtils.loadAnimation(context, R.anim.button_anim_exit)
            mBinding.communityEdit.startAnimation(animation)
        } else {
            val animation = AnimationUtils.loadAnimation(context, R.anim.button_anim_enter)
            mBinding.communityEdit.startAnimation(animation)
        }
        mBinding.communityEdit.visibility = visibility
    }

    override fun onStop() {
        super.onStop()
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        NewLogUtils.logActivityPause("论坛详情页", "jump_forum_detail", stayTime, mBbsId, mBbsType, "", "")
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateToolbarStyle(mIsToolbarWhite)
        if (::mBinding.isInitialized) {
            for (i in 0 until mBinding.fragmentTabLayout.tabCount) {
                val tab = mBinding.fragmentTabLayout.getTabAt(i)
                if (tab != null) {
                    updateTabStyle(tab, tab.isSelected)
                }
            }
            mForumSectionAdapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
        }
    }

    override fun scrollToTop() {
        val fragment = mFragmentsList.safelyGetInRelease(mViewPager.currentItem)
        if (fragment is IScrollable && fragment.isAdded) {
            fragment.scrollToTop()
        }
        mBinding.appbar.setExpanded(true)
    }

    companion object {
        const val INDEX_ALL = 0
        const val INDEX_ESSENCE = 1
        const val INDEX_TRENDS = 2
        const val INDEX_ASK = 2
        const val INDEX_VIDEO = 3
        const val TAB_TITLE_ALL = "全部"
        const val TAB_TITLE_ESSENCE = "精华"
        const val TAB_TRENDS = "专区"
        const val TAB_TITLE_ASK = "问答"
        const val TAB_TITLE_VIDEO = "视频"
        const val EB_SHOW_QUESTION_BUTTON = "EB_SHOW_QUESTION_BUTTON"
        const val EB_HIDE_QUESTION_BUTTON = "EB_HIDE_QUESTION_BUTTON"
        const val ARTICLE_REQUEST_CODE = 200
        const val QUESTION_REQUEST_CODE = 201
        const val VIDEO_REQUEST_CODE = 202
        const val TOP_CONTENT_EXPAND_LIMIT_COUNT = 4
        const val TOP_CONTENT_ANIMATION_DURATION = 200L
        var TOP_CONTENT_ITEM_HEIGHT = 34F.dip2px()
        var TOP_CONTENT_TOP_MARGIN = 8F.dip2px()
    }
}