package com.gh.gamecenter.home.custom.adapter

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.core.util.forEach
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.AsyncCell
import com.gh.gamecenter.databinding.ItemHomeGameCollectionBigSlideCardCustomBinding
import com.gh.gamecenter.databinding.ItemHomeGameCollectionBigSlideCardGameBinding
import com.gh.gamecenter.databinding.ItemHomeGameCollectionSmallSlideCardCustomBinding
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.eventbus.EBPackage
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureListProvider
import com.gh.gamecenter.home.custom.IGameChangedNotifier
import com.gh.gamecenter.home.custom.eventlistener.GameSubjectCollectionEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageData
import com.gh.gamecenter.home.custom.model.CustomSubjectCollectionItem
import com.lightgame.download.DownloadEntity

class CustomHomeGameCollectionSlideAdapter(
    context: Context,
    private var mIsBigSlide: Boolean,
    private val entrance: String,
    private val eventHelper: GameSubjectCollectionEventHelper
) : CustomBaseChildAdapter<CustomPageData.LinkColumnCollection.CustomSubjectEntity, RecyclerView.ViewHolder>(context) {

    private val mBigSlideViewHolderList = SparseArray<HomeGameCollectionBigSlideCardViewHolder>()

    private lateinit var data: CustomSubjectCollectionItem

    fun setData(data: CustomSubjectCollectionItem) {
        this.data = data
        submitList(data.data.data)
    }

    override fun getKey(t: CustomPageData.LinkColumnCollection.CustomSubjectEntity): String {
        return t.id
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
        if (mIsBigSlide) {
            HomeGameCollectionBigSlideCardViewHolder(
                HomeGameCollectionBigSlideCardCell(context).apply { inflate() }
            ).apply {
                mBigSlideViewHolderList.put(mBigSlideViewHolderList.size(), this)
            }
        } else {
            HomeGameCollectionSmallSlideCardViewHolder(parent.toBinding())
        }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val subject = getItem(position)
        val games = subject.games

        // 大卡片
        if (holder is HomeGameCollectionBigSlideCardViewHolder) {
            holder.bindView(subject)
            (holder.itemView as HomeGameCollectionBigSlideCardCell).bindWhenInflated {
                (holder.itemView as HomeGameCollectionBigSlideCardCell).binding?.run {
                    val params = root.layoutParams as ViewGroup.MarginLayoutParams
                    params.leftMargin = if (position == 0) 0 else (-24F).dip2px()

                    if (subject.user.isValid) {
                        gUser.goneIf(false)
                        ImageUtils.display(userIv, subject.user.icon)
                        userTv.text = subject.user.name
                        listOf(userIv, userTv).forEach {
                            it.setOnClickListener {
                                eventHelper.onUserClick(subject.user.id)
                            }
                        }
                    } else {
                        gUser.goneIf(true)
                    }
                    ImageUtils.display(coverImage, subject.image)

                    titleTv.text = subject.title

                    listOf(gameItem1, gameItem2, gameItem3).forEachIndexed { index, binding ->
                        binding.root.goneIf(games.size < index + 1) {
                            val gameEntity = games[index]
                            holder.updateGameItem(binding, gameEntity)
                        }
                    }

                    divider.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(context))
                    moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    container.background = R.drawable.bg_item_game_test_v2.toDrawable(context)

                    moreTv.text = "查看全部${subject.count.game}款游戏"
                    root.setOnClickListener {
                        eventHelper.navigateSubjectCollectionPage(position, subject)
                    }
                }
            }
        }

        // 小卡片
        if (holder is HomeGameCollectionSmallSlideCardViewHolder) {
            holder.updateSubject(subject)
            holder.binding.run {
                val params = root.layoutParams as ViewGroup.MarginLayoutParams
                params.leftMargin = if (position == 0) 0 else (-24F).dip2px()

                if (subject.user.isValid) {
                    gUser.goneIf(false)
                    userTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                    userTv.text = subject.user.name
                    ImageUtils.display(userIv, subject.user.icon)
                    listOf(userIv, userTv).forEach {
                        it.setOnClickListener {
                            eventHelper.onUserClick(subject.user.id)
                        }
                    }
                } else {
                    gUser.goneIf(true)
                }
                container.background = R.drawable.bg_item_game_test_v2.toDrawable(context)
                titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))

                ImageUtils.display(coverImage, subject.image)
                titleTv.text = subject.title

                subject.count.let { gameCountTv.text = "+${it.game - games.size}" }
                var showGameCount = 0
                listOf(gameIcon1, gameIcon2, gameIcon3).forEachIndexed { index, gameIcon ->
                    gameIcon.goneIf(games.size < index + 1) {
                        val gameEntity = games[index]
                        gameIcon.displayGameIcon(gameEntity)
                        gameIcon.setBorderColor(com.gh.gamecenter.common.R.color.ui_surface)
                        gameIcon.setOnClickListener {
                            eventHelper.navigateToGameDetailPage(index, gameEntity, subject)
                        }
                        showGameCount = index + 1
                    }
                }

                val moreCount = subject.count.game - showGameCount
                gameCountTv.goneIf(moreCount <= 0) {
                    gameCountTv.text = "+$moreCount"
                }

                root.setOnClickListener {
                    eventHelper.navigateSubjectCollectionPage(position, subject)
                }
            }
        }
    }

    override fun notifyDownload(download: DownloadEntity) {
        mBigSlideViewHolderList.forEach { _, it ->
            it.notifyDownload(download)
        }
    }

    override fun notifyDownloadDeleted(status: EBDownloadStatus) {
        mBigSlideViewHolderList.forEach { _, it ->
            it.notifyDownloadDeleted(status)
        }
    }

    override fun notifyInstalled(busFour: EBPackage) {
        mBigSlideViewHolderList.forEach { _, it ->
            it.notifyInstalled(busFour)
        }
    }

    private inner class HomeGameCollectionBigSlideCardCell(context: Context) : AsyncCell(context) {
        var binding: ItemHomeGameCollectionBigSlideCardCustomBinding? = null

        override val layoutId = R.layout.item_home_game_collection_big_slide_card_custom
        override val switchToWrapContentWhenInflated = true
        override fun createDataBindingView(view: View): View? {
            binding = ItemHomeGameCollectionBigSlideCardCustomBinding.bind(view)
            return view.rootView
        }
    }

    inner class HomeGameCollectionBigSlideCardViewHolder(view: View) :
        BaseRecyclerViewHolder<Any>(view),
        IGameChangedNotifier,
        IExposureListProvider {

        private var subject: CustomPageData.LinkColumnCollection.CustomSubjectEntity? = null

        fun bindView(subject: CustomPageData.LinkColumnCollection.CustomSubjectEntity) {
            this.subject = subject
        }

        override fun notifyDownload(download: DownloadEntity) {
            subject?.games?.forEachIndexed { index, item ->
                val hasApk = item.getApk().any {
                    it.packageName == download.packageName
                }
                if (hasApk && item.id == download.gameId) {
                    item.getEntryMap()[download.platform] = download
                    (itemView as? HomeGameCollectionBigSlideCardCell)?.binding?.run {
                        when (index) {
                            0 -> updateGameItem(gameItem1, item)
                            1 -> updateGameItem(gameItem2, item)
                            2 -> updateGameItem(gameItem3, item)
                        }
                    }
                }
            }
        }

        override fun notifyDownloadDeleted(status: EBDownloadStatus) {
            checkResetData()
        }

        override fun notifyInstalled(busFour: EBPackage) {
            checkResetData()
        }

        fun checkResetData() {
            val games = subject?.games ?: arrayListOf()
            (itemView as HomeGameCollectionBigSlideCardCell).binding?.run {
                listOf(gameItem1, gameItem2, gameItem3).forEachIndexed { index, binding ->
                    binding.root.goneIf(games.size < index + 1) {
                        val gameEntity = games[index]
                        updateGameItem(binding, gameEntity)
                    }
                }
            }
        }

        fun updateGameItem(
            binding: ItemHomeGameCollectionBigSlideCardGameBinding,
            gameEntity: GameEntity
        ) {
            binding.root.visibility = View.VISIBLE

            binding.gameIconIv.displayGameIcon(gameEntity)
            binding.gameNameTv.text = gameEntity.name
            binding.gameNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            binding.gameDesTv.text = gameEntity.brief
            binding.gameDesTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))

            DownloadItemUtils.setOnClickListener(
                context,
                binding.downloadBtn,
                gameEntity,
                bindingAdapterPosition,
                null,
                entrance,
                location = "游戏单合集",
                traceEvent = gameEntity.exposureEvent,
                clickCallback = {
                    eventHelper.onDownloadButtonClick(bindingAdapterPosition, gameEntity, subject)
                },
                refreshCallback = {
                    DownloadItemUtils.updateItem(
                        context,
                        gameEntity,
                        GameViewHolder(binding.root).apply {
                            gameDownloadBtn = binding.downloadBtn
                            gameDownloadTips = binding.downloadTipsLottie
                            multiVersionDownloadTv = binding.multiVersionDownloadTv
                        },
                        true
                    )
                },
                allStateClickCallback = null
            )

            DownloadItemUtils.updateItem(
                context,
                gameEntity,
                GameViewHolder(binding.root).apply {
                    gameDownloadBtn = binding.downloadBtn
                    gameDownloadTips = binding.downloadTipsLottie
                    multiVersionDownloadTv = binding.multiVersionDownloadTv
                },
                false
            )

            binding.root.setOnClickListener {
                NewFlatLogUtils.logGameListCollectionClick(
                    entrance,
                    "",
                    "",
                    subject?.title ?: "",
                    subject?.id ?: "",
                    "游戏"
                )

                eventHelper.navigateToGameDetailPage(bindingAdapterPosition, gameEntity, subject)
            }
        }

        override fun provideExposureDataList(): List<ExposureEvent>? {
            return subject?.games?.map {
                it.exposureEvent?.getFreshExposureEvent()!!
            }
        }

        override fun provideExposureData(): ExposureEvent? = null

    }

    class HomeGameCollectionSmallSlideCardViewHolder(val binding: ItemHomeGameCollectionSmallSlideCardCustomBinding) :
        RecyclerView.ViewHolder(binding.root),
        IExposureListProvider {

        private var boundedSubject: CustomPageData.LinkColumnCollection.CustomSubjectEntity? = null

        fun updateSubject(subject: CustomPageData.LinkColumnCollection.CustomSubjectEntity) {
            boundedSubject = subject
        }

        override fun provideExposureDataList(): List<ExposureEvent>? {
            return boundedSubject?.games?.map {
                it.exposureEvent?.getFreshExposureEvent()!!
            }
        }

        override fun provideExposureData(): ExposureEvent? = null
    }
}