package com.gh.gamecenter.forum.home

import android.app.Activity
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.ColorFilter
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.view.*
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.ColorUtils
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.airbnb.lottie.LottieProperty
import com.airbnb.lottie.SimpleColorFilter
import com.airbnb.lottie.model.KeyPath
import com.airbnb.lottie.value.LottieValueCallback
import com.gh.common.browse.BrowseTimer
import com.gh.common.iinterface.ISuperiorChain
import com.gh.common.prioritychain.CommunityHomeGuideHandler
import com.gh.common.prioritychain.PriorityChain
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.TrackableDialog
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.EntranceConsts.IS_DETAIL_PAGE
import com.gh.gamecenter.common.retrofit.ApiResponse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.AvatarBorderView
import com.gh.gamecenter.core.iinterface.IScrollable
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.databinding.FragmentCommunityHomeBinding
import com.gh.gamecenter.databinding.TabItemCommunityBinding
import com.gh.gamecenter.eventbus.EBSkip
import com.gh.gamecenter.eventbus.EBTypeChange
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.forum.home.follow.FollowHomeFilterPopWindow
import com.gh.gamecenter.forum.home.follow.fragment.FollowHomeFragment
import com.gh.gamecenter.forum.search.ForumOrUserSearchActivity
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserRepository
import com.gh.gamecenter.qa.article.detail.ArticleDetailWebCacheManager
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
import com.gh.gamecenter.qa.draft.CommunityDraftWrapperActivity
import com.gh.gamecenter.qa.questions.edit.QuestionEditActivity
import com.gh.gamecenter.qa.video.publish.VideoPublishActivity
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.gh.gamecenter.wrapper.MainWrapperViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.halo.assistant.HaloApp
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs
import kotlin.math.roundToInt

class CommunityHomeFragment : LazyFragment() {

    private var mBinding: FragmentCommunityHomeBinding? = null
    private var mViewModel: CommunityHomeViewModel? = null
    private var mMainWrapperViewModel: MainWrapperViewModel? = null
    private var mFragmentList = arrayListOf<Fragment>()
    private var mTitleList = arrayListOf("关注", "推荐", "论坛", "活动")
    private var mTabList = arrayListOf<Any>()
    private var mDefaultSelectedTab = -1
    private var mNavigationBitmap: Bitmap? = null
    private var mShowVideo = true
    private var mBottomTabId = ""
    private val mPriorityChain by lazy { PriorityChain() }
    private var mSuperiorChain: ISuperiorChain? = null

    private val browseTimer = BrowseTimer()
        .withResult {
            SensorsBridge.trackCommunityBrowsingDuration(it / 1000.0)
        }

    private val followFilterPopWindow by lazy {
        FollowHomeFilterPopWindow.create(requireContext()).apply {
            setOnDismissListener {
                resetFollowTab()
            }
            setFilterListener(object : FollowHomeFilterPopWindow.OnFilteredChangedListener {
                override fun filterFollowed(position: Int) {
                    mViewModel?.filterFollowed(position)
                }

            })
        }
    }

