package com.gh.gamecenter.servers.gametest2

import android.content.Context
import android.graphics.Typeface
import android.text.Html
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.ExposureListener
import com.gh.common.exposure.IExposable
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.databinding.ItemGameServerTestV2CollapsedBinding
import com.gh.gamecenter.databinding.ItemGameServerTestV2TimeBinding
import com.gh.gamecenter.databinding.ItemGameServerTestV2TopGamesBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.PageLocation
import com.gh.gamecenter.feature.exposure.ExposureEvent

class GameServerTestV2ListAdapter(
    private val context: Context,
    private val mFragment: GameServerTestV2ListFragment,
    private var mGameServerTestV2ViewModel: GameServerTestV2ViewModel?,
    private var mBasicExposureSource: List<ExposureSource>?,
    private var mOuterSequence: Int,
    private val mLinkText: String,
    private val mPageLocation: PageLocation
) : ListAdapter<GameServerTestV2ListViewModel.ItemData>(context), IExposable {

    private val mExposureEventArray: SparseArray<ExposureEvent> = SparseArray()

    override fun areItemsTheSame(
        oldItem: GameServerTestV2ListViewModel.ItemData?,
        newItem: GameServerTestV2ListViewModel.ItemData?
    ): Boolean {
        if (oldItem?.isBigImage != null && newItem?.isBigImage != null) {
            return oldItem.isBigImage == newItem.isBigImage
        }
        if (oldItem?.isCollapsed != null && newItem?.isCollapsed != null) {
            return oldItem.isCollapsed == newItem.isCollapsed
        }
        if (oldItem?.bigTime != null && newItem?.bigTime != null) {
            return oldItem.bigTime == newItem.bigTime
        }
        if (oldItem?.time != null && newItem?.time != null) {
            return oldItem.time == newItem.time
        }
        if (oldItem?.game != null && newItem?.game != null) {
            return oldItem.game?.id == newItem.game?.id
        }
        if (oldItem?.topGames != null && newItem?.topGames != null) {
            return oldItem.topGames == newItem.topGames
        }
        return false
    }

    override fun getItemViewType(position: Int): Int {
        if (position == mEntityList.size) {
            return VIEW_TYPE_FOOTER
        }
        return when {
            mEntityList[position].bigTime != null -> VIEW_TYPE_TIME
            mEntityList[position].isBigImage -> VIEW_TYPE_BIG_IMAGE_ITEM
            mEntityList[position].isCollapsed -> VIEW_TYPE_COLLAPSED_ITEM
            mEntityList[position].isTopGames -> VIEW_TYPE_TOP_GAMES
            else -> VIEW_TYPE_ITEM
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            VIEW_TYPE_FOOTER -> {
                FooterViewHolder(mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false))
            }
            VIEW_TYPE_TIME -> {
                GameServerTestTimeViewHolder(parent.toBinding())
            }
            VIEW_TYPE_BIG_IMAGE_ITEM -> {
                GameBigImageViewHolder(parent.toBinding())
            }
            VIEW_TYPE_COLLAPSED_ITEM -> {
                GameServerTestCollapsedItemViewHolder(parent.toBinding())
            }
            VIEW_TYPE_TOP_GAMES -> {
                GameServerTestTopGamesItemViewHolder(parent.toBinding())
            }
            else -> {
                GameServerTestV2ItemViewHolder(parent.toBinding())
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameServerTestV2ItemViewHolder -> {
                val itemData = mEntityList[position]
                val gameEntity = itemData.game!!
                val exposureEvent = putExposureEvent(gameEntity, position)
                holder.binding.root.updateLayoutParams<MarginLayoutParams> {
                    topMargin = if (position == 1) 4F.dip2px() else 12F.dip2px()
                }

                holder.bindAttachGame(holder, gameEntity, this, "新游开测", exposureEvent, "详情页", mLinkText, mPageLocation)
            }
            is GameBigImageViewHolder -> {
                val gameEntity = mEntityList[position].game!!
                val exposureEvent = putExposureEvent(gameEntity, position)
                holder.binding.root.updateLayoutParams<MarginLayoutParams> {
                    topMargin = if (position == 1) 16F.dip2px() else 12F.dip2px()
                }

                holder.bindAttachGame(
                    holder,
                    gameEntity,
                    this,
                    "新游开测",
                    exposureEvent,
                    mLinkText, mPageLocation
                )
            }
            is GameServerTestTimeViewHolder -> {
                holder.binding.root.updateLayoutParams<MarginLayoutParams> {
                    topMargin = if (position != 0 && mEntityList.getOrNull(position - 1)?.isTopGames == false) 12F.dip2px() else 0
                }
                holder.binding.root.setPadding(
                    16F.dip2px(),
                    if (position == 0) 4F.dip2px() else 20F.dip2px(),
                    16F.dip2px(),
                    if (position == 0) 12F.dip2px() else 4F.dip2px()
                )
                holder.binding.bigTimeTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                holder.binding.timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                holder.binding.gameCountTv.setTextColor(com.gh.gamecenter.common.R.color.text_neutral.toColor(context))
                holder.binding.bigTimeTv.setTypeface(Typeface.createFromAsset(context.assets, Constants.DIN_FONT_PATH))
                holder.binding.bigTimeTv.text = mEntityList[position].bigTime
                holder.binding.timeTv.text = mEntityList[position].time
                holder.binding.gameCountTv.text = "${mEntityList[position].gameCount} 款游戏"
            }
            is GameServerTestCollapsedItemViewHolder -> {
                val itemData = mEntityList[position]
                holder.binding.run {
                    root.setPadding(0, if (position == 1) 4F.dip2px() else 12F.dip2px(), 0, 0)
                    collapsedGameContainer.background = R.drawable.border_round_stroke_ui_divider_999.toDrawable(context)
                    expandTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    expandTv.text = Html.fromHtml("展开其他<font color='#2888E0'>${itemData.collapsedGames?.size ?: 0}</font>款游戏")
                    val gameIconList = listOf(gameIcon1, gameIcon2, gameIcon3)
                    gameIconList.forEach {
                        it.setBorderColor(com.gh.gamecenter.common.R.color.ui_background)
                    }
                    itemData.collapsedGames?.take(3)?.forEachIndexed { index, game ->
                        gameIconList[index].displayGameIcon(game)
                    }
                    itemData.collapsedGames?.size?.let {
                        gameIcon1.goneIf(it == 0)
                        gameIcon2.goneIf(it < 2)
                        gameIcon3.goneIf(it < 3)
                    }
                    collapsedGameContainer.setOnClickListener {
                        itemData.collapsedGames?.let {
                            CollapsedGamesDialogFragment.show(context, ArrayList(it), mLinkText, mPageLocation) { game, position ->
                                putExposureEvent(game, position, true)
                            }
                            SensorsBridge.trackColumnTestClick(
                                location = "详情页",
                                recommendType = mLinkText,
                                text = "其他游戏弹窗",
                                bottomTab = mPageLocation.bottomTab,
                                multiTabName = mPageLocation.severalTabPageName,
                                multiTabId = mPageLocation.severalTabPageId,
                                position = mPageLocation.tabPosition,
                                tabContent = mPageLocation.tabContent
                            )
                        }
                    }
                }
            }
            is GameServerTestTopGamesItemViewHolder -> {
                val itemData = mEntityList[position]
                holder.binding.recyclerView.run {
                    if (adapter !is GameServerTestTopGameAdapter) {
                        (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                        itemData.topGames?.let {
                            val topGameAdapter = GameServerTestTopGameAdapter(mContext, it, mLinkText, mPageLocation) { game, position ->
                                putExposureEvent(game, position, isTopGame = true)
                            }
                            adapter = topGameAdapter
                            addOnScrollListener(ExposureListener(mFragment, topGameAdapter))
                        }
                    } else {
                        adapter!!.notifyItemRangeChanged(0, adapter!!.itemCount)
                    }
                }
            }
            is FooterViewHolder -> {
                initFooterViewHolder(holder)
            }
        }
    }

    private fun putExposureEvent(
        gameEntity: GameEntity,
        position: Int,
        isCollapsedGame: Boolean = false,
        isTopGame: Boolean = false
    ): ExposureEvent {
        val exposureSources = ArrayList<ExposureSource>()
        val selectedCategoryFilter = mGameServerTestV2ViewModel?.getCategoryFilterString() ?: ""
        val selectedTimeFilter = mGameServerTestV2ViewModel?.selectedTimeFilterLiveData?.value
        val bigImageMode = if (mGameServerTestV2ViewModel?.bigImageMode == true) "大图模式" else "关闭大图"
        exposureSources.add(
            ExposureSource(
                "新游开测",
                "${mLinkText}-${bigImageMode}-${selectedTimeFilter}-${gameEntity.testTime}"
            )
        )
        if (isCollapsedGame) {
            exposureSources.add(ExposureSource("其他游戏弹窗", selectedCategoryFilter))
        } else if (isTopGame) {
            exposureSources.add(ExposureSource("置顶游戏"))
        }
        val exposureEvent = ExposureEvent.createEventWithSourceConcat(
            gameEntity = gameEntity.apply {
                outerSequence = mOuterSequence
                sequence = position
            },
            basicSource = mBasicExposureSource ?: listOf(),
            source = exposureSources
        )
        if (!isCollapsedGame && !isTopGame) {
            mExposureEventArray.put(position, exposureEvent)
        }
        return exposureEvent
    }

    private fun initFooterViewHolder(viewHolder: FooterViewHolder) {
        viewHolder.run {
            itemView.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(mContext))
            loading.visibility = View.GONE
            itemView.isClickable = false
            hint.setText(com.gh.gamecenter.common.R.string.load_over_hint)
        }
    }

    override fun getItemCount(): Int = if (mEntityList.isEmpty()) 0 else mEntityList.size + 1

    companion object {
        const val VIEW_TYPE_TIME = 0
        const val VIEW_TYPE_ITEM = 1
        const val VIEW_TYPE_BIG_IMAGE_ITEM = 2
        const val VIEW_TYPE_FOOTER = 3
        const val VIEW_TYPE_COLLAPSED_ITEM = 4
        const val VIEW_TYPE_TOP_GAMES = 5
    }

    class GameServerTestTimeViewHolder(var binding: ItemGameServerTestV2TimeBinding) :
        RecyclerView.ViewHolder(binding.root)

    class GameServerTestCollapsedItemViewHolder(var binding: ItemGameServerTestV2CollapsedBinding) :
        RecyclerView.ViewHolder(binding.root)

    class GameServerTestTopGamesItemViewHolder(var binding: ItemGameServerTestV2TopGamesBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return mExposureEventArray.get(pos)
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return null
    }
}