package com.gh.gamecenter.gamecollection.hotlist

import android.content.Context
import android.graphics.Typeface
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.ItemGameCollectionHotListBinding
import com.gh.gamecenter.entity.GameCollectionListEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.gamecollection.square.GameCollectionListItemData

class GameCollectionHotListAdapter(
    context: Context,
    private val mPosition: Int,
    private val mGameCollectionListEntity: GameCollectionListEntity? = null,
    private val mViewModel: GameCollectionHotListViewModel,
    private val mIsFromDetail: Boolean = false,
    private val mEntrance: String,
    private val mPath: String,
    private val mBasicExposureSource: List<ExposureSource>
) : ListAdapter<GameCollectionListItemData>(context), IExposable {
    private val mCoverWidth = (DisplayUtils.getScreenWidth() - 40F.dip2px()) / 2
    override fun getItemViewType(position: Int): Int {
        return if (isShowHeaderItem() && position == 0) ItemViewType.ITEM_HEADER else if (position == itemCount - 1) ItemViewType.ITEM_FOOTER else ItemViewType.ITEM_BODY
    }

    private fun isShowHeaderItem() = !mGameCollectionListEntity?.explain.isNullOrEmpty()

    private fun getHeaderItemCount() = if (mGameCollectionListEntity?.explain.isNullOrEmpty()) 0 else 1

    private fun getRealPosition(position: Int) = position - getHeaderItemCount()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_FOOTER ->
                FooterViewHolder(
                    mLayoutInflater.inflate(
                        com.gh.gamecenter.common.R.layout.refresh_footerview,
                        parent,
                        false
                    )
                )

            ItemViewType.ITEM_HEADER -> GameCollectionPlayerCreationAdapter.GameCollectionPlayerCreationHeaderItemViewHolder(
                parent.toBinding()
            )

            else -> GameCollectionHotListItemViewHolder(parent.toBinding())
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameCollectionPlayerCreationAdapter.GameCollectionPlayerCreationHeaderItemViewHolder) {
            holder.binding.run {
                root.setPadding(0, if (mIsFromDetail) 16F.dip2px() else 0, 0, 12F.dip2px())
                timeSfv.visibility = View.GONE
                tipsIv.visibility = View.GONE
                tipsTv.text = mGameCollectionListEntity?.explain
                tipsTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
            }
        }

        if (holder is GameCollectionHotListItemViewHolder) {
            val realPosition = getRealPosition(position)
            val itemData = mEntityList[realPosition]
            val entity = itemData.gameCollectionItem
            holder.binding.run {
                root.background = com.gh.gamecenter.common.R.drawable.background_shape_white_radius_8.toDrawable(mContext)
                titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                userTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(mContext))
                gameCountTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))

                rankIv.goneIf(realPosition > 2 || mIsFromDetail) {
                    rankIv.setImageResource(
                        when (realPosition) {
                            0 -> R.drawable.icon_leaderboard_1
                            1 -> R.drawable.icon_leaderboard_2
                            else -> R.drawable.icon_leaderboard_3
                        }
                    )
                }
                rankTv.goneIf(realPosition < 3 || mIsFromDetail) {
                    rankTv.typeface = Typeface.createFromAsset(mContext.assets, Constants.DIN_FONT_PATH)
                    rankTv.text = "${realPosition + 1}"
                }
                stampIv.goneIf(entity?.stamp.isNullOrEmpty())
                stampIv.setBackgroundResource(if (entity?.stamp == "official") R.drawable.label_game_collection_official else R.drawable.label_game_collection_special_choice)
                titleTv.text = entity?.title
                userTv.text = entity?.user?.name
                coverImage.setTag(ImageUtils.TAG_TARGET_WIDTH, mCoverWidth)
                ImageUtils.display(coverImage, entity?.cover)
                ImageUtils.display(userIv, entity?.user?.icon)

                val gameIcons = arrayListOf(gameImage1, gameImage2, gameImage3)
                val games = entity?.games ?: arrayListOf()
                val exposureEventList = arrayListOf<ExposureEvent>()
                gameIcons.forEachIndexed { index, gameIcon ->
                    gameIcon.goneIf(games.size < index + 1) {
                        val gameEntity = games[index].toGameEntity()
                        val exposureEvent = ExposureEvent.createEventWithSourceConcat(
                            gameEntity.apply {
                                outerSequence = mGameCollectionListEntity?.position
                                sequence = realPosition
                            },
                            mBasicExposureSource,
                            listOf(
                                ExposureSource(
                                    "游戏单",
                                    "${itemData.gameCollectionItem?.title} + ${itemData.gameCollectionItem?.id}"
                                )
                            )
                        )
                        exposureEventList.add(exposureEvent)

                        gameIcon.displayGameIcon(gameEntity)
                        gameIcon.setBorderColor(com.gh.gamecenter.common.R.color.ui_surface)
                        gameIcon.setOnClickListener {
                            NewFlatLogUtils.logGameCollectionHotListClick(
                                mGameCollectionListEntity?.name ?: "",
                                mGameCollectionListEntity?.id ?: "",
                                mGameCollectionListEntity?.name ?: "",
                                "游戏"
                            )
                            if (mIsFromDetail) {
                                SensorsBridge.trackGameListCollectionClick(
                                    location = "合集详情",
                                    gameListCollectionId = mGameCollectionListEntity?.id ?: "",
                                    gameListCollectionName = mGameCollectionListEntity?.name ?: "",
                                    position = position,
                                    text = "游戏",
                                    otherParams = hashMapOf(
                                        "game_name" to (gameEntity.name ?: ""),
                                        "game_id" to gameEntity.id
                                    )
                                )
                            } else {
                                SensorsBridge.trackEvent("ViewGameCollectHotRankTabClick", json {
                                    "position" to mPosition
                                    "list_name" to mGameCollectionListEntity?.name
                                    "game_list_collection_name" to mGameCollectionListEntity?.name
                                    "game_list_collection_id" to mGameCollectionListEntity?.id
                                    "text" to "游戏"
                                    "game_name" to gameEntity.name
                                    "game_id" to gameEntity.id
                                })
                            }
                            GameDetailActivity.startGameDetailActivity(
                                mContext,
                                gameEntity.id,
                                BaseActivity.mergeEntranceAndPath(mEntrance, mPath),
                                exposureEvent
                            )
                        }
                    }
                }
                itemData.exposureEventList = exposureEventList
                gameCountTv.goneIf(games.isEmpty())
                titleTv.maxLines = if (games.isEmpty()) 2 else 1
                titleTv.layoutParams = (titleTv.layoutParams as ConstraintLayout.LayoutParams).apply {
                    topMargin = if (games.isEmpty()) 10F.dip2px() else 32F.dip2px()
                }
                entity?.count?.let { gameCountTv.text = "+${it.game - games.size}" }
                listOf(userIv, userTv).forEach {
                    it.setOnClickListener {
                        NewFlatLogUtils.logGameCollectionHotListClick(
                            mGameCollectionListEntity?.name ?: "",
                            mGameCollectionListEntity?.id ?: "",
                            mGameCollectionListEntity?.name ?: "",
                            "个人主页"
                        )
                        if (mIsFromDetail) {
                            SensorsBridge.trackGameListCollectionClick(
                                location = "合集详情",
                                gameListCollectionId = mGameCollectionListEntity?.id ?: "",
                                gameListCollectionName = mGameCollectionListEntity?.name ?: "",
                                position = position,
                                text = "个人主页",
                                otherParams = hashMapOf("mongold_id" to (entity?.user?.id ?: ""))
                            )
                        } else {
                            SensorsBridge.trackEvent("ViewGameCollectHotRankTabClick", json {
                                "position" to mPosition
                                "list_name" to mGameCollectionListEntity?.name
                                "game_list_collection_name" to mGameCollectionListEntity?.name
                                "game_list_collection_id" to mGameCollectionListEntity?.id
                                "text" to "个人主页"
                                "mongold_id" to entity?.user?.id
                            })
                        }
                        DirectUtils.directToHomeActivity(mContext, entity?.user?.id, 0, mEntrance, mPath)
                    }
                }
                root.setOnClickListener {
                    NewFlatLogUtils.logGameCollectionHotListClick(
                        mGameCollectionListEntity?.name ?: "",
                        mGameCollectionListEntity?.id ?: "",
                        mGameCollectionListEntity?.name ?: "",
                        "游戏单"
                    )
                    if (mIsFromDetail) {
                        SensorsBridge.trackGameListCollectionClick(
                            location = "合集详情",
                            gameListCollectionId = mGameCollectionListEntity?.id ?: "",
                            gameListCollectionName = mGameCollectionListEntity?.name ?: "",
                            position = position,
                            text = "游戏单",
                            otherParams = hashMapOf(
                                "game_collect_title" to (entity?.title ?: ""),
                                "game_collect_id" to (entity?.id ?: "")
                            )
                        )
                    } else {
                        SensorsBridge.trackEvent("ViewGameCollectHotRankTabClick", json {
                            "position" to mPosition
                            "list_name" to mGameCollectionListEntity?.name
                            "game_list_collection_name" to mGameCollectionListEntity?.name
                            "game_list_collection_id" to mGameCollectionListEntity?.id
                            "text" to "游戏单"
                            "game_collect_title" to entity?.title
                            "game_collect_id" to entity?.id
                        })
                    }
                    DirectUtils.directToGameCollectionDetail(
                        it.context,
                        entity?.id ?: "",
                        mEntrance,
                        mPath,
                        ExposureEvent.createEventWithSourceConcat(
                            null,
                            mBasicExposureSource,
                            listOf(
                                ExposureSource(
                                    "游戏单",
                                    "${itemData.gameCollectionItem?.title} + ${itemData.gameCollectionItem?.id}"
                                )
                            )
                        )
                    )
                }
            }
        }
        if (holder is FooterViewHolder) {
            holder.initItemPadding()
            holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
            holder.hint.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_B3B3B3))
            val lp = holder.itemView.layoutParams as RecyclerView.LayoutParams
            lp.height = DisplayUtils.dip2px(48F)
            lp.width = ViewGroup.LayoutParams.MATCH_PARENT
            holder.itemView.layoutParams = lp
        }
    }

    override fun getItemCount(): Int =
        if (mEntityList.isNotEmpty()) mEntityList.size + FOOTER_ITEM_COUNT + getHeaderItemCount() else 0

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return if (getRealPosition(pos) in 0 until mEntityList.size) {
            mEntityList[pos].exposureEvent
        } else {
            null
        }
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return if (getRealPosition(pos) in 0 until mEntityList.size) {
            mEntityList[pos].exposureEventList
        } else {
            null
        }
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        val layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager) {
            layoutManager.spanSizeLookup = object : SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    if (getItemViewType(position) == ItemViewType.ITEM_FOOTER || getItemViewType(position) == ItemViewType.ITEM_HEADER) {
                        return layoutManager.spanCount
                    }
                    return 1
                }
            }
        }
    }

    class GameCollectionHotListItemViewHolder(val binding: ItemGameCollectionHotListBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)
}