package com.gh.gamecenter.home.custom.adapter

import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.game.GameAndPosition
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.model.*
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_ACCELERATOR_RECENT_PLAYED
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_AMWAY_WALL
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COLLECTION_REFRESH_ICON_LANE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COLLECTION_REFRESH_ICON_MATRIX
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COLLECTION_REFRESH_SLIDE_LIST
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_ANNOUNCEMENT_BANNER
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_BANNER
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_BANNER_WITH_CARDS
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_CONTENT_LABEL_LANE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_HORIZONTAL_SLIDE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_NOTIFICATION_COLUMN
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_RECOMMEND_CARD
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_COMMON_VERTICAL_TWO_CARDS
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_CONTENT_CARD
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_DISCOVER
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_DOUBLE_GAME_WELFARE_CARD
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_DOUBLE_ROW
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_FOOTER
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_FOLD_SLIDE_LARGE_IMAGE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_HOME_GAME_ITEM
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_GALLERY_SLIDE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_ICON_LANE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_STATIC_GALLERY
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_TIME_LINE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_ICON_MATRIX
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_LONG_LIST
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_VERTICAL_IMAGE_TEXT
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_GAME_VERTICAL_SLIDE
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_HORIZONTAL_SLIDE_VIDEO_LIST
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_MINI_GAME_RECENT_PLAY
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_NAVIGATION
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_NEW_GAME_TEST
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_PK
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_PLUGIN
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_RANK_COLLECTION
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_RECENT_PLAY
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_RECOMMEND
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_SINGLE_GAME_CARD
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_SUBJECT_COLLECTION_BANNER
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_SUBJECT_COLLECTION_HORIZONTAL_SLIDE_LARGE_CARD
import com.gh.gamecenter.home.custom.model.CustomPageItem.Companion.CUSTOM_PAGE_ITEM_TYPE_SUBJECT_COLLECTION_HORIZONTAL_SLIDE_SMALL_CARD
import com.gh.gamecenter.home.custom.viewholder.*
import com.gh.gamecenter.home.video.ScrollCalculatorHelper
import com.lightgame.download.DownloadEntity

