package com.gh.gamecenter.fragment

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.graphics.ColorUtils
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.gh.common.exposure.ExposureSource
import com.gh.common.util.DirectUtils
import com.gh.common.util.LogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.amway.AmwayFragment
import com.gh.gamecenter.catalog.CatalogFragment
import com.gh.gamecenter.category.CategoryDirectoryFragment
import com.gh.gamecenter.category2.CategoryV2Fragment
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.FragmentMainHomeWrapperBinding
import com.gh.gamecenter.databinding.TabItemMainBinding
import com.gh.gamecenter.discovery.DiscoveryFragment
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.entity.SubjectRecommendEntity
import com.gh.gamecenter.game.GameFragment
import com.gh.gamecenter.game.columncollection.detail.ColumnCollectionDetailFragment
import com.gh.gamecenter.game.commoncollection.detail.CommonCollectionDetailFragment
import com.gh.gamecenter.gamecollection.square.GameCollectionSquareFragment
import com.gh.gamecenter.home.HomeFragment
import com.gh.gamecenter.servers.GameServersPublishFragment
import com.gh.gamecenter.servers.GameServersTestFragment
import com.gh.gamecenter.subject.SubjectFragment
import com.google.android.material.appbar.AppBarLayout
import com.halo.assistant.fragment.WebFragment
import kotlin.math.abs

class HomeSearchToolWrapperFragment : SearchToolWrapperFragment() {

    private var mBinding: FragmentMainHomeWrapperBinding? = null
    private var mTabTitleList = arrayListOf<TextView>()

    private var mTabSelectedColor: Int = 0
    private var mTabDefaultColor: Int = 0

    private var mCurrentAppBarColor: Int = 0

    private var mIsDisplayingLightContent = false

    private var mDefaultSelectedTab = -1
    private var mLastSelectedPosition = 0

    private var mViewModel: HomeSearchToolWrapperViewModel? = null

    private var mFragmentList = ArrayList<Fragment>()

    private var mHomeTab: SubjectRecommendEntity? = null
    private var mHomeTabPosition = -1
    private var mOffsetCritical = 0.7F

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

