package com.gh.gamecenter.gamecollection.detail

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.exposure.ExposureEvent
import com.gh.common.exposure.ExposureSource
import com.gh.common.exposure.ExposureType
import com.gh.common.exposure.IExposable
import com.gh.common.util.CommentHelper
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.GameCollectionDetailNoneGameItemBinding
import com.gh.gamecenter.databinding.GameCollectionGameItemBinding
import com.gh.gamecenter.databinding.ItemArticleDetailCommentBinding
import com.gh.gamecenter.databinding.LayoutGameCollectionAuthTagBinding
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.game.GameItemViewHolder
import com.gh.gamecenter.gamecollection.detail.conversation.GameCollectionCommentConversationAdapter
import com.gh.gamecenter.gamecollection.detail.conversation.GameCollectionCommentConversationViewModel
import com.gh.gamecenter.qa.article.detail.CommentItemData
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.comment.CommentPictureAdapter
import com.gh.gamecenter.qa.comment.OnCommentOptionClickListener
import com.gh.gamecenter.qa.comment.base.BaseCommentAdapter
import com.lightgame.download.DownloadEntity

open class GameCollectionDetailAdapter(
    context: Context,
    private val type: AdapterType,
    val mEntrance: String,
    val mViewModel: GameCollectionDetailViewModel,
    commentClosure: ((CommentEntity) -> Unit)? = null
) : BaseCommentAdapter(context, mViewModel, type, mEntrance, commentClosure), IExposable {

    var recommendPrefBitmap: Bitmap? = null
    val positionAndPackageMap = HashMap<String, Int>()
    private var mExposureEventArray: SparseArray<ExposureEvent>? = null
    private var mItemDecoration: RecyclerView.ItemDecoration? = null

    override fun setListData(updateData: MutableList<CommentItemData>?) {
        mExposureEventArray = SparseArray(updateData?.size ?: 0)
        // 记录游戏位置
        if (updateData != null) {
            for (i in 0 until updateData.size) {
                val gameEntity = updateData[i].game
                if (gameEntity != null) {
                    var packages = gameEntity.id
                    for (apkEntity in gameEntity.getApk()) {
                        packages += apkEntity.packageName
                    }
                    gameEntity.sequence = i
                    positionAndPackageMap[packages + i] = i
                }
            }
        }
        super.setListData(updateData)
    }

    override fun getItemViewType(position: Int): Int {
        val item = mEntityList[position]
        return when {
            item.game != null -> ITEM_GAME
            item.gameEmpty != null -> ITEM_GAME_EMPTY
            item.divider != null -> ITEM_DIVIDER
            else -> super.getItemViewType(position)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ITEM_GAME -> GameCollectionGameItemViewHolder(
                GameCollectionGameItemBinding.bind(
                    mLayoutInflater.inflate(
                        R.layout.game_collection_game_item,
                        parent,
                        false
                    )
                )
            )

            ITEM_GAME_EMPTY -> GameCollectionGameEmptyViewHolder(
                GameCollectionDetailNoneGameItemBinding.bind(
                    mLayoutInflater.inflate(
                        R.layout.game_collection_detail_none_game_item,
                        parent,
                        false
                    )
                )
            )

            ITEM_DIVIDER -> GameCollectionDividerViewHolder(
                mLayoutInflater.inflate(
                    R.layout.game_collection_detail_divider_item,
                    parent,
                    false
                )
            )


            else -> super.onCreateViewHolder(parent, viewType)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is CommentFilterViewHolder -> {
                holder.bindView(gameCollection = true)
            }

            is GameCollectionGameItemViewHolder -> {
                holder.bindView(
                    mEntityList[position].game!!,
                    position,
                    position + 1 == mViewModel.gameCollectionDetail?.games?.size ?: 0
                )
            }

            is GameCollectionGameEmptyViewHolder -> {
                mViewModel.postFirstItemInitOver()
                holder.binding.noneGameContainer.setBackgroundColor(R.color.background_white.toColor(mContext))
                holder.binding.noneGameTv.setTextColor(R.color.text_body.toColor(mContext))
            }

            is CommentItemViewHolder -> {
                bindComment(holder.binding, mEntityList[position].commentNormal!!, position) { deleteCommentEntity ->
                    val findEntity =
                        mEntityList.find { it.commentNormal != null && it.commentNormal?.id == deleteCommentEntity.id }
                    val index = mEntityList.indexOf(findEntity)
                    mEntityList.remove(findEntity)
                    notifyItemRemoved(index)

                    //刷新 ITEM_FILTER
                    mViewModel.commentCount -= 1
                    if (this !is GameCollectionCommentConversationAdapter) {
                        notifyItemChanged(mViewModel.filterPos)
                    }

                    mEntityList[0].commentTop?.reply = (mEntityList[0].commentTop?.reply
                        ?: 0) - 1
                    SyncPageRepository.postSyncData(
                        SyncDataEntity(
                            mEntityList[0].commentTop?.id
                                ?: "",
                            SyncFieldConstants.ARTICLE_COMMENT_REPLY_COUNT,
                            mEntityList[0].commentTop?.reply,
                            checkFieldEntity = true
                        )
                    )
                    //刷新评论详情头部
//                    notifyItemChanged(0)
                }
            }

            is CommentFooterViewHolder -> {
                holder.bindView(mIsLoading, mIsNetworkError, mIsOver, R.string.game_collection_load_over_hint)
            }

            is GameCollectionDividerViewHolder -> {
                holder.itemView.setBackgroundColor(R.color.background.toColor(mContext))
            }

            else -> super.onBindViewHolder(holder, position)
        }
    }

    fun bindComment(
        binding: ItemArticleDetailCommentBinding,
        comment: CommentEntity,
        position: Int,
        deleteCallBack: ((comment: CommentEntity) -> Unit)? = null
    ) {
        bindNormalComment(binding, comment, deleteCallBack)
        binding.run {
            if (type == AdapterType.COMMENT) {
                // 游戏单详情页面用的样式
                updateSubComment(this, comment)

                floorHintTv.visibility = View.GONE
                bottomDivider.goneIf(position == itemCount - 2)

                root.setOnClickListener {
                    mContext.startActivity(
                        CommentActivity.getGameCollectionCommentReplyIntent(
                            mContext,
                            mViewModel.gameCollectionId,
                            comment.id ?: "",
                            mViewModel.commentCount,
                            comment
                        )
                    )
                }

                commentCountTv.setOnClickListener {
                    mContext.startActivity(
                        CommentActivity.getGameCollectionCommentDetailIntent(
                            mContext,
                            comment.id ?: "",
                            mViewModel.gameCollectionId,
                            false,
                            mEntrance,
                            "游戏单详情"
                        )
                    )
                }

                contentTv.text = comment.content

                commentCountTv.text = mViewModel.getCommentText(comment.reply, "回复")
            } else {
                // 评论详情用的样式
                floorHintTv.visibility = View.GONE
                commentCountTv.setOnClickListener { commentClosure?.invoke(comment) }
                commentCountTv.text = "回复"
                likeCountTv.text = mViewModel.getLikeText(comment.vote, "")
                root.setOnClickListener { binding.commentCountTv.performClick() }

                if (comment.parentUser != null && !TextUtils.isEmpty(comment.parentUser!!.id)) {
                    val prefix = "回复"
                    val colon = " ："
                    val parentUserName = " @${comment.parentUser?.name} "

                    val prefixSpan = SpanBuilder(prefix).color(
                        binding.root.context,
                        0,
                        prefix.length,
                        R.color.text_title
                    ).build()
                    val parentUserNameSpan = SpanBuilder(parentUserName)
                        .click(mContext, 0, parentUserName.length, R.color.text_subtitleDesc) {
                            DirectUtils.directToHomeActivity(
                                binding.root.context,
                                comment.user.id,
                                1,
                                mEntrance,
                                PATH_ARTICLE_DETAIL_COMMENT
                            )
                            MtaHelper.onEvent("帖子详情", "引用回复区域", "用户名字")
                        }.build()
                    val colonSpan = SpanBuilder(colon).color(
                        binding.root.context,
                        0,
                        colon.length,
                        R.color.text_title
                    ).build()
                    val authorSpan = if (comment.parentUser?.me?.isCommentOwner == true) {
                        SpanBuilder("作者").image(0, "作者".length, R.drawable.ic_hint_author).build()
                    } else {
                        ""
                    }

                    contentTv.text = SpannableStringBuilder()
                        .append(prefixSpan)
                        .append(parentUserNameSpan)
                        .append(authorSpan)
                        .append(colonSpan)
                        .append(comment.content)
                } else {
                    contentTv.text = comment.content
                }
            }
        }
    }

    fun bindNormalComment(
        binding: ItemArticleDetailCommentBinding,
        comment: CommentEntity,
        deleteCallBack: ((comment: CommentEntity) -> Unit)? = null
    ) {
        binding.run {
            root.setBackgroundColor(R.color.background_white.toColor(mContext))
            subCommentContainer.setBackgroundColor(R.color.background_space_2.toColor(mContext))
            divider.setBackgroundColor(R.color.background_space.toColor(mContext))
            bottomDivider.setBackgroundColor(R.color.divider.toColor(mContext))
            userNameTv.setTextColor(R.color.text_subtitle.toColor(mContext))
            badgeTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
            floorHintTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
            contentTv.setTextColor(R.color.text_title.toColor(mContext))
            collapseTv.setTextColor(R.color.theme_font.toColor(mContext))
            firstSubCommentTv.setTextColor(R.color.text_subtitle.toColor(mContext))
            secondSubCommentTv.setTextColor(R.color.text_subtitle.toColor(mContext))
            moreSubCommentBtn.setTextColor(R.color.theme_font.toColor(mContext))
            timeTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
            likeCountTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
            commentCountTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))

            if (comment.isHighlight) {
                comment.isHighlight = false
                binding.highlightBg.run {
                    visibility = View.VISIBLE
                    postDelayed({
                        tryWithDefaultCatch {
                            visibility = View.GONE
                        }
                    }, 3000)
                }
            }

            if (!comment.images.isNullOrEmpty()) {
                if (commentPictureRv.adapter == null) {
                    commentPictureRv.apply {
                        layoutManager = GridLayoutManager(context, 3)
                        adapter = CommentPictureAdapter(context, comment.images!!, "")
                        if (itemDecorationCount == 0) {
                            addItemDecoration(
                                GridSpacingItemColorDecoration(
                                    context,
                                    2,
                                    R.color.background_white
                                ).apply { mItemDecoration = this })
                        }
                        visibility = View.VISIBLE
                    }
                } else {
                    (commentPictureRv.adapter as CommentPictureAdapter).checkResetData(comment.images!!)
                    mItemDecoration?.let { commentPictureRv.removeItemDecoration(it) }
                    commentPictureRv.addItemDecoration(
                        GridSpacingItemColorDecoration(
                            commentPictureRv.context,
                            2,
                            R.color.background_white
                        ).apply { mItemDecoration = this })
                }
            } else {
                binding.commentPictureRv.visibility = View.GONE
            }

            CommentItemViewHolder.bindView(binding, comment)

            if (comment.isForceExpand) {
                comment.isForceExpand = false
                contentTv.setExpandMaxLines(Int.MAX_VALUE)
                contentTv.setIsExpanded(true)
                contentTv.post {
                    collapseTv.goneIf(contentTv.lineCount <= 4)
                }
            } else {
                contentTv.setExpandMaxLines(if (comment.isExpand) Int.MAX_VALUE else 4)
                contentTv.setIsExpanded(comment.isExpand)
                collapseTv.goneIf(!comment.isExpand)
            }
            contentTv.setExpandCallback {
                comment.isExpand = true
                collapseTv.visibility = View.VISIBLE
                CommentItemViewHolder.bindView(binding, comment)
            }
            collapseTv.setOnClickListener {
                comment.isExpand = false
                collapseTv.visibility = View.GONE
                contentTv.setExpandMaxLines(4)
                contentTv.setIsExpanded(false)
                CommentItemViewHolder.bindView(binding, comment)
            }
            userIconIv.display(
                comment.user.border,
                comment.user.icon,
                comment.user.auth?.icon
            )

            userIconIv.setOnClickListener {
                DirectUtils.directToHomeActivity(
                    mContext,
                    comment.user.id,
                    "",
                    "游戏单详情-评论"
                )
            }

            userNameTv.setOnClickListener {
                DirectUtils.directToHomeActivity(
                    mContext,
                    comment.user.id,
                    "",
                    "游戏单详情-评论"
                )
            }

            likeCountTv.text = mViewModel.getLikeText(
                comment.vote,
                if (mViewModel is GameCollectionCommentConversationViewModel) "" else "赞同"
            )

            if (comment.me?.isCommentVoted == true) {
                likeCountTv.setTextColor(R.color.theme_font.toColor(likeCountTv.context))
                likeCountTv.setDrawableStart(R.drawable.comment_vote_select)
            } else {
                likeCountTv.setTextColor(R.color.text_subtitleDesc.toColor(likeCountTv.context))
                likeCountTv.setDrawableStart(R.drawable.comment_vote_unselect)
            }

            likeCountTv.setDebouncedClickListener {
                likeCountTv.context.ifLogin("游戏单详情-评论-点赞") {
                    mViewModel.postVoteGameCollectionComment(comment) {
                        likeCountTv.setDrawableStart(if (comment.me?.isCommentVoted == true) R.drawable.comment_vote_select else R.drawable.comment_vote_unselect)
                        likeCountTv.text = mViewModel.getLikeText(comment.vote)
                        likeCountTv.setTextColor(
                            if (comment.me?.isCommentVoted == true) R.color.theme_font.toColor(likeCountTv.context)
                            else R.color.text_subtitleDesc.toColor(likeCountTv.context)
                        )
                    }
                }
            }

            badgeTv.setOnClickListener {
                DialogUtils.showViewBadgeDialog(mContext, comment.user.badge, object : ConfirmListener {
                    override fun onConfirm() {
                        DirectUtils.directToBadgeWall(
                            mContext,
                            comment.user.id,
                            comment.user.name,
                            comment.user.icon
                        )
                    }
                })
            }

            badgeIv.setOnClickListener { badgeTv.performClick() }

            moreIv.setOnClickListener {
                CommentHelper.showGameCollectionCommentOption(
                    it,
                    comment,
                    mViewModel.gameCollectionId,
                    object : OnCommentOptionClickListener {
                        override fun onCommentOptionClick(entity: CommentEntity, option: String) {
                            when (option) {
                                "删除评论" -> {
                                    DialogHelper.showDialog(
                                        binding.moreIv.context,
                                        "提示",
                                        "删除评论后，评论下所有的回复都将被删除",
                                        "删除",
                                        "取消",
                                        {
                                            mViewModel.deleteComment(comment) {
                                                deleteCallBack?.invoke(comment)
                                            }
                                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                            }
                        }
                    }
                )
            }
        }
    }

    private fun updateSubComment(
        binding: ItemArticleDetailCommentBinding,
        comment: CommentEntity,
    ) {
        val subCommentList = comment.subCommentList
        val ownerUserId = mViewModel.ownerUserId
        binding.moreSubCommentBtn.goneIf(comment.reply < 3)
        binding.moreSubCommentBtn.text = "查看全部${comment.reply}条回复"
        binding.subCommentContainer.goneIf(subCommentList.isNullOrEmpty())
        binding.firstSubCommentTv.goneIf(subCommentList?.firstOrNull() == null)
        binding.secondSubCommentTv.goneIf(subCommentList?.secondOrNull() == null)
        binding.subCommentContainer.setRoundedColorBackground(R.color.background_space_2, 5F)

        subCommentList?.firstOrNull()?.let {
            binding.firstSubCommentTv.text = getSubCommentSpanned(
                it.user.name,
                if (it.user.id == ownerUserId) "作者" else "",
                it.content
            )
        }
        subCommentList?.secondOrNull()?.let {
            binding.secondSubCommentTv.text = getSubCommentSpanned(
                it.user.name,
                if (it.user.id == ownerUserId) "作者" else "",
                it.content
            )
        }
        binding.subCommentContainer.setOnClickListener {
            mContext.startActivity(
                CommentActivity.getGameCollectionCommentDetailIntent(
                    mContext,
                    comment.id ?: "",
                    mViewModel.gameCollectionId,
                    false,
                    mEntrance,
                    "游戏单详情"
                )
            )
        }
    }

    private fun getSubCommentSpanned(
        name: String?,
        author: String?,
        content: String?
    ): SpannableStringBuilder {
        val finalAuthor = author ?: ""
        val finalName = "$name "
        val colon = " ："

        val nameSpan =
            SpanBuilder(finalName).color(mContext, 0, finalName.length, R.color.theme_font).build()
        val authorSpan = if (finalAuthor.isNotEmpty()) SpanBuilder(finalAuthor).image(
            0,
            finalAuthor.length,
            R.drawable.ic_hint_author
        ).build() else ""
        val colonSpan = SpanBuilder(colon).color(mContext, 0, colon.length, R.color.theme_font).build()
        return SpannableStringBuilder().append(nameSpan).append(authorSpan).append(colonSpan)
            .append(content)
    }

    fun notifyItemByDownload(download: DownloadEntity) {
        for (key in positionAndPackageMap.keys) {
            if (key.contains(download.packageName) && key.contains(download.gameId)) {
                val position = positionAndPackageMap[key]
                if (position != null && mEntityList != null && position < mEntityList.size && mEntityList[position].game != null) {
                    mEntityList[position].game!!.getEntryMap()[download.platform] = download
                    notifyItemChanged(position)
                }
            }
        }
    }

    fun notifyItemAndRemoveDownload(status: EBDownloadStatus) {
        for (key in positionAndPackageMap.keys) {
            if (key.contains(status.packageName) && key.contains(status.gameId)) {
                val position = positionAndPackageMap[key]
                if (position != null && mEntityList != null && position < mEntityList.size && mEntityList[position].game != null) {
                    mEntityList[position].game!!.getEntryMap().remove(status.platform)
                    notifyItemChanged(position)
                }
            }
        }
    }

    inner class GameCollectionGameEmptyViewHolder(val binding: GameCollectionDetailNoneGameItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    inner class GameCollectionDividerViewHolder(view: View) : RecyclerView.ViewHolder(view)

    inner class GameCollectionGameItemViewHolder(val binding: GameCollectionGameItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bindView(gameEntity: GameEntity, position: Int, isLast: Boolean) {
            binding.run {
                container.background = R.drawable.reuse_listview_item_style.toDrawable(mContext)
                gameCollectionRecommendTv.background = R.drawable.bg_shape_space_radius_8.toDrawable(mContext)
                gameCollectionRecommendTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
                gameItemIncluded.run {
                    root.background = R.drawable.reuse_listview_item_style.toDrawable(mContext)
                    gameKaifuType.setBackgroundColor(R.color.theme.toColor(mContext))
                    gameName.setTextColor(R.color.text_title.toColor(mContext))
                    gameDes.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
                    recommendStarPref.setTextColor(R.color.text_subtitleDesc.toColor(mContext))

                    gameIconView.displayGameIcon(gameEntity)
                    BindingAdapters.setGameName(gameName, gameEntity, false, null)
                    BindingAdapters.setTextSize(gameRating, if (gameEntity.commentCount > 3) 12 else 10)
                    BindingAdapters.setGameTags(labelList, gameEntity)
                    gameRating.setDrawableStart(
                        if (gameEntity.commentCount > 3) R.drawable.game_horizontal_rating.toDrawable(mContext) else null
                    )
                    gameRating.setPadding(0, 0, if (gameEntity.commentCount > 3) 8F.dip2px() else 0, 0)
                    gameRating.text = if (gameEntity.commentCount > 3) {
                        if (gameEntity.star == 10.0F) "10" else gameEntity.star.toString()
                    } else ""
                    gameRating.setTextColor(
                        if (gameEntity.commentCount > 3) R.color.theme_font.toColor(mContext) else R.color.theme.toColor(
                            mContext
                        )
                    )
                    gameDes.text = gameEntity.decoratedDes
                    recommendStar.rating = gameEntity.recommendStar.toFloat()
                    GameItemViewHolder.initGameSubtitle(gameEntity, gameSubtitleTv, gameDesSpace, root)
                }
                root.setPadding(
                    16F.dip2px(),
                    if (position == 0) 16F.dip2px() else 8F.dip2px(),
                    16F.dip2px(),
                    16F.dip2px()
                )
                gameItemIncluded.root.setPadding(0, 0, 0, 0)
                gameItemIncluded.root.background = null
                gameItemIncluded.recommendStarPref.text = "推荐指数"
                initServerType(gameEntity)

                val exposureSources = ArrayList<ExposureSource>().apply {
                    add(ExposureSource("游戏单", "${mViewModel.gameCollectionTitle}+${mViewModel.gameCollectionId}"))
                }
                val exposureEvent = ExposureEvent.createEvent(
                    gameEntity,
                    exposureSources,
                    null,
                    ExposureType.EXPOSURE
                )
                mExposureEventArray!!.put(position, exposureEvent)

                if (gameEntity.recommendText.isNotEmpty()) {
                    if (recommendPrefBitmap == null) {
                        recommendPrefBitmap = getAuthTagBitmap()
                    }
                    val drawable = BitmapDrawable(mContext.resources, recommendPrefBitmap)
                    drawable.setBounds(0, 0, 54F.dip2px(), 14F.dip2px())
                    gameCollectionRecommendTv.text =
                        SpanBuilder(" ${gameEntity.recommendText.take(45)}").image(0, 1, drawable).build()
                } else {
                    gameCollectionRecommendTv.text = gameEntity.brief?.take(45)
                }

                root.setOnClickListener {
                    GameDetailActivity.startGameDetailActivity(
                        mContext,
                        gameEntity.id,
                        mEntrance,
                        exposureEvent
                    )
                }

                DownloadItemUtils.setOnClickListener(
                    mContext,
                    binding.gameItemIncluded.downloadBtn,
                    gameEntity,
                    position,
                    this@GameCollectionDetailAdapter,
                    mEntrance,
                    "游戏单详情-游戏列表:${gameEntity.name}",
                    exposureEvent
                )

                DownloadItemUtils.updateItem(
                    mContext,
                    gameEntity,
                    GameViewHolder(binding.gameItemIncluded),
                    true,
                    isShowRecommendStar = true
                )
            }

            mViewModel.postFirstItemInitOver()
        }

        fun initServerType(gameEntity: GameEntity) {
            val serverLabel = gameEntity.serverLabel
            when {
                gameEntity.test != null -> {
                    binding.gameItemIncluded.gameKaifuType.visibility = View.GONE
                    binding.gameItemIncluded.gameKaifuType.text = ""
                }
                serverLabel != null && !gameEntity.advanceDownload -> {
                    binding.gameItemIncluded.gameKaifuType.visibility = View.VISIBLE
                    binding.gameItemIncluded.gameKaifuType.text = serverLabel.value
                    if (gameEntity.isUseDefaultServerStyle()) {
                        binding.gameItemIncluded.gameKaifuType.background =
                            R.drawable.server_label_default_bg.toDrawable(binding.root.context)
                        binding.gameItemIncluded.gameKaifuType.setTextColor(R.color.text_server_label.toColor(binding.root.context))
                    } else {
                        binding.gameItemIncluded.gameKaifuType.background =
                            DrawableView.getServerDrawable(serverLabel.color)
                        binding.gameItemIncluded.gameKaifuType.setTextColor(R.color.white.toColor(binding.root.context))
                    }
                }
                else -> binding.gameItemIncluded.gameKaifuType.visibility = View.GONE
            }

            // 由于RecyclerView的复用机制 需要每次测量gameName的宽
            binding.gameItemIncluded.gameName.requestLayout()
        }
    }

    private fun getAuthTagBitmap(): Bitmap? {
        val view = LayoutGameCollectionAuthTagBinding.inflate(mLayoutInflater).root
        view.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? = mExposureEventArray!!.get(pos)

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? = null

    companion object {
        const val ITEM_GAME = 900
        const val ITEM_GAME_EMPTY = 901
        const val ITEM_DIVIDER = 902
    }
}