package com.gh.gamecenter.mygame

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.exposure.ExposureEvent
import com.gh.common.exposure.ExposureSource
import com.gh.common.exposure.IExposable
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.ItemFollowedGameBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.game.GameItemViewHolder
import com.gh.gamecenter.gamedetail.GameDetailFragment

class MyFollowedGameAdapter(context: Context, var mViewModel: MyFollowedGameViewModel) :
    ListAdapter<GameEntity>(context), IExposable {

    private val mEntrance = "(我的关注)"
    private val mExposureEventSparseArray: SparseArray<ExposureEvent> = SparseArray()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.GAME_NORMAL -> {
                MyFollowedGameViewHolder(
                    ItemFollowedGameBinding.bind(
                        mLayoutInflater.inflate(
                            R.layout.item_followed_game,
                            parent,
                            false
                        )
                    )
                )
            }
            else -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) {
            return ItemViewType.ITEM_FOOTER
        }
        return ItemViewType.GAME_NORMAL
    }

    override fun getItemCount(): Int {
        return if (mEntityList == null || mEntityList.isEmpty()) return 0 else mEntityList.size + 1
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is MyFollowedGameViewHolder -> {
                val gameEntity = mEntityList[position]
                val path = "关注Tab"
                val newPath = "关注Tab_新"

                holder.run {
                    binding.run {
                        gameItemIncluded.run {
                            root.background = null
                            gameKaifuType.setBackgroundColor(R.color.theme.toColor(root.context))
                            gameName.setTextColor(R.color.text_title.toColor(root.context))
                            gameDes.setTextColor(R.color.text_subtitleDesc.toColor(root.context))
                            recommendStarPref.setTextColor(R.color.text_subtitleDesc.toColor(root.context))
                            cardContainer.background = R.drawable.bg_shape_space_radius_8.toDrawable(root.context)

                            gameIconView.displayGameIcon(gameEntity)
                            BindingAdapters.setGameName(gameName, gameEntity, false, null)
                            BindingAdapters.setTextSize(gameRating, if (gameEntity.commentCount > 3) 12 else 10)
                            BindingAdapters.setGameTags(labelList, gameEntity)
                            gameRating.setDrawableStart(if (gameEntity.commentCount > 3) R.drawable.game_horizontal_rating.toDrawable() else null)
                            gameRating.setPadding(0, 0, if (gameEntity.commentCount > 3) 8F.dip2px() else 0, 0)
                            gameRating.text = if (gameEntity.commentCount > 3) {
                                if (gameEntity.star == 10.0F) "10" else gameEntity.star.toString()
                            } else ""
                            gameRating.setTextColor(
                                if (gameEntity.commentCount > 3) R.color.theme_font.toColor(mContext) else R.color.theme.toColor(
                                    mContext
                                )
                            )
                            gameDes.text = gameEntity.decoratedDes
                            recommendStar.rating = gameEntity.recommendStar.toFloat()
                            GameItemViewHolder.initGameSubtitle(gameEntity, gameSubtitleTv, gameDesSpace, root)
                        }
                        root.background = R.drawable.reuse_listview_item_style.toDrawable(root.context)
                        listOf(forumTv, trendsTv, commentsTv).forEach {
                            it.setTextColor(R.color.text_subtitle.toColor(mContext))
                        }
                        initServerType(gameEntity)
                        initShortcut(gameEntity, mEntrance, path, newPath)
                        updateConcernButton(gameEntity, mViewModel)
                    }

                    val exposureEvent = ExposureEvent.createEvent(
                        gameEntity,
                        listOf(ExposureSource("我的游戏", "关注"))
                    )
                    mExposureEventSparseArray.append(position, exposureEvent)

                    itemView.setOnClickListener {
                        MtaHelper.onEvent("我的光环", path, "点击其他位置")
                        MtaHelper.onEvent("我的光环", newPath, "点击其他位置")
                        MtaHelper.onEvent("我的光环_新", path, "点击其他位置")
                        NewFlatLogUtils.logMyGameFollowTabGameCardClick(
                            "游戏详情",
                            gameEntity.id,
                            gameEntity.name ?: ""
                        )
                        GameDetailActivity.startGameDetailActivity(mContext, gameEntity.id, mEntrance, exposureEvent)
                    }
                }
            }
            is FooterViewHolder -> {
                // 本列表不需要分页
                holder.run {
                    initItemPadding()
                    loading.visibility = View.GONE
                    hint.text = "没有更多了"
                    itemView.setOnClickListener {
                        if (mIsNetworkError) {
                            mViewModel.load(LoadType.RETRY)
                        }
                    }
                }
            }
        }
    }

    override fun getEventByPosition(pos: Int): ExposureEvent = mExposureEventSparseArray.get(pos)

    override fun getEventListByPosition(pos: Int) = null
}

class MyFollowedGameViewHolder(var binding: ItemFollowedGameBinding) : RecyclerView.ViewHolder(binding.root) {