        savedInstanceState?.let { mDefaultSelectedTab = it.getInt(LAST_SELECTED_POSITION) }
    }

    override fun onFragmentFirstVisible() {
        mViewModel = viewModelProviderFromParent()

        mSearchToolbarFragment =
            childFragmentManager.findFragmentById(R.id.wrapper_toolbar) as SearchToolbarFragment?
                ?: SearchToolbarFragment()
        mSearchToolbarFragment.with(Bundle().apply { putString(EntranceConsts.KEY_LOCATION, "首页") })

        setSearchHints()

        // 记录 appBarOffset 供其它子页面使用
        mBinding?.appbar?.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            mViewModel?.appBarOffset = abs(verticalOffset)
        })

        childFragmentManager.beginTransaction()
            .replace(R.id.wrapper_toolbar, mSearchToolbarFragment)
            .commitAllowingStateLoss()

        mViewModel?.tabs?.observe(viewLifecycleOwner) {
            if (mDefaultSelectedTab == -1) {
                mDefaultSelectedTab = mViewModel?.defaultTabPosition ?: 0
            }
            mHomeTab = it?.find { tab -> tab.type == "home" }
            mHomeTabPosition = it.indexOf(mHomeTab)
            initViewPager(it)

            // 当 tab 只有一个的时候隐藏顶部 tab 栏，停用 nestedScroll
            if (it.size == 1) {
                mBinding?.tabContainer?.visibility = View.GONE
                (mBinding?.collapsingToolbar?.layoutParams as? AppBarLayout.LayoutParams)?.let { lp ->
                    lp.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL
                }
            }

            mBinding?.noConnectionContainer?.reuseNoConnection?.visibility = View.GONE
            mBinding?.loadingContainer?.reuseLlLoading?.visibility = View.GONE
        }

        mViewModel?.error?.observe(viewLifecycleOwner) {
            mBinding?.noConnectionContainer?.reuseNoConnection?.visibility = View.VISIBLE
            mBinding?.loadingContainer?.reuseLlLoading?.visibility = View.GONE
            mBinding?.noConnectionContainer?.reuseNoConnection?.setOnClickListener {
                mViewModel?.getHomeContentUnion()
                mBinding?.noConnectionContainer?.reuseNoConnection?.visibility = View.GONE
                mBinding?.loadingContainer?.reuseLlLoading?.visibility = View.VISIBLE
            }
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()

        DisplayUtils.setLightStatusBar(requireActivity(), !mIsDisplayingLightContent && !mIsDarkModeOn)
    }

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

    override fun getInflatedLayout() =
        FragmentMainHomeWrapperBinding.inflate(layoutInflater).apply { mBinding = this }.root

    private fun initViewPager(tabList: ArrayList<SubjectRecommendEntity>) {
        val fragmentList = generateFragments(tabList).apply { mFragmentList = this }
        val tabTitleList = arrayListOf<String>()

        tabList.forEach { tabTitleList.add(it.name ?: "") }

        mBinding?.run {
            viewPager.offscreenPageLimit = fragmentList.size
            viewPager.doOnScroll(
                onPageSelected = { position ->
                    notifyChildFragmentLifecycle(position)
                    updateTabTextStyle(position, 0F)
                    mViewModel?.forumTabPairs?.forEach { pair ->
                        if (pair.first == position) {
                            DirectUtils.directForumDetail(requireContext(), pair.second, "首页")
                            viewPager.post { viewPager.currentItem = position - 1 }
                        }
                    }
                    mViewModel?.tabs?.value?.run {
                        this.safelyGetInRelease(position).let {
                            LogUtils.logHomeTopTabClick(it?.name, it?.type, it?.text, it?.link, position)
                            if (it?.type == "common_collection") {
                                NewLogUtils.logAccessToCommonCollectionDetail(it.link ?: "", it.text ?: "", "首页顶部Tab栏")
                            }
                        }
                    }
                },
                onPageScrolled = { position, positionOffset, _ ->
                    val backgroundWhiteColor = R.color.background_white.toColor(requireContext())
                    val backgroundColor = R.color.background.toColor(requireContext())
                    val amwayPrimaryColor = R.color.amway_primary_color.toColor(requireContext())
                    val tabDefaultLightColor = TAB_DEFAULT_COLOR_LIGHT.toColor(requireContext())
                    val tabSelectedColor = TAB_SELECTED_COLOR.toColor(requireContext())
                    val tabDefaultColor = TAB_DEFAULT_COLOR.toColor(requireContext())

                    if (position + 1 != mTabTitleList.size) {
                        var currentAppBarColor =
                            tabList.safelyGetInRelease(position)?.primaryColor ?: backgroundWhiteColor
                        var incomingAppBarColor =
                            tabList.safelyGetInRelease(position + 1)?.primaryColor ?: backgroundWhiteColor

                        if (mIsDarkModeOn && currentAppBarColor == Color.WHITE) {
                            currentAppBarColor = backgroundWhiteColor
                        }
                        if (mIsDarkModeOn && incomingAppBarColor == Color.WHITE) {
                            incomingAppBarColor = backgroundWhiteColor
                        }
                        if (mFragmentList.isNotEmpty() && mFragmentList.safelyGetInRelease(position) is AmwayFragment) {
                            currentAppBarColor = if (mIsDarkModeOn) backgroundColor else amwayPrimaryColor
                            tabList.safelyGetInRelease(position)?.currentSelectColor = currentAppBarColor
                        }
                        if (mFragmentList.isNotEmpty() && mFragmentList.safelyGetInRelease(position + 1) is AmwayFragment) {
                            incomingAppBarColor = if (mIsDarkModeOn) backgroundColor else amwayPrimaryColor
                        }

                        val proximatelySelectedPosition =
                            if (positionOffset < 0.5) position else position + 1

                        val appBarColorInBetween = if (currentAppBarColor == incomingAppBarColor) {
                            currentAppBarColor
                        } else {
                            ColorUtils.blendARGB(currentAppBarColor, incomingAppBarColor, positionOffset)
                        }

                        // 颜色显示是否变更
                        val isContentStyleChanged =
                            tabList.safelyGetInRelease(proximatelySelectedPosition)?.useLightStyle != mIsDisplayingLightContent
                        mIsDisplayingLightContent =
                            tabList.safelyGetInRelease(proximatelySelectedPosition)?.useLightStyle ?: false

                        mTabSelectedColor = if (mIsDisplayingLightContent) tabDefaultLightColor else tabSelectedColor
                        mTabDefaultColor = if (mIsDisplayingLightContent) tabDefaultLightColor else tabDefaultColor

                        if (isContentStyleChanged) {
                            updateIndicatorDrawable()
                            DisplayUtils.setLightStatusBar(
                                requireActivity(),
                                !mIsDisplayingLightContent && !mIsDarkModeOn
                            )
                        }

                        mTabTitleList[position].run {
                            textSize = (DEFAULT_TAB_TEXT_SIZE + ((1 - positionOffset) * 4)).roundTo(1)
                            setTextColor(ColorUtils.blendARGB(mTabDefaultColor, mTabSelectedColor, 1 - positionOffset))
                        }
                        mTabTitleList[position + 1].run {
                            textSize = (DEFAULT_TAB_TEXT_SIZE + ((positionOffset) * 4)).roundTo(1)
                            setTextColor(ColorUtils.blendARGB(mTabDefaultColor, mTabSelectedColor, positionOffset))
                        }

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

                        mCurrentAppBarColor = appBarColorInBetween
                        updateAppBarStyle(appBarColorInBetween, mIsDisplayingLightContent)
                    } else {
                        var currentAppBarColor =
                            tabList.safelyGetInRelease(position)?.primaryColor ?: backgroundWhiteColor
                        if (mIsDarkModeOn && currentAppBarColor == Color.WHITE) {
                            currentAppBarColor = backgroundWhiteColor
                        }
                        if (mFragmentList.isNotEmpty() && mFragmentList.safelyGetInRelease(position) is AmwayFragment) {
                            currentAppBarColor = if (mIsDarkModeOn) backgroundColor else amwayPrimaryColor
                            tabList.safelyGetInRelease(position)?.currentSelectColor = currentAppBarColor
                        }
                        mIsDisplayingLightContent = tabList.safelyGetInRelease(position)?.useLightStyle == true
                        mTabSelectedColor =
                            if (mIsDisplayingLightContent) tabDefaultLightColor else tabSelectedColor
                        mTabDefaultColor =
                            if (mIsDisplayingLightContent) tabDefaultLightColor else tabDefaultColor

                        updateAppBarStyle(currentAppBarColor, mIsDisplayingLightContent)
                        updateIndicatorDrawable()
                        DisplayUtils.setLightStatusBar(requireActivity(), !mIsDisplayingLightContent && !mIsDarkModeOn)
                    }

                    updateTabTextStyle(position, positionOffset)
                }
            )

            // 设置默认 position 避免 position 为 0 的 fragment 被先加载显示再跳转至具体页面
            tryCatchInRelease {
                val field = ViewPager::class.java.getDeclaredField("mRestoredCurItem")
                field.isAccessible = true
                field.set(viewPager, mDefaultSelectedTab)
                mLastSelectedPosition = mDefaultSelectedTab
            }
            viewPager.adapter =
                FragmentAdapter(childFragmentManager, fragmentList, tabTitleList)
            tabLayout.setupWithViewPager(mBinding?.viewPager)
            indicatorView.setupWithTabLayout(mBinding?.tabLayout)
            indicatorView.setupWithViewPager(mBinding?.viewPager)
            indicatorView.setIndicatorWidth(18)
            for (i in 0 until mBinding?.tabLayout?.tabCount!!) {
                val tab = mBinding?.tabLayout?.getTabAt(i) ?: continue
                val tabTitle = if (tab.text != null) tab.text.toString() else ""
                val tabViewBinding = generateTabView(tabTitle)
                mTabTitleList.add(tabViewBinding.tabTitle)
                tab.customView = tabViewBinding.root
                tab.view.setPadding(0, 0, 0, 0)
                if (i == 0) {
                    tab.view.layoutParams =
                        (tab.view.layoutParams as LinearLayout.LayoutParams).apply { setMargins(10F.dip2px(), 0, 0, 0) }
                }
                if (i == mBinding?.tabLayout?.tabCount!! - 1) {
                    tab.view.layoutParams =
                        (tab.view.layoutParams as LinearLayout.LayoutParams).apply { setMargins(0, 0, 10F.dip2px(), 0) }
                }
            }
        }
    }

    private fun updateIndicatorDrawable() {
        mBinding?.run {
            if (mIsDisplayingLightContent) {
                indicatorView.updateIndicatorDrawable(R.drawable.ic_home_tab_indicator_white.toDrawable(requireContext()))
            } else {
                indicatorView.updateIndicatorDrawable(R.drawable.ic_commodity_selected.toDrawable(requireContext()))
            }
        }
    }

    fun onScrollChanged(totalHeight: Int, offset: Int) {
        val currentTab = getCurrentTab()
        val backgroundWhiteColor = R.color.background_white.toColor(requireContext())
        val backgroundColor = R.color.background.toColor(requireContext())
        val amwayPrimaryColor = R.color.amway_primary_color.toColor(requireContext())
        val tabDefaultLightColor = TAB_DEFAULT_COLOR_LIGHT.toColor(requireContext())
        val tabSelectedColor = TAB_SELECTED_COLOR.toColor(requireContext())
        val tabDefaultColor = TAB_DEFAULT_COLOR.toColor(requireContext())

        currentTab?.offsetRatio = offset / totalHeight.toFloat()
        if ((currentTab?.isTopViewShow == true && offset >= totalHeight)
            || currentTab?.isSlideEmpty == true
        ) {
            currentTab.isTopViewShow = false
            currentTab.primaryColor = backgroundWhiteColor
            currentTab.useLightStyle = false
            mIsDisplayingLightContent = false
            updateAppBarColorWhenScrollChanged(backgroundWhiteColor)
            DisplayUtils.setLightStatusBar(requireActivity(), !mIsDisplayingLightContent && !mIsDarkModeOn)
            mTabSelectedColor = TAB_SELECTED_COLOR.toColor(requireContext())
            mTabDefaultColor = TAB_DEFAULT_COLOR.toColor(requireContext())
            mBinding?.indicatorView?.updateIndicatorDrawable(R.drawable.ic_commodity_selected.toDrawable())
            updateTabTextStyle(mLastSelectedPosition, 0f)
        } else if (offset < totalHeight) {
            var currentSelectColor = currentTab?.currentSelectColor ?: 0
            val offsetMeetsCriticalPoint = (currentTab?.offsetRatio ?: 0f) < mOffsetCritical
            currentTab?.isTopViewShow = true
            if (mFragmentList.isNotEmpty()
                && mFragmentList.safelyGetInRelease(mBinding?.viewPager?.currentItem ?: 0) is AmwayFragment
            ) {
                currentSelectColor = if (mIsDarkModeOn) backgroundColor else amwayPrimaryColor
            }
            val colorInBetween =
                ColorUtils.blendARGB(currentSelectColor, backgroundWhiteColor, currentTab?.offsetRatio ?: 0f)
            updateAppBarColorWhenScrollChanged(colorInBetween)
            currentTab?.primaryColor = colorInBetween
            currentTab?.useLightStyle = offsetMeetsCriticalPoint
            currentTab?.primaryColor = colorInBetween
            currentTab?.useLightStyle = offsetMeetsCriticalPoint
            if (mIsDisplayingLightContent != currentTab?.useLightStyle) {
                mIsDisplayingLightContent = offsetMeetsCriticalPoint
            }
            DisplayUtils.setLightStatusBar(requireActivity(), !mIsDisplayingLightContent && !mIsDarkModeOn)
            mTabSelectedColor = if (offsetMeetsCriticalPoint) tabDefaultLightColor else tabSelectedColor
            mTabDefaultColor = if (offsetMeetsCriticalPoint) tabDefaultLightColor else tabDefaultColor
            mBinding?.indicatorView?.updateIndicatorDrawable(
                if (offsetMeetsCriticalPoint)
                    R.drawable.ic_home_tab_indicator_white.toDrawable()
                else
                    R.drawable.ic_commodity_selected.toDrawable()
            )
            updateTabTextStyle(mLastSelectedPosition, 0f)
        }
    }

    private fun updateAppBarColorWhenScrollChanged(color: Int) {
        val currentTab = getCurrentTab()
        if ((currentTab?.offsetRatio ?: 0f) >= 1f && color != R.color.background_white.toColor(requireContext())) {
            currentTab?.currentSelectColor = color
            currentTab?.primaryColor = color
        }
        updateAppBarStyle(color, color != R.color.background_white.toColor(requireContext()))
    }

    fun changeAppBarColor(color: Int) {
        val currentTab = getCurrentTab()
        //此处的判断是防止banner在滑动过程中切换tab会导致背景设置错误
        if (currentTab?.type != "home") {
            val homeTab = mViewModel?.tabs?.value?.safelyGetInRelease(mHomeTabPosition)
            homeTab?.currentSelectColor = color
            if (homeTab?.isTopViewShow == true) {
                val colorInBetween =
                    ColorUtils.blendARGB(color, R.color.background_white.toColor(requireContext()), homeTab.offsetRatio)
                homeTab.primaryColor = colorInBetween
            }
        } else {
            currentTab.currentSelectColor = color
            if (currentTab.isTopViewShow) {
                val colorInBetween =
                    ColorUtils.blendARGB(
                        color,
                        R.color.background_white.toColor(requireContext()),
                        currentTab.offsetRatio
                    )
                currentTab.primaryColor = colorInBetween
                updateAppBarStyle(colorInBetween, colorInBetween != R.color.background_white.toColor(requireContext()))
            }
        }
    }

    fun getCurrentTab(): SubjectRecommendEntity? {
        return if (mBinding?.viewPager != null) {
            val currentItem = mBinding?.viewPager?.currentItem ?: -1
            mViewModel?.tabs?.value?.safelyGetInRelease(currentItem)
        } else null
    }

    private fun notifyChildFragmentLifecycle(currentSelectedPosition: Int) {
        tryWithDefaultCatch {
            // 补充 Viewpager Fragment 的生命周期， 先调用旧选中 fragment 的 onPause 再当前的 onResume
            // 避免部分被内嵌的 Fragment 不能正常运作
            if (mFragmentList.size > mLastSelectedPosition) {
                val fragment: Fragment = mFragmentList[mLastSelectedPosition]
                if (!fragment.isAdded) return

                fragment.onPause()
                val childFragmentManager = fragment.childFragmentManager
                val fragments = childFragmentManager.fragments
                for (childFragment in fragments) {
                    childFragment.onPause()
                }
            }
            if (mFragmentList.size > currentSelectedPosition) {
                val fragment: Fragment = mFragmentList[currentSelectedPosition]
                if (!fragment.isAdded) return

                fragment.onResume()
                val childFragmentManager = fragment.childFragmentManager
                val fragments = childFragmentManager.fragments
                for (childFragment in fragments) {
                    childFragment.onResume()
                }
            }
            mLastSelectedPosition = currentSelectedPosition
        }
    }

    private fun generateFragments(tabList: ArrayList<SubjectRecommendEntity>): ArrayList<Fragment> {
        val fragmentList = arrayListOf<Fragment>()
        for ((index, tab) in tabList.withIndex()) {
            val fragment = when (tab.type) {
                "home" -> HomeFragment().with(Bundle())
                "top_game_comment" -> AmwayFragment().with(Bundle())
                "block" -> GameFragment().with(Bundle().apply {
                    putParcelable(EntranceConsts.KEY_BLOCK_DATA, tab)
                })
                "server" -> GameServersPublishFragment().with(Bundle())
                "game_list" -> GameCollectionSquareFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_ENTRANCE, "顶部tab")
                    putInt(EntranceConsts.KEY_TAB_INDEX, index)
                    putString(EntranceConsts.KEY_NAME, tab.name)
                })
                "column_test" -> GameServersTestFragment().with(Bundle().apply {
                    putString(GameServersTestFragment.TEST_COLUMN_ID, tab.link)
                })
                "category" -> CategoryDirectoryFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_CATEGORY_ID, tab.link)
                    putString(EntranceConsts.KEY_CATEGORY_TITLE, tab.text)
                })
                "catalog" -> CatalogFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_CATALOG_ID, tab.link)
                    putString(EntranceConsts.KEY_CATALOG_TITLE, tab.text)
                })
                "category_v2" -> CategoryV2Fragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_CATEGORY_ID, tab.link)
                    putString(EntranceConsts.KEY_CATEGORY_TITLE, tab.text)
                })
                "ranking", "column_collection" -> ColumnCollectionDetailFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_ENTRANCE, "首页")
                    putString(EntranceConsts.KEY_COLLECTION_ID, tab.link)
                    putInt(EntranceConsts.KEY_POSITION, 0)
                    putString(EntranceConsts.KEY_COLUMNNAME, tab.text)
                    putBoolean(EntranceConsts.KEY_IS_COLUMN_COLLECTION, true)
                })
                "column" -> SubjectFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_ENTRANCE, "首页")
                    putParcelable(
                        EntranceConsts.KEY_SUBJECT_DATA,
                        SubjectData(tab.link, tab.text, false)
                    )
                })
                "web" -> WebFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_URL, tab.link)
                    putString(EntranceConsts.KEY_ENTRANCE, "首页tab")
                    putBoolean(WebFragment.KEY_OPEN_NATIVE_PAGE, false)
                    putBoolean(WebFragment.KEY_ENABLE_HORIZONTAL_SCROLL_DISPATCH, true)
                    if (tab.link?.contains("leave_web_page_handle_back_pressed=true") == true) {
                        putBoolean(WebFragment.KEY_LEAVE_WEB_PAGE_TO_HANDLE_BACK_PRESSED, true)
                    }
                })
                "common_collection" -> CommonCollectionDetailFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_ENTRANCE, "首页顶部Tab栏")
                    putString(EntranceConsts.KEY_COLLECTION_ID, tab.link)
                    putString(EntranceConsts.KEY_COLUMNNAME, tab.text)
                })
                "explore_column" -> DiscoveryFragment().with(Bundle().apply {
                    putString(EntranceConsts.KEY_ENTRANCE, "首页")
                    putInt(EntranceConsts.KEY_POSITION, index)
                })
                "bbs" -> Fragment()
                else -> Fragment()
            }
            fragment.arguments?.putInt(EntranceConsts.KEY_TAB_COUNT, tabList.size)
            fragment.arguments?.putBoolean(EntranceConsts.KEY_IS_HOME, true)
            fragment.arguments?.putParcelable(
                EntranceConsts.KEY_EXPOSURE_SOURCE,
                ExposureSource("首页顶部Tab栏", tab.name ?: "")
            )
            fragmentList.add(fragment)
        }
        return fragmentList
    }

    /**
     * 更新所有 tab 栏的文字 style
     */
    private fun updateTabTextStyle(selectedPosition: Int, positionOffset: Float) {
        for ((index, titleTv) in mTabTitleList.withIndex()) {
            if (index == selectedPosition) {
                titleTv.setTextColor(mTabSelectedColor)
                if (positionOffset == 0F) {
                    titleTv.setTypeface(null, Typeface.NORMAL)
                    titleTv.setTypeface(titleTv.typeface, Typeface.BOLD)
                }
            } else {
                titleTv.setTextColor(mTabDefaultColor)
                if (positionOffset == 0F) {
                    titleTv.setTypeface(null, Typeface.NORMAL)
                }
            }
        }
    }

    /**
     * 更新 AppBar 的控件 style
     */
    private fun updateAppBarStyle(color: Int, useLightStyle: Boolean) {
        mBinding?.appbar?.setBackgroundColor(color)
        mBinding?.statusBar?.setBackgroundColor(color)
        mBinding?.tabContainer?.setBackgroundColor(color)

        mSearchToolbarFragment.updateStyle(mIsDarkModeOn || useLightStyle)
    }

    private fun generateTabView(title: String): TabItemMainBinding {
        val binding = TabItemMainBinding.inflate(LayoutInflater.from(requireContext()))
        binding.tabTitle.run {
            text = title
            textSize = DEFAULT_TAB_TEXT_SIZE
            setTextColor(mTabDefaultColor)
        }
        binding.invisibleTabTitle.run {
            text = title
            textSize = DEFAULT_TAB_TEXT_SIZE
        }
        return binding
    }

    override fun onBackPressed(): Boolean {
        mBinding?.viewPager?.run {
            if (mFragmentList.isNotEmpty() && mFragmentList.safelyGetInRelease(currentItem) is WebFragment) {
                return (mFragmentList.safelyGetInRelease(currentItem) as WebFragment).onBackPressed()
            }
        }
        return super.onBackPressed()
    }

    private fun updateTabAndToolbarStyle() {
        mViewModel?.tabs?.value?.forEach {
            if (it.type != "top_game_comment") {
                it.primaryColor = R.color.background_white.toColor(requireContext())
            }
        }
        mBinding?.viewPager?.currentItem?.let {
            if (it < mFragmentList.size) {
                when (mFragmentList[it]) {
                    is HomeFragment -> (mFragmentList[it] as HomeFragment).onScrollChanged()
                    is AmwayFragment -> (mFragmentList[it] as AmwayFragment).onScrollChanged()
                    else -> onScrollChanged(0, 0)
                }
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        getCurrentTab()?.isTopViewShow = true
        updateTabAndToolbarStyle()
    }

    companion object {
        const val LAST_SELECTED_POSITION = "last_selected_position"

        var TAB_SELECTED_COLOR: Int = R.color.text_title
        var TAB_DEFAULT_COLOR: Int = R.color.text_subtitle

        var TAB_DEFAULT_COLOR_LIGHT: Int = R.color.search_text_color_light

        var DEFAULT_TAB_TEXT_SIZE = 16F
    }

}