package com.gh.gamecenter.gamecollection.hotlist

import android.content.Context
import android.graphics.Typeface
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
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.entity.LinkEntity
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.ItemGameCollectionPlayerCreationBinding
import com.gh.gamecenter.databinding.ItemGameCollectionPlayerCreationHeaderBinding
import com.gh.gamecenter.entity.PlayerCreationItem
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.login.user.UserManager

class GameCollectionPlayerCreationAdapter(
    context: Context,
    private val mViewModel: GameCollectionPlayerCreationViewModel,
    private val mEntrance: String,
    private val mPath: String,
    private val mBasicExposureSourceList: ArrayList<ExposureSource>,
    private val mOnCheckedCallback: (Int) -> Unit
) : ListAdapter<PlayerCreationItem>(context) {

    private var mTipLinkEntity: LinkEntity? = null

    public override fun setListData(updateData: MutableList<PlayerCreationItem>?) {
        if (mEntityList.isEmpty()) {
            if (updateData.isNullOrEmpty()) {
                notifyDataSetChanged()
            } else {
                mEntityList = ArrayList(updateData)
                notifyItemRangeInserted(HEADER_ITEM_COUNT, mEntityList.size + FOOTER_ITEM_COUNT)
            }
        } else {
            val oldDataSize = mEntityList.size
            if (updateData.isNullOrEmpty()) {
                mEntityList = arrayListOf()
                notifyItemRangeRemoved(HEADER_ITEM_COUNT, oldDataSize + FOOTER_ITEM_COUNT)
            } else {
                mEntityList = ArrayList(updateData)
                notifyItemRangeChanged(HEADER_ITEM_COUNT, oldDataSize + FOOTER_ITEM_COUNT)
            }
        }
    }

    fun setTipData(linkEntity: LinkEntity) {
        mTipLinkEntity = linkEntity
        notifyItemChanged(0)
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) ItemViewType.ITEM_HEADER else if (position == itemCount - 1) ItemViewType.ITEM_FOOTER else ItemViewType.ITEM_BODY
    }

    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 -> GameCollectionPlayerCreationHeaderItemViewHolder(parent.toBinding())

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

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameCollectionPlayerCreationHeaderItemViewHolder) {
            mTipLinkEntity?.let { link ->
                holder.binding.run {
                    tipsTv.text = link.text
                    tipsTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                    tipsIv.setOnClickListener {
                        DirectUtils.directToLinkPage(mContext, link, "", "")
                    }

                    timeSfv.setItemList(listOf("周榜", "月榜"), if (mViewModel.isWeek) 0 else 1)
                    timeSfv.setOnCheckedCallback(mOnCheckedCallback)
                }
            }
        }

        if (holder is GameCollectionPlayerCreationItemViewHolder) {
            val realPosition = position - HEADER_ITEM_COUNT
            val entity = mEntityList[realPosition]
            holder.binding.run {
                root.setCardBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(mContext))
                gameCollectionCv.setCardBackgroundColor(com.gh.gamecenter.common.R.color.ui_container_1.toColor(mContext))
                rankTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                userNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                authTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                userFansAndVoteCountTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                gameCollectionCountTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(mContext))
                gameCollectionTitleTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(mContext))

                rankIv.goneIf(realPosition > 2) {
                    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) {
                    rankTv.typeface = Typeface.createFromAsset(mContext.assets, Constants.DIN_FONT_PATH)
                    rankTv.text = "${realPosition + 1}"
                }
                userNameTv.text = entity.user?.name
                authTv.goneIf(entity.user?.auth == null) {
                    authTv.text = entity?.user?.auth?.text
                }
                userFansAndVoteCountTv.text = "${entity.user?.count?.fans}粉丝  ${entity.user?.count?.vote}赞同"
                userAvatar.display(entity.user?.iconBorder?.url, entity.user?.icon, entity.user?.auth?.icon)
                followTv.goneIf(entity.user?.id == UserManager.getInstance().userId)
                badgeIv.goneIf(entity?.user?.badge == null) {
                    ImageUtils.display(badgeIv, entity.user?.badge?.icon)
                }
                badgeIv.setOnClickListener {
                    DialogUtils.showViewBadgeDialog(mContext, entity?.user?.badge) {
                        DirectUtils.directToBadgeWall(
                            mContext,
                            entity?.user?.id,
                            entity?.user?.name,
                            entity?.user?.icon
                        )
                    }
                }
                entity?.user?.me?.let {
                    followTv.text = if (it.isFollower) "已关注" else "关注"
                    followTv.setTextColor(
                        if (it.isFollower) com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext) else com.gh.gamecenter.common.R.color.text_theme.toColor(
                            mContext
                        )
                    )
                    followTv.background =
                        if (it.isFollower) com.gh.gamecenter.feature.R.drawable.button_round_gray_light.toDrawable(mContext) else R.drawable.button_round_primary_light.toDrawable(
                            mContext
                        )
                    followTv.setOnClickListener { view ->
                        SensorsBridge.trackUserFollowClick(
                            userId = entity.user.id,
                            userName = entity.user.name,
                            buttonName = followTv.text.toString()
                        )
                        mContext.ifLogin("板块成员") {
                            if (entity.user.id == UserManager.getInstance().userId) return@ifLogin
                            debounceActionWithInterval(view.id) {
                                NewFlatLogUtils.logGameCollectionHotListClick(
                                    GameCollectionHotListWrapperFragment.PLAYER_CREATION_TAB_NAME,
                                    "",
                                    "",
                                    "关注"
                                )
                                SensorsBridge.trackEvent("ViewGameCollectHotRankTabClick", json {
                                    "position" to 0
                                    "tab_content" to if (mViewModel.isWeek) "周榜" else "月榜"
                                    "text" to "关注"
                                    "mongold_id" to entity.user.id
                                })
                                if (it.isFollower) {
                                    mViewModel.followingCommand(entity.user.id, false) {
                                        it.isFollower = false
                                        notifyItemChanged(position)
                                    }
                                } else {
                                    mViewModel.followingCommand(entity.user.id, true) {
                                        it.isFollower = true
                                        notifyItemChanged(position)
                                    }
                                }
                            }
                        }
                    }
                }
                gameCollectionCountTv.text = "${entity.user?.count?.gameList}"
                gameCollectionTitleTv.text = entity?.gameList?.title

                listOf(
                    userAvatar,
                    userNameTv,
                    userFansAndVoteCountTv,
                    gameCollectionCountTv,
                    gameCollectionIv
                ).forEach {
                    it.setOnClickListener {
                        NewFlatLogUtils.logGameCollectionHotListClick(
                            GameCollectionHotListWrapperFragment.PLAYER_CREATION_TAB_NAME,
                            "",
                            "",
                            "个人主页"
                        )
                        SensorsBridge.trackEvent("ViewGameCollectHotRankTabClick", json {
                            "position" to 0
                            "tab_content" to if (mViewModel.isWeek) "周榜" else "月榜"
                            "text" to "个人主页"
                            "mongold_id" to entity?.user?.id
                        })
                        DirectUtils.directToHomeActivity(mContext, entity?.user?.id, 0, mEntrance, mPath)
                    }
                }
                listOf(gameCollectionTitleTv, moreIv).forEach {
                    it.setOnClickListener {
                        NewFlatLogUtils.logGameCollectionHotListClick(
                            GameCollectionHotListWrapperFragment.PLAYER_CREATION_TAB_NAME,
                            "",
                            "",
                            "游戏单"
                        )
                        SensorsBridge.trackEvent("ViewGameCollectHotRankTabClick", json {
                            "position" to 0
                            "tab_content" to if (mViewModel.isWeek) "周榜" else "月榜"
                            "text" to "游戏单"
                            "game_collect_title" to entity?.gameList?.title
                            "game_collect_id" to entity?.gameList?.id
                        })
                        DirectUtils.directToGameCollectionDetail(
                            mContext,
                            entity?.gameList?.id ?: "",
                            mEntrance,
                            mPath,
                            ExposureEvent.createEventWithSourceConcat(
                                null,
                                mBasicExposureSourceList,
                                listOf(ExposureSource("游戏单热榜-玩家创作榜", if (mViewModel.isWeek) "周榜" else "月榜"))
                            )
                        )
                    }
                }
            }
        }

        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 + HEADER_ITEM_COUNT + FOOTER_ITEM_COUNT else HEADER_ITEM_COUNT

    class GameCollectionPlayerCreationItemViewHolder(val binding: ItemGameCollectionPlayerCreationBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)

    class GameCollectionPlayerCreationHeaderItemViewHolder(val binding: ItemGameCollectionPlayerCreationHeaderBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)

    companion object {
        const val HEADER_ITEM_COUNT = 1
        const val FOOTER_ITEM_COUNT = 1
    }
}