    fun updateConcernButton(gameEntity: GameEntity, viewModel: MyFollowedGameViewModel) {
        binding.run {
            if (gameEntity.isRelated) {
                gameItemIncluded.downloadBtn.layoutParams = gameItemIncluded.downloadBtn.layoutParams.apply {
                    width = 72F.dip2px()
                    height = 28F.dip2px()
                }
                gameItemIncluded.downloadBtn.text = "关联关注"
                gameItemIncluded.downloadBtn.setTextColor(R.color.text_subtitleDesc.toColor(root.context))
                gameItemIncluded.downloadBtn.background = R.drawable.button_round_border_eeeeee.toDrawable(root.context)

                gameItemIncluded.downloadBtn.setOnClickListener { }
            } else {
                gameItemIncluded.downloadBtn.layoutParams = gameItemIncluded.downloadBtn.layoutParams.apply {
                    width = 56F.dip2px()
                    height = 28F.dip2px()
                }
                gameItemIncluded.downloadBtn.text = "已关注"
                gameItemIncluded.downloadBtn.setTextColor(R.color.text_subtitleDesc.toColor(root.context))
                gameItemIncluded.downloadBtn.background = R.drawable.button_round_gray_light.toDrawable(root.context)

                gameItemIncluded.downloadBtn.setOnClickListener {
                    NewFlatLogUtils.logMyGameFollowTabGameCardClick(
                        "取消关注",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                    DialogHelper.showDialog(root.context, "取消关注",
                        root.context.getString(com.gh.gamecenter.common.R.string.cancel_concern_dialog),
                        "确定取消",
                        "暂不取消", confirmClickCallback = {
                            viewModel.unfollowGame(gameEntity)
                            NewFlatLogUtils.logMyGameCancelFollowDialogClick(
                                "确定取消", gameEntity.id,
                                gameEntity.name ?: ""
                            )
                        }, cancelClickCallback = {
                            NewFlatLogUtils.logMyGameCancelFollowDialogClick(
                                "关闭弹窗", gameEntity.id,
                                gameEntity.name ?: ""
                            )
                        }, uiModificationCallback = {
                            it.confirmTv.setTextColor(R.color.theme_red.toColor(root.context))
                        }, extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                    )
                }
            }
        }
    }

    fun initServerType(gameEntity: GameEntity) {
        val serverLabel = gameEntity.serverLabel
        when {
            gameEntity.test != null -> {
                binding.gameItemIncluded.gameKaifuType.visibility = View.GONE
                binding.gameItemIncluded.gameKaifuType.text = ""
            }
            serverLabel != null && !gameEntity.advanceDownload -> {
                binding.gameItemIncluded.gameKaifuType.visibility = View.VISIBLE
                binding.gameItemIncluded.gameKaifuType.text = serverLabel.value
                if (gameEntity.isUseDefaultServerStyle()) {
                    binding.gameItemIncluded.gameKaifuType.background =
                        R.drawable.server_label_default_bg.toDrawable(binding.root.context)
                    binding.gameItemIncluded.gameKaifuType.setTextColor(R.color.text_server_label.toColor(binding.root.context))
                } else {
                    binding.gameItemIncluded.gameKaifuType.background =
                        DrawableView.getServerDrawable(serverLabel.color)
                    binding.gameItemIncluded.gameKaifuType.setTextColor(R.color.white.toColor(binding.root.context))
                }
            }
            else -> binding.gameItemIncluded.gameKaifuType.visibility = View.GONE
        }

        // 由于RecyclerView的复用机制 需要每次测量gameName的宽
        binding.gameItemIncluded.gameName.requestLayout()
    }

    fun initShortcut(gameEntity: GameEntity, entrance: String, path: String, newPath: String) {
        if (gameEntity.isRatingOpen) {
            binding.commentsContainer.visibility = View.VISIBLE
            binding.commentsContainer.setOnClickListener {
                MtaHelper.onEvent("我的光环", path, "评论入口")
                MtaHelper.onEvent("我的光环_新", newPath, "评论入口")
                MtaHelper.onEvent("我的光环_新", path, "评论入口")
                when (path) {
                    "关注Tab" -> NewFlatLogUtils.logMyGameFollowTabGameCardClick(
                        "评论",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                    "预约Tab" -> NewFlatLogUtils.logMyGameReserveTabGameCardClick(
                        "评论",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                }

                GameDetailActivity.startGameDetailActivity(
                    binding.root.context,
                    gameEntity,
                    entrance,
                    isSkipGameComment = true
                )
            }
        } else {
            binding.commentsContainer.visibility = View.GONE
        }

        if (gameEntity.isZoneOpen) {
            binding.trendsContainer.visibility = View.VISIBLE
            binding.trendsContainer.setOnClickListener {
                MtaHelper.onEvent("我的光环", path, "动态入口")
                MtaHelper.onEvent("我的光环_新", newPath, "专区入口")
                MtaHelper.onEvent("我的光环_新", path, "动态入口")
                when (path) {
                    "关注Tab" -> NewFlatLogUtils.logMyGameFollowTabGameCardClick(
                        "专区",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                    "预约Tab" -> NewFlatLogUtils.logMyGameReserveTabGameCardClick(
                        "专区",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                }

                GameDetailActivity.startGameDetailActivity(
                    binding.root.context,
                    gameEntity,
                    entrance,
                    defaultTab = GameDetailFragment.INDEX_TRENDES
                )
            }
        } else {
            binding.trendsContainer.visibility = View.GONE
        }

        if (gameEntity.isBbsOpen) {
            binding.forumContainer.visibility = View.VISIBLE
            binding.forumContainer.setOnClickListener {
                when (path) {
                    "关注Tab" -> NewFlatLogUtils.logMyGameFollowTabGameCardClick(
                        "论坛",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                    "预约Tab" -> NewFlatLogUtils.logMyGameReserveTabGameCardClick(
                        "论坛",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                }
                GameDetailActivity.startGameDetailActivity(
                    binding.root.context,
                    gameEntity,
                    entrance,
                    defaultTab = GameDetailFragment.INDEX_BBS
                )
            }
        } else {
            binding.forumContainer.visibility = View.GONE
        }

        binding.cardContainer.isVisible = gameEntity.isRatingOpen || gameEntity.isZoneOpen || gameEntity.isBbsOpen
        binding.cardContainer.dividerDrawable = R.drawable.divider_my_follow.toDrawable(binding.cardContainer.context)
    }

}