class CustomPageAdapter(
    private val viewModel: CustomPageViewModel,
    private val lifecycleOwner: LifecycleOwner,
    private val scrollCalculatorHelper: ScrollCalculatorHelper,
) : ListAdapter<CustomPageItem, BaseCustomViewHolder>(CALLBACK), IGameChangedNotifier {

    private var loadStatus: LoadStatus? = null

    private var recyclerView: RecyclerView? = null

    /**
     * 记录第一个显示的 itemView 的位置
     * note：由于组件中可能在第一个位置配置了 va最近在玩 qq小游戏最近在玩 微信小游戏最近在玩 加速-最近在玩
     * 当后台配置了这几个组件时，用户还没有玩过游戏，这几个组件会加入到显示列表中，由于还没有数据，ItemView处于隐藏状态
     * 所以：使用 viewHolder.bindingAdapterPosition == 0 来判断是否是第一个组件时会出现不准的情况
     */
    private val _firstShowPosition = MutableLiveData<Int>().apply {
        value = 0
    }
    val firstShowPosition: LiveData<Int> = _firstShowPosition

    override fun submitList(list: List<CustomPageItem>?, commitCallback: Runnable?) {
        val dataWithFooter = if (list.isNullOrEmpty()) {
            ArrayList(list)
        } else {
            list + CustomFooterItem
        }
        super.submitList(dataWithFooter, commitCallback)
    }

    /**
     * 查找第一个出现的组件 在 data 中的位置
     * 请注意：这里的 return 不能删除
     */
    fun updateFirstItemId() {
        currentList.forEachIndexed { index, item ->
            when (item) {
                is CustomRecentGamesItem -> {
                    if (item.data.isNotEmpty()) {
                        _firstShowPosition.value = index
                        return
                    }
                }

                is CustomRecentWeChatMiniGamesItem -> {
                    if (item.data.isNotEmpty()) {
                        _firstShowPosition.value = index
                        return
                    }
                }

                is CustomRecentQqMiniGamesItem -> {
                    if (item.data.isNotEmpty()) {
                        _firstShowPosition.value = index
                        return
                    }
                }

                is CustomRecentAcceleratorItem -> {
                    if (item.data.isNotEmpty()) {
                        _firstShowPosition.value = index
                        return
                    }
                }

                else -> {
                    _firstShowPosition.value = index
                    return
                }
            }
        }
    }

    /**
     * 由于 loadMore 是在 OnScrollListener 中触发的，当调用notifyItemChanged时，会引发警告，并且本地通知刷新无效
     * warn message:
     * Cannot call this method in a scroll callback.
     * Scroll callbacks mightbe run during a measure & layout pass where you cannot change theRecyclerView data.
     * Any method call that might change the structureof the RecyclerView or the adapter contents should be postponed tothe next frame.
     * 所以，需要在post之后调用notifyItemChanged
     */
    fun setLoadStatus(status: LoadStatus) {
        loadStatus = status
        recyclerView?.post {
            notifyItemChanged(itemCount - 1)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return getItem(position).itemType
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseCustomViewHolder =
        when (viewType) {
            CUSTOM_PAGE_ITEM_TYPE_DOUBLE_ROW -> CustomDoubleCardViewHolder(viewModel, parent.toBinding())
            CUSTOM_PAGE_ITEM_TYPE_HORIZONTAL_SLIDE_VIDEO_LIST ->
                CustomHomeHorizontalSlideVideoListViewHolder(
                    viewModel,
                    scrollCalculatorHelper,
                    parent.toBinding()
                )

            CUSTOM_PAGE_ITEM_TYPE_GAME_LONG_LIST ->
                CustomGameItemViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_GAME_VERTICAL_SLIDE ->
                CustomGameVerticalSlideViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_GAME_ICON_MATRIX ->
                CustomIconMatrixViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_TIME_LINE, CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_ICON_LANE ->
                CustomGameHorizontalSlideListViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_STATIC_GALLERY ->
                CustomGameGalleryViewHolder(
                    viewModel,
                    CustomGameGalleryViewHolder.GameGalleryItemCell(parent.context).apply { inflate() }
                )

            CUSTOM_PAGE_ITEM_TYPE_GAME_HORIZONTAL_GALLERY_SLIDE ->
                CustomGameGallerySlideViewHolder(viewModel, parent.toBinding(), lifecycleOwner)

            CUSTOM_PAGE_ITEM_TYPE_GAME_FOLD_SLIDE_LARGE_IMAGE ->
                CustomFoldSlideLargeImageViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_GAME_HOME_GAME_ITEM ->
                CustomHomeGameItemViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_RANK_COLLECTION ->
                CustomRankCollectionViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_SUBJECT_COLLECTION_HORIZONTAL_SLIDE_LARGE_CARD ->
                CustomHomeGameCollectionSlideViewHolder(true, viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_SUBJECT_COLLECTION_HORIZONTAL_SLIDE_SMALL_CARD ->
                CustomHomeGameCollectionSlideViewHolder(false, viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_SUBJECT_COLLECTION_BANNER -> {
                CustomHomeGameCollectionCarouselViewHolder(viewModel, lifecycleOwner, parent.toBinding())
            }

            CUSTOM_PAGE_ITEM_TYPE_RECENT_PLAY -> {
                CustomHomeRecentVGameViewHolder(true, viewModel, parent.toBinding())
            }

            CUSTOM_PAGE_ITEM_TYPE_PLUGIN -> {
                CustomGamePluginViewHolder(true, viewModel, parent.toBinding())
            }

            CUSTOM_PAGE_ITEM_TYPE_NEW_GAME_TEST -> {
                CustomHomeItemGameTestV2ViewHolder(viewModel, lifecycleOwner, parent.toBinding())
            }

            CUSTOM_PAGE_ITEM_TYPE_DISCOVER ->
                CustomHomeDiscoverCardViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_CONTENT_CARD ->
                CustomBigImageRecommendViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_AMWAY_WALL ->
                CustomHomeAmwayListViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COMMON_BANNER ->
                CustomHomeSlideListViewHolder(
                    viewModel,
                    lifecycleOwner,
                    parent.toBinding()
                )

            CUSTOM_PAGE_ITEM_TYPE_COMMON_BANNER_WITH_CARDS ->
                CustomHomeSlideWithCardsViewHolder(
                    viewModel,
                    lifecycleOwner,
                    parent.toBinding()
                )

            CUSTOM_PAGE_ITEM_TYPE_NAVIGATION ->
                CustomNavigationViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_RECOMMEND ->
                CustomHomeRecommendItemViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COMMON_HORIZONTAL_SLIDE ->
                CustomCommonCollectionViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COMMON_VERTICAL_TWO_CARDS ->
                CustomCommonCollection12ViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COLLECTION_REFRESH_ICON_LANE ->
                CustomRefreshIconViewHolder(parent.context, viewModel, false, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COLLECTION_REFRESH_ICON_MATRIX ->
                CustomRefreshIconViewHolder(parent.context, viewModel, true, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COLLECTION_REFRESH_SLIDE_LIST ->
                CustomGameCollectionRefreshVerticalSlideViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COMMON_CONTENT_LABEL_LANE ->
                ContentLabelLaneViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COMMON_NOTIFICATION_COLUMN ->
                NotificationColumnViewHolder(viewModel, lifecycleOwner, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_MINI_GAME_RECENT_PLAY -> CustomHomeRecentMiniGameViewHolder(
                viewModel,
                parent.toBinding()
            )

            CUSTOM_PAGE_ITEM_TYPE_COMMON_ANNOUNCEMENT_BANNER ->
                CustomAnnouncementBannerViewHolder(viewModel, lifecycleOwner, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_COMMON_RECOMMEND_CARD ->
                CustomRecommendCardViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_SINGLE_GAME_CARD ->
                CustomSingleGameCardViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_DOUBLE_GAME_WELFARE_CARD ->
                CustomDoubleWelfareCardViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_GAME_VERTICAL_IMAGE_TEXT ->
                CustomGameVerticalImageTextViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_ACCELERATOR_RECENT_PLAYED -> {
                CustomRecentAcceleratorViewHolder(viewModel, parent.toBinding())
            }

            CUSTOM_PAGE_ITEM_TYPE_FOOTER -> CustomFooterViewHolder(viewModel, parent.toBinding())

            CUSTOM_PAGE_ITEM_TYPE_PK -> CustomPKItemViewHolder(viewModel, lifecycleOwner, parent.toBinding())

            else -> InvalidViewHolder(viewModel, parent.toBinding())
        }

    override fun onBindViewHolder(holder: BaseCustomViewHolder, position: Int) = Unit

    override fun onBindViewHolder(holder: BaseCustomViewHolder, position: Int, payloads: MutableList<Any>) {
        val item = getItem(position)
        when (holder) {
            is CustomDoubleCardViewHolder -> holder.bindView(item)

            is CustomHomeHorizontalSlideVideoListViewHolder -> holder.bindView(item)

            is CustomGameItemViewHolder -> holder.bindView(item, this)

            is CustomGameVerticalSlideViewHolder -> holder.bindView(item)

            is CustomIconMatrixViewHolder -> holder.bindView(item)

            is CustomGameHorizontalSlideListViewHolder -> holder.bindView(item)

            is CustomGameGalleryViewHolder -> holder.bindView(item)

            is CustomGameGallerySlideViewHolder -> holder.bindView(item)

            is CustomFoldSlideLargeImageViewHolder -> holder.bindView(item)

            is CustomHomeGameItemViewHolder -> holder.bindView(item, position, this)

            is CustomRankCollectionViewHolder -> holder.bindView(item)

            is CustomHomeGameCollectionSlideViewHolder -> holder.bindView(item)

            is CustomHomeGameCollectionCarouselViewHolder -> holder.bindView(item)

            is CustomHomeRecentVGameViewHolder -> holder.bindView(item)

            is CustomGamePluginViewHolder -> holder.bindView(item) {
                notifyItemChanged(position)
            }

            is CustomHomeItemGameTestV2ViewHolder -> holder.bindView(item, position)

            is CustomHomeDiscoverCardViewHolder -> holder.bindView(item, position)

            is CustomBigImageRecommendViewHolder -> holder.bindView(item)

            is CustomHomeAmwayListViewHolder -> holder.bindView(item)

            is CustomHomeSlideListViewHolder -> holder.bindView(item)

            is CustomHomeSlideWithCardsViewHolder -> holder.bindView(item)

            is CustomNavigationViewHolder -> holder.bindView(item)

            is CustomHomeRecommendItemViewHolder -> holder.bindView(item)

            is CustomCommonCollectionViewHolder -> holder.bindView(item)

            is CustomCommonCollection12ViewHolder -> holder.bindView(item)

            is CustomRefreshIconViewHolder -> holder.bindView(item)

            is CustomHomeRecentMiniGameViewHolder -> holder.bindView(item)

            is CustomGameCollectionRefreshVerticalSlideViewHolder -> holder.bindView(item)

            is ContentLabelLaneViewHolder -> holder.bindView(item)

            is NotificationColumnViewHolder -> holder.bindView(item)

            is CustomAnnouncementBannerViewHolder -> holder.bindView(item)

            is CustomRecommendCardViewHolder -> holder.bindView(item)

            is CustomSingleGameCardViewHolder -> holder.bindView(item, this)

            is CustomDoubleWelfareCardViewHolder -> holder.bindView(item)

            is CustomFooterViewHolder -> holder.initFooterViewHolder(
                loadStatus == LoadStatus.LIST_LOADING,
                loadStatus == LoadStatus.LIST_FAILED,
                loadStatus == LoadStatus.LIST_OVER,
                R.string.load_over_with_click_hint
            ) {
                if (loadStatus == LoadStatus.LIST_OVER) {
                    recyclerView?.scrollToPosition(0)
                } else if (loadStatus == LoadStatus.LIST_FAILED) {
                    viewModel.onLoadMore()
                    notifyItemChanged(itemCount - 1)
                }
            }

            else -> holder.bindView(item)
        }
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        this.recyclerView = recyclerView
        recyclerView.addOnScrollListener(onLoadMoreListener)
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        recyclerView.removeOnScrollListener(onLoadMoreListener)
        this.recyclerView = null
    }

    override fun onViewAttachedToWindow(holder: BaseCustomViewHolder) {
        holder.onViewAttach(recyclerView)
    }

    override fun onViewDetachedFromWindow(holder: BaseCustomViewHolder) {
        holder.onViewDetach(recyclerView)
    }

    override fun notifyDownload(download: DownloadEntity) {
        val data = getGameEntityByPackage(download.packageName)
        data.forEach { (game, position, _) ->
            if (game != null && game.name == download.name) {
                game.getEntryMap()[download.platform] = download
            }
            checkIfOnlyNotifyItemChanged(position) {
                it.notifyDownload(download)
            }
        }
    }

    /**
     * 更新 游戏下载被删除 事件
     */
    override fun notifyDownloadDeleted(status: EBDownloadStatus) {
        val data = getGameEntityByPackage(status.packageName)
        data.forEach { (game, position, _) ->
            if (game != null && game.name == status.name) {
                game.getEntryMap().remove(status.platform)
            }
            checkIfOnlyNotifyItemChanged(position) {
                it.notifyDownloadDeleted(status)
            }
        }
    }

    override fun notifyInstalled(busFour: EBPackage) {
        val data = getGameEntityByPackage(busFour.packageName)
        data.forEach { (_, position, _) ->
            checkIfOnlyNotifyItemChanged(position) {
                it.notifyInstalled(busFour)
            }
        }
    }

    private fun checkIfOnlyNotifyItemChanged(position: Int, block: (IGameChangedNotifier) -> Unit) {
        val viewHolder = recyclerView?.findViewHolderForAdapterPosition(position)
        if (viewHolder is BaseCustomViewHolder) {
            if (viewHolder.onlyNotifyItemChanged) {
                notifyItemChanged(position)
            } else {
                block(viewHolder)
            }
        } else {
            // 当 RecyclerView 中没有找到对应的 ViewHolder 时，尝试调用 notifyItemChanged 来通知更新
            // 这可能是因为 ViewHolder 已经被回收或不在屏幕上。在这种情况下，我们仍然希望更新数据
            // 但是这并不能保证些什么，因为 ViewHolder 可能已经被销毁
            recyclerView?.adapter?.notifyItemChanged(position)
        }
    }

    fun getGameEntityByPackage(packageName: String): List<GameAndPosition> {
        val positionMap = viewModel.gamePositionAndPackageHelper.positionAndPackageMap
        return positionMap.entries
            .filter { (key, position) ->
                key.contains(packageName) && position < itemCount
            }
            .flatMap { (_, position) ->
                when (val item = getItem(position)) {
                    is CustomRecentGamesItem -> {
                        item.data.map {
                            GameAndPosition(null, position)
                        }
                    }

                    is CustomGameTestV2Item -> {
                        val positionList = ArrayList<GameAndPosition>()
                        viewModel.getNewGameTestUserCase(item.link.link ?: "none")
                            .getDataListLiveData().value?.forEach { gameDataWrapper ->
                                val gameEntity = gameDataWrapper.gameData
                                if (gameEntity != null) {
                                    for (apkEntity in gameEntity.getApk()) {
                                        if (apkEntity.packageName == packageName) {
                                            positionList.add(GameAndPosition(gameEntity, position))
                                        }
                                    }
                                }
                            }
                        positionList
                    }

                    else -> {
                        item.showDownloadGames.map { game ->
                            GameAndPosition(game, position)
                        }
                    }
                }
            }
    }


    private val onLoadMoreListener = object : OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val layoutManger = recyclerView.layoutManager
            if (layoutManger is LinearLayoutManager) {
                val lastVisibleItemPosition = layoutManger.findLastVisibleItemPosition()
                if (lastVisibleItemPosition == itemCount - 1 && loadStatus != LoadStatus.LIST_OVER && loadStatus != LoadStatus.LIST_LOADING) {
                    viewModel.onLoadMore()
                }
            }
        }
    }


    companion object {
        // 游戏单轮换刷新
        const val PAYLOAD_REFRESH_GAME_LIST = "payload_refresh_game_list"

        // 刷新游戏下载状态
        const val PAYLOAD_REFRESH_GAME_CHANGED = "payload_refresh_game_changed"

        private val CALLBACK = object : DiffUtil.ItemCallback<CustomPageItem>() {
            override fun areItemsTheSame(
                oldItem: CustomPageItem,
                newItem: CustomPageItem
            ) = oldItem.areItemsTheSame(newItem)

            override fun areContentsTheSame(
                oldItem: CustomPageItem,
                newItem: CustomPageItem
            ) = oldItem.areContentsTheSame(newItem)
        }
    }
}