package com.gh.gamecenter.gamedetail.detail.viewholder

import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DataCollectionUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewsUtils
import com.gh.gamecenter.GameNewsActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.databinding.ItemGameDetailRecyclerViewBinding
import com.gh.gamecenter.databinding.ItemGameDetailStrategyBinding
import com.gh.gamecenter.databinding.ItemGameDetailStrategyFixedTopBinding
import com.gh.gamecenter.feature.entity.NewsEntity
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.entity.ContentCardEntity
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import com.gh.gamecenter.gamedetail.entity.GameDetailStrategy
import com.gh.gamecenter.gamedetail.entity.GameDetailTabEntity
import com.gh.gamecenter.newsdetail.NewsDetailActivity

class GameDetailStrategyItemViewHolder(
    val binding: ItemGameDetailRecyclerViewBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel
) : BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {
    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val entity = data.linkGameGuide ?: return
        binding.run {
            titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
            moreTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_text_theme_12.toDrawable(context))
            titleTv.text = entity.name
            if (entity.rightTop == "link") {
                moreTv.text = "攻略专区"
                moreTv.isVisible = true
                moreTv.setOnClickListener {
                    val tabList = viewModel.gameDetailTabListLiveData.value?.data
                    if (tabList?.find { it.type == GameDetailTabEntity.TYPE_ZONE } != null) {
                        viewModel.performTabSelected(GameDetailTabEntity.TYPE_ZONE)
                    } else {
                        viewModel.performContentCardClicked(ContentCardEntity.TYPE_ZONE)
                    }
                    SensorsBridge.trackGameDetailModuleClick(
                        gameId,
                        gameName,
                        gameType,
                        "右上角",
                        moduleType,
                        entity.name,
                        sequence,
                        gameStatus = gameStatus
                    )
                }
            } else if (entity.rightTop == "more") {
                moreTv.text = "更多"
                moreTv.goneIf(entity.data.size < 3)
                moreTv.setOnClickListener {
                    val intent = GameNewsActivity.getIntent(
                        context,
                        viewModel.game?.name,
                        viewModel.game?.id,
                        viewModel.entrance + "+(游戏详情[" + viewModel.game?.name + "]:新手攻略-全部)"
                    )
                    context.startActivity(intent)
                    SensorsBridge.trackGameDetailModuleClick(
                        gameId,
                        gameName,
                        gameType,
                        "右上角",
                        moduleType,
                        entity.name,
                        sequence,
                        gameStatus = gameStatus
                    )
                }
            }

            if (recyclerView.adapter !is StrategyItemAdapter) {
                recyclerView.isNestedScrollingEnabled = false
                (recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                recyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                val dataList = if (entity.articleTop.isNotEmpty()) {
                    entity.articleTop.map { GameDetailStrategy.StrategyData(type = "article", linkArticle = it, isFixedTop = true) } + entity.data
                } else {
                    entity.data
                }
                recyclerView.adapter = StrategyItemAdapter(dataList)
            } else {
                recyclerView.adapter?.run { notifyItemRangeChanged(0, itemCount) }
            }
        }
    }

    inner class StrategyItemAdapter(val dataList: List<GameDetailStrategy.StrategyData>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun getItemViewType(position: Int): Int = if (dataList[position].isFixedTop) ITEM_FIXED_TOP else ITEM_NORMAL

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
            if (viewType == ITEM_FIXED_TOP) FixedTopStrategyItemViewHolder(parent.toBinding()) else StrategyItemViewHolder(parent.toBinding())

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val strategyData = dataList.getOrNull(position) ?: return
            val newsEntity = strategyData.linkArticle
            val communityArticleEntity = strategyData.linkCommunityArticle
            if (holder is StrategyItemViewHolder) {
                holder.binding.run {
                    root.updateLayoutParams<MarginLayoutParams> {
                        leftMargin = if (position == 0) 16F.dip2px() else 8F.dip2px()
                        rightMargin = if (position == itemCount - 1) 16F.dip2px() else 0
                    }
                    root.background = R.drawable.bg_shape_f8_radius_8.toDrawable(context)
                    titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                    contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    newsEntity?.let {
                        titleTv.text = it.title ?: ""
                        contentTv.text = it.intro ?: ""
                        timeTv.text =
                            if (TimeUtils.isToday(it.publishOn)) "今天" else TimeUtils.getFormatTime(it.publishOn)
                        root.setOnClickListener { _ ->
                            skipNewsDetail(it, position)
                            SensorsBridge.trackGameDetailModuleClick(
                                gameId,
                                gameName,
                                gameType,
                                "组件内容",
                                moduleType,
                                itemData?.linkGameGuide?.name,
                                sequence,
                                it.title,
                                position + 1,
                                linkType = "article",
                                linkId = it.id,
                                linkText = it.title,
                                gameStatus = gameStatus
                            )
                        }
                    }
                    communityArticleEntity?.let {
                        titleTv.text = it.title
                        contentTv.text = it.content
                        timeTv.text =
                            if (TimeUtils.isToday(it.time?.create ?: 0L)) "今天" else TimeUtils.getFormatTime(it.time?.create ?: 0L)
                        root.setOnClickListener { _ ->
                            DirectUtils.directToCommunityArticle(context, it.community, it.id, viewModel.entrance, "游戏详情-游戏攻略")
                            SensorsBridge.trackGameDetailModuleClick(
                                gameId,
                                gameName,
                                gameType,
                                "组件内容",
                                moduleType,
                                itemData?.linkGameGuide?.name,
                                sequence,
                                linkType = "community_article",
                                linkId = it.id,
                                linkText = it.title,
                                gameStatus = gameStatus
                            )
                        }
                    }

                }
            }
            if (holder is FixedTopStrategyItemViewHolder) {
                holder.binding.run {
                    root.updateLayoutParams<MarginLayoutParams> {
                        leftMargin = if (position == 0) 16F.dip2px() else 8F.dip2px()
                        rightMargin = if (position == itemCount - 1) 16F.dip2px() else 0
                    }
                    root.setCardBackgroundColor(com.gh.gamecenter.common.R.color.ui_container_1.toColor(context))
                    titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                    descTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    newsEntity?.let {
                        ImageUtils.display(backgroundIv, it.thumb)
                        titleTv.text = it.title ?: ""
                        descTv.text = it.type ?: ""
                        root.setOnClickListener { _ ->
                            skipNewsDetail(it, position)
                            SensorsBridge.trackGameDetailModuleClick(
                                gameId,
                                gameName,
                                gameType,
                                "组件内容",
                                moduleType,
                                itemData?.linkGameGuide?.name,
                                sequence,
                                linkType = "article",
                                linkId = it.id,
                                linkText = it.title,
                                gameStatus = gameStatus
                            )
                        }
                    }
                }
            }
        }

        override fun getItemCount(): Int = dataList.size

        private fun skipNewsDetail(article: NewsEntity, position: Int) {
            DataCollectionUtils.uploadClick(context, "新手攻略", "游戏详情", article.title)

            // 统计阅读量
            NewsUtils.statNewsViews(article.id)
            NewsDetailActivity.startNewsDetailActivity(
                context, article,
                viewModel.entrance + "+(游戏详情[" + viewModel.game?.name + "]:新手攻略-列表[" + (position + 1) + "])"
            )
        }
    }

    inner class StrategyItemViewHolder(val binding: ItemGameDetailStrategyBinding) :
        RecyclerView.ViewHolder(binding.root)

    inner class FixedTopStrategyItemViewHolder(val binding: ItemGameDetailStrategyFixedTopBinding) :
        RecyclerView.ViewHolder(binding.root)

    companion object {
        const val ITEM_FIXED_TOP = 0
        const val ITEM_NORMAL = 1
    }
}