    private val obTabSelectedListener = object : OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            if (tab?.position == TAB_FOLLOW_INDEX) {
                mViewModel?.updateFilterResId(R.drawable.ic_follow_arrow_down)
            }
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            if (tab?.position == TAB_FOLLOW_INDEX) {
                mViewModel?.updateFilterResId(null)
            }
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
            if (mViewModel?.followFilterStatus?.value == R.drawable.ic_follow_arrow_down) {
                mViewModel?.updateFilterResId(R.drawable.ic_follow_arrow_up)
                mBinding?.tabLayout?.let(followFilterPopWindow::showAsDropDown)
            }
        }

    }

    override fun getRealLayoutId(): Int {
        return R.layout.fragment_community_home
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        mBinding = FragmentCommunityHomeBinding.bind(inflatedView)
    }


    override fun onFragmentFirstVisible() {
        ArticleDetailWebCacheManager.init(requireContext().applicationContext)

        mViewModel = viewModelProvider()
        mMainWrapperViewModel = viewModelProviderFromParent(MainWrapperViewModel.Factory(HaloApp.getInstance()))

        super.onFragmentFirstVisible()

        initViewPager()

        mViewModel?.followFilterStatus?.observe(viewLifecycleOwner, Observer { resId ->
            val tabLayout = mBinding?.tabLayout ?: return@Observer
            val tab = tabLayout.getTabAt(TAB_FOLLOW_INDEX)
            val tvTitle = tab?.customView?.findViewById<TextView>(R.id.tab_title)
            if (resId != null) {
                tvTitle?.setDrawableEnd(resId, 8F.dip2px(), 8F.dip2px())
            } else {
                tvTitle?.setDrawableEnd(null, 8F.dip2px(), 8F.dip2px())
            }


        })
    }

    private fun addHomeVideoGuideHandler() {
        val decorView = activity?.window?.decorView as? FrameLayout
        val communityHomeGuideHandler = CommunityHomeGuideHandler(21, requireContext(), decorView, mBinding?.videoLottie)
        mPriorityChain.addHandler(communityHomeGuideHandler)
    }

    override fun initRealView() {
        super.initRealView()

        mViewModel?.articleLiveData?.observeNonNull(viewLifecycleOwner) {
            insertDataToRecommendTab(it)
        }

        mMainWrapperViewModel?.bottomTabListLiveData?.observe(this) { tabList ->
            mBinding?.videoAndSearchContainer?.goneIf(!mShowVideo) {
                val decorView = requireActivity().window.decorView as? FrameLayout
                addHomeVideoGuideHandler()

                // 每日首次进入社区tab视频lottie播放3次
                val lastPlayTime = SPUtils.getLong(Constants.SP_COMMUNITY_HOME_VIDEO_LOTTIE_LAST_PLAY_TIME, 0L) / 1000
                if (!TimeUtils.isToday(lastPlayTime) && decorView?.findViewById<View>(R.id.guideContainer) == null) {
                    mBinding?.videoLottie?.playAnimation()
                    SPUtils.setLong(Constants.SP_COMMUNITY_HOME_VIDEO_LOTTIE_LAST_PLAY_TIME, System.currentTimeMillis())
                }
            }
        }

        mMainWrapperViewModel?.bottomDoubleTabAction?.observe(viewLifecycleOwner) {
            if (isSupportVisible && it.id == mBottomTabId) {
                scrollToTop()
            }
        }

        mBinding?.run {
            topBg.visibleIf(!mIsDarkModeOn)

            videoLottie.setOnClickListener {
                DirectUtils.directToLegacyVideoDetail(
                    requireContext(),
                    "",
                    VideoDetailContainerViewModel.Location.VIDEO_ACTIVITY.value,
                    referer = "视频流-社区右上角",
                    isHomeVideo = true
                )
            }
            searchIconIv.setOnClickListener {
                NewLogUtils.logCommunitySearchClick()
                NewLogUtils.logForumSearchEnter("社区搜索栏")
                NewFlatLogUtils.logAccessToBbsSearch("社区", "")
                requireContext().startActivity(
                    ForumOrUserSearchActivity.getIntent(
                        requireContext(),
                        "",
                        "论坛首页",
                        SOURCE_ENTRANCE,
                        SOURCE_ENTRANCE
                    )
                )
            }

            communityEditBtn.setOnClickListener {
                NewLogUtils.logRecommendFeedPublishClick()
                showCommunityEditWindow()
            }

            topBg.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    topBg.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    if (topBg.width <= 0 || topBg.height <= 0) return
                    val bitmap = topBg.getBitmapFromView()
                    bitmap?.let {
                        mNavigationBitmap = Bitmap.createBitmap(
                            it,
                            0,
                            0,
                            it.width,
                            DisplayUtils.getStatusBarHeight(resources) + 52F.dip2px()
                        )
                    }
                }
            })

            val isDetailPage = arguments?.getBoolean(IS_DETAIL_PAGE) ?: false
            ivBack.visibility = if (isDetailPage) View.VISIBLE else View.GONE
            if (isDetailPage) {
                ivBack.setOnClickListener {
                    activity?.finish()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        savedInstanceState?.let { mDefaultSelectedTab = it.getInt(LAST_SELECTED_POSITION) }
        mBottomTabId = arguments?.getString(EntranceConsts.KEY_BOTTOM_TAB_ID, "") ?: ""
    }

    override fun onResume() {
        super.onResume()
        browseTimer.start()
    }

    override fun onPause() {
        super.onPause()
        browseTimer.stop()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        mBinding?.viewPager?.let { outState.putInt(LAST_SELECTED_POSITION, it.currentItem) }
        super.onSaveInstanceState(outState)
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        DisplayUtils.transparentStatusBar(requireActivity())
        DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn)
        NewLogUtils.logCommunityHomeEvent("view_community")

        mSuperiorChain?.registerInferiorChain(mPriorityChain)
    }

    override fun onFragmentPause() {
        super.onFragmentPause()

        mSuperiorChain?.unregisterInferiorChain(mPriorityChain)
    }

    fun setCurrentItem(index: Int) {
        mBinding?.viewPager?.currentItem = index
    }

    private fun initViewPager() {
        val defaultSelectedPosition =
            if (mDefaultSelectedTab != -1) mDefaultSelectedTab
            else arguments?.getInt(EntranceConsts.KEY_SUB_POSITION) ?: 0

        mBinding?.run {
            mTabList.clear()
            mFragmentList.clear()
            val tag = "android:switcher:${viewPager.id}:"

            val followFragment = childFragmentManager.findFragmentByTag("$tag$TAB_FOLLOW_INDEX")
                ?: FollowHomeFragment()
            mFragmentList.add(followFragment)

            val forumArticleListFragment = childFragmentManager.findFragmentByTag("$tag$TAB_RECOMMEND_INDEX")
                ?: ForumArticleListFragment().with(
                    bundleOf(
                        EntranceConsts.KEY_ENTRANCE to "社区",
                        EntranceConsts.KEY_PATH to "推荐"
                    )
                )
            mFragmentList.add(forumArticleListFragment)

            val forumFragment = childFragmentManager.findFragmentByTag("${tag}$TAB_FORUM_INDEX")
                ?: ForumFragment().with(bundleOf(EntranceConsts.KEY_ENTRANCE to "社区"))
            mFragmentList.add(forumFragment)

            val activityFragment = childFragmentManager.findFragmentByTag("${tag}$TAB_ACTIVITY_INDEX")
                ?: ForumActivityFragment().with(bundleOf(EntranceConsts.KEY_ENTRANCE to "活动"))
            mFragmentList.add(activityFragment)

            viewPager.run {
                offscreenPageLimit = mFragmentList.size
                tryCatchInRelease {
                    val field = ViewPager::class.java.getDeclaredField("mRestoredCurItem")
                    field.isAccessible = true
                    field.set(this, defaultSelectedPosition)
                }
                adapter = FragmentAdapter(childFragmentManager, mFragmentList, mTitleList)
                doOnScroll(
                    onPageSelected = { position ->
                        communityEditBtn.goneIf(position != TAB_RECOMMEND_INDEX && position != TAB_FOLLOW_INDEX)
                        when (position) {
                            TAB_FOLLOW_INDEX -> {
                                root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
                                topBg.translationY = 0F
                                changeNavigationBg()
                                NewLogUtils.logCommunityHomeEvent("click_for_you_tab")
                                SensorsBridge.trackCommunityTopTabSelected("关注")
                            }

                            TAB_RECOMMEND_INDEX -> {
                                root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
                                topBg.translationY = 0F
                                changeNavigationBg()
                                NewLogUtils.logCommunityHomeEvent("click_for_you_tab")
                                SensorsBridge.trackCommunityTopTabSelected("推荐")
                            }

                            TAB_FORUM_INDEX -> {
                                root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
                                (mFragmentList[2] as ForumFragment).translationY.run {
                                    topBg.translationY = -this.toFloat()
                                    changeNavigationBg(this)
                                }
                                NewLogUtils.logCommunityHomeEvent("click_forum_tab")
                                SensorsBridge.trackCommunityTopTabSelected("论坛")
                            }

                            TAB_ACTIVITY_INDEX -> {
                                root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
                                (mFragmentList[3] as ForumActivityFragment).translationY.run {
                                    topBg.translationY = -this.toFloat()
                                    changeNavigationBg(this)
                                }
                                NewLogUtils.logCommunityHomeEvent("click_activity_tab")
                                SensorsBridge.trackCommunityTopTabSelected("活动")
                            }
                        }
                    },
                    onPageScrolled = { position, positionOffset, _ ->
                        if (position + 1 != mTabList.size) {
                            (mTabList[position] as TextView).run {
                                textSize = (DEFAULT_TAB_TEXT_SIZE + ((1 - positionOffset) * 4)).roundTo(1)
                                setTextColor(
                                    ColorUtils.blendARGB(
                                        TAB_DEFAULT_COLOR.toColor(requireContext()),
                                        TAB_SELECTED_COLOR.toColor(requireContext()),
                                        1 - positionOffset
                                    )
                                )
                            }
                            if (mTabList[position + 1] is TextView) {
                                (mTabList[position + 1] as TextView).run {
                                    textSize = (DEFAULT_TAB_TEXT_SIZE + ((positionOffset) * 4)).roundTo(1)
                                    setTextColor(
                                        ColorUtils.blendARGB(
                                            TAB_DEFAULT_COLOR.toColor(requireContext()),
                                            TAB_SELECTED_COLOR.toColor(requireContext()),
                                            positionOffset
                                        )
                                    )
                                }
                            } else {
                                (mTabList[position + 1] as TabItemCommunityBinding).run {
                                    val layoutParams = tabImg.layoutParams
                                    layoutParams.width =
                                        (DEFAULT_TAB_IMG_WIDTH + 8F.dip2px() * positionOffset).roundToInt()
                                    layoutParams.height =
                                        ((DEFAULT_TAB_IMG_HEIGHT) + 4F.dip2px() * positionOffset).roundToInt()
                                    tabImg.layoutParams = layoutParams
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        tabImg.imageTintList =
                                            ColorStateList.valueOf(
                                                ColorUtils.blendARGB(
                                                    TAB_DEFAULT_COLOR.toColor(requireContext()),
                                                    TAB_SELECTED_COLOR.toColor(requireContext()),
                                                    positionOffset
                                                )
                                            )
                                    }

                                }
                            }

                            // 多 tab 切换的时候可能会出现某些 tab 的文字没有回归到原始大小的问题的问题 (positionOffset 不保证连续)
                            for ((index, tabTv) in mTabList.withIndex()) {
                                val isNeedReset =
                                    abs(index - position) >= 2 && tabTv is TextView && tabTv.textSize != DEFAULT_TAB_TEXT_SIZE
                                if (isNeedReset) {
                                    (tabTv as TextView).textSize = DEFAULT_TAB_TEXT_SIZE
                                    tabTv.setTextColor(TAB_DEFAULT_COLOR.toColor(requireContext()))
                                }
                            }
                        }

                        updateTabStyle(position, positionOffset)
                    }
                )
            }
            tabLayout.addOnTabSelectedListener(obTabSelectedListener)
            tabLayout.setupWithViewPager(viewPager)
            indicatorView.run {
                setupWithTabLayout(tabLayout)
                setupWithViewPager(viewPager)
                setIndicatorWidth(18)
            }

            val selectedPosition = if (UserManager.getInstance().isLoggedIn) {
                TAB_FOLLOW_INDEX
            } else {
                TAB_RECOMMEND_INDEX
            }
            for (i in 0 until tabLayout.tabCount) {
                val tab = tabLayout.getTabAt(i) ?: continue
                val tabTitle = if (tab.text != null) tab.text.toString() else ""
                val tabViewBinding = generateTabView(tabTitle, i, selectedPosition)
                tab.customView = tabViewBinding.root
            }
            viewPager.setCurrentItem(selectedPosition, false)
        }
    }

    private fun updateTabStyle(selectedPosition: Int, positionOffset: Float) {
        for ((index, titleView) in mTabList.withIndex()) {
            if (titleView is TextView) {
                updateTabText(titleView, index, selectedPosition, positionOffset)
            } else {
                updateTabImage(titleView as TabItemCommunityBinding, index, selectedPosition, positionOffset)
            }
        }
    }

    private fun updateTabText(
        titleView: TextView,
        index: Int,
        selectedPosition: Int,
        positionOffset: Float
    ) {
        if (index == selectedPosition) {
            if (positionOffset == 0F) {
                titleView.setTextColor(TAB_SELECTED_COLOR.toColor(requireContext()))
                titleView.setTypeface(titleView.typeface, Typeface.BOLD)
            } else if (positionOffset > 0F) {
                titleView.setTypeface(null, Typeface.NORMAL)
            }
        } else {
            titleView.setTypeface(null, Typeface.NORMAL)
            if (positionOffset == 0F) {
                titleView.setTextColor(TAB_DEFAULT_COLOR.toColor(requireContext()))
            }
        }
    }

    private fun updateTabImage(
        binding: TabItemCommunityBinding,
        index: Int,
        selectedPosition: Int,
        positionOffset: Float
    ) {
        if (index == selectedPosition) {
            updateTabImageIfSelected(binding, positionOffset)
        } else {
            updateTabImageIfUnSelected(binding, positionOffset)
        }
    }

    private fun updateTabImageIfSelected(binding: TabItemCommunityBinding, positionOffset: Float) {
        binding.run {
            if (positionOffset == 0F) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    tabImg.imageTintList = ColorStateList.valueOf(TAB_SELECTED_COLOR.toColor(requireContext()))
                } else {
                    tabImg.setImageResource(R.drawable.ic_tab_activity_active)
                }
            }
        }
    }

    private fun updateTabImageIfUnSelected(binding: TabItemCommunityBinding, positionOffset: Float) {
        binding.run {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                tabImg.setImageResource(R.drawable.ic_tab_activity_default)
            }
            if (positionOffset == 0F) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    tabImg.imageTintList = ColorStateList.valueOf(TAB_DEFAULT_COLOR.toColor(requireContext()))
                }
            }
        }
    }

    private fun generateTabView(title: String, index: Int, selectedPosition: Int): TabItemCommunityBinding {
        val binding = TabItemCommunityBinding.inflate(LayoutInflater.from(requireContext()))
        binding.run {
            if (index == TAB_ACTIVITY_INDEX) {
                mTabList.add(binding)
                tabTitle.visibility = View.GONE
                tabImg.visibility = View.VISIBLE
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    tabImg.setImageResource(R.drawable.ic_tab_activity_svg)
                } else {
                    tabImg.setImageResource(R.drawable.ic_tab_activity_default)
                }
            } else {
                mTabList.add(tabTitle)
                tabTitle.visibility = View.VISIBLE
                tabImg.visibility = View.GONE
                tabTitle.run {
                    text = title
                    textSize = DEFAULT_TAB_TEXT_SIZE
                    setTextColor(TAB_DEFAULT_COLOR.toColor(requireContext()))
                    if (index == TAB_FOLLOW_INDEX && selectedPosition == TAB_FOLLOW_INDEX) {
                        mViewModel?.updateFilterResId(R.drawable.ic_follow_arrow_down)
                    }
                }
            }
        }
        return binding
    }

    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(),
            com.gh.gamecenter.common.R.style.DialogWindowTransparent,
            "社区",
            "社区-发布弹窗",
            null,
            "发布-空白",
            "发布-返回",
            false
        )
        val window = dialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(com.gh.gamecenter.common.R.style.community_publication_animation)
        dialog.setContentView(contentView, params)
        dialog.show()
        NewLogUtils.logBbsPostPanelClick("推荐信息流", "", "")

        val draft = contentView.findViewById<View>(R.id.draft)
        draft.setOnClickListener {
            it.context.ifLogin("论坛首页-发布-发帖子") {
                startActivity(CommunityDraftWrapperActivity.getIntent(requireContext()))
            }
        }

        val avatar = contentView.findViewById<AvatarBorderView>(R.id.avatar)
        val observer = Observer<ApiResponse<UserInfoEntity>> { avatar.displayAvatar(it?.data?.icon) }
        UserRepository.getInstance().loginUserInfo.observe(viewLifecycleOwner, observer)
        dialog.setOnDismissListener {
            UserRepository.getInstance().loginUserInfo.removeObserver(observer)
        }

        contentView.findViewById<View>(R.id.community_edit_article_container).setOnClickListener {
            context?.ifLogin("论坛首页-发布-发帖子", action = {
                showRegulationTestDialogIfNeeded {
                    MtaHelper.onEvent("论坛首页", "发布", "发帖子")
                    NewLogUtils.logArticleEditEnter("推荐信息流", "", "")
                    startActivityForResult(
                        ArticleEditActivity.getIntent(requireContext(), null, entrance = "社区推荐Tab"),
                        ARTICLE_REQUEST_CODE
                    )
                    dialog.dismiss()
                }
            })
        }
        contentView.findViewById<View>(R.id.community_edit_question_container).setOnClickListener {
            context?.ifLogin("论坛首页-发布-提问", action = {
                showRegulationTestDialogIfNeeded {
                    MtaHelper.onEvent("论坛首页", "发布", "提问")
                    NewLogUtils.logQuestionEditEnter("推荐信息流", "", "")
                    startActivityForResult(
                        QuestionEditActivity.getIntent(requireContext(), entrance = "社区推荐Tab"),
                        QUESTION_REQUEST_CODE
                    )
                    dialog.dismiss()
                }
            })
        }
        contentView.findViewById<View>(R.id.community_edit_video_container).setOnClickListener {
            context?.ifLogin("论坛首页-发布-视频", action = {
                showRegulationTestDialogIfNeeded {
                    MtaHelper.onEvent("论坛首页", "发布", "发视频")
                    NewLogUtils.logPublishVideoEnter("推荐信息流", "", "")
                    startActivityForResult(
                        VideoPublishActivity.getIntent(
                            context = requireContext(),
                            type = "",
                            entrance = mEntrance,
                            path = "论坛首页"
                        ),
                        VIDEO_REQUEST_CODE
                    )
                    dialog.dismiss()
                }
            })
        }
        contentView.findViewById<View>(R.id.community_edit_close).setOnClickListener {
            NewLogUtils.logBbsPostPanelCloseClick()
            dialog.dismiss()
        }
    }

    private fun resetFollowTab() {
        mBinding?.tabLayout?.run {
            if (selectedTabPosition == TAB_FOLLOW_INDEX) {
                mViewModel?.updateFilterResId(R.drawable.ic_follow_arrow_down)
            } else {
                mViewModel?.updateFilterResId(null)
            }
        }
        mBinding?.tabLayout?.removeOnTabSelectedListener(obTabSelectedListener)
        mBinding?.tabLayout?.addOnTabSelectedListener(obTabSelectedListener)
    }

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

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

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

    private fun insertDataToRecommendTab(entity: ArticleEntity) {
        (mFragmentList[TAB_RECOMMEND_INDEX] as? ForumArticleListFragment)?.insertDataToFirstIndex(entity)
    }

    override fun onBackPressed(): Boolean {
        mBinding?.viewPager?.run {
            if (currentItem == 1) {
                return (mFragmentList[1] as ForumArticleListFragment).onBackPressed()
            }
        }
        return super.onBackPressed()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(status: EBTypeChange) {
        val currentPosition = mBinding?.viewPager?.currentItem ?: 0
        if (currentPosition != TAB_FOLLOW_INDEX && currentPosition != TAB_RECOMMEND_INDEX) {
            return
        }

        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) {
        mBinding?.run {
            if (communityEditBtn.visibility == visibility) return

            if (visibility == View.GONE) {
                val animation = AnimationUtils.loadAnimation(context, R.anim.button_anim_exit)
                communityEditBtn.startAnimation(animation)
            } else {
                val animation = AnimationUtils.loadAnimation(context, R.anim.button_anim_enter)
                communityEditBtn.startAnimation(animation)
            }
            communityEditBtn.visibility = visibility
        }
    }

    private fun scrollToTop() {
        if (mFragmentList.isEmpty()) return
        val currentPosition = mBinding?.viewPager?.currentItem ?: 0
        val fragment = mFragmentList.getOrNull(currentPosition)
        if (fragment is IScrollable) {
            fragment.scrollToTop()
        }
        if (currentPosition == TAB_FOLLOW_INDEX || currentPosition == TAB_RECOMMEND_INDEX) {
            setPutQuestionButtonStatus(View.VISIBLE)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(skip: EBSkip) {
        if (skip.type == EB_TAB) {
            val tabPosition = skip.currentItem
            mBinding?.viewPager?.currentItem = tabPosition
        }
    }

    fun translateTopBg(y: Int) {
        mBinding?.run {
            if (viewPager.currentItem != TAB_RECOMMEND_INDEX) topBg.translationY = -y.toFloat()
            changeNavigationBg(y)
        }
    }

    private fun changeNavigationBg(y: Int = 0) {
        mBinding?.run {
            if (!mIsDarkModeOn && viewPager.currentItem != TAB_RECOMMEND_INDEX && y != 0) {
                if (navigationBg.drawable == null) {
                    navigationBg.setBackgroundColor(
                        if (viewPager.currentItem == TAB_FORUM_INDEX) {
                            com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext())
                        } else {
                            com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext())
                        }
                    )
                    navigationBg.setImageBitmap(mNavigationBitmap)
                }
            } else if (!mIsDarkModeOn && navigationBg.drawable != null) {
                navigationBg.setBackgroundColor(com.gh.gamecenter.common.R.color.transparent.toColor(requireContext()))
                navigationBg.setImageDrawable(null)
            } else if (viewPager.currentItem == TAB_RECOMMEND_INDEX || viewPager.currentItem == TAB_FOLLOW_INDEX) {
                navigationBg.setBackgroundColor(
                    if (mIsDarkModeOn && y > 0) com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()) else if (mIsDarkModeOn && y == 0) com.gh.gamecenter.common.R.color.ui_background.toColor(
                        requireContext()
                    ) else com.gh.gamecenter.common.R.color.transparent.toColor(requireContext())
                )
                navigationBg.setImageDrawable(null)
            } else if (mIsDarkModeOn) {
                navigationBg.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
                navigationBg.setImageDrawable(null)
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (isSupportVisible) DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn)
        mBinding?.tabLayout?.run {
            for (i in 0 until tabCount) {
                val tab: TabLayout.Tab? = getTabAt(i)
                if (tab != null) {
                    val tvTitle = tab.customView?.findViewById<TextView>(R.id.tab_title)
                    if (tvTitle != null && tvTitle.visibility == View.VISIBLE) {
                        tvTitle.post {
                            if (i == TAB_FOLLOW_INDEX && tab.isSelected) {
                                val resId = mViewModel?.followFilterStatus?.value
                                if (resId != null) {
                                    mViewModel?.updateFilterResId(resId)
                                }
                            }
                            tvTitle.setTextColor(
                                ColorStateList.valueOf(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                            )
                        }
                    }
                }
            }
        }
        mBinding?.run {
            root.setBackgroundColor(
                if (viewPager.currentItem == TAB_FORUM_INDEX) com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()) else com.gh.gamecenter.common.R.color.ui_background.toColor(
                    requireContext()
                )
            )
            topBg.run {
                visibleIf(!mIsDarkModeOn)
                post {
                    val bitmap = getBitmapFromView()
                    bitmap?.let {
                        mNavigationBitmap = Bitmap.createBitmap(
                            it,
                            0,
                            0,
                            it.width,
                            DisplayUtils.getStatusBarHeight(resources) + 52f.dip2px()
                        )
                    }
                }
            }
            searchIconIv.setImageResource(R.drawable.ic_column_search)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                searchIconIv.imageTintList = ColorStateList.valueOf(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
            }

            val csl = AppCompatResources.getColorStateList(requireContext(), com.gh.gamecenter.common.R.color.text_primary)
            val filter = SimpleColorFilter(csl.defaultColor)
            val keyPath = KeyPath("**")
            val callback = LottieValueCallback<ColorFilter>(filter)
            videoLottie.addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback)
        }

        followFilterPopWindow.onDarkModeChanged()


    }

    fun getTopBgView() = mBinding?.topBg

    fun setSuperiorChain(superiorChain: ISuperiorChain?): CommunityHomeFragment {
        this.mSuperiorChain = superiorChain
        return this
    }

    companion object {
        var TAB_SELECTED_COLOR: Int = com.gh.gamecenter.common.R.color.text_primary
        var TAB_DEFAULT_COLOR: Int = com.gh.gamecenter.common.R.color.community_forum_more
        var DEFAULT_TAB_TEXT_SIZE = 16F
        var DEFAULT_TAB_IMG_WIDTH = 34F.dip2px()
        var DEFAULT_TAB_IMG_HEIGHT = 16F.dip2px()
        const val EB_TAB = "forum_tab"
        const val TAB_FOLLOW_INDEX = 0
        const val TAB_RECOMMEND_INDEX = 1
        const val TAB_FORUM_INDEX = 2
        const val TAB_ACTIVITY_INDEX = 3
        const val ARTICLE_REQUEST_CODE = 200
        const val QUESTION_REQUEST_CODE = 201
        const val VIDEO_REQUEST_CODE = 202
        const val LAST_SELECTED_POSITION = "last_selected_position"
        const val EB_SHOW_QUESTION_BUTTON = "EB_SHOW_QUESTION_BUTTON"
        const val EB_HIDE_QUESTION_BUTTON = "EB_HIDE_QUESTION_BUTTON"

        private const val SOURCE_ENTRANCE = "社区"
    }
}