package com.gh.gamecenter.mygame

import android.content.Context
import android.util.SparseArray
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.databind.BindingAdapters
import com.gh.common.exposure.IExposable
import com.gh.common.util.DownloadItemUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.ReservationHelper
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.callback.CancelListener
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.ItemFollowedGameBinding
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.game.GameAndPosition

class MyReservationAdapter(context: Context, var mViewModel: MyReservationViewModel) : 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.binding.run {
                    root.background = R.drawable.reuse_listview_item_style.toDrawable(root.context)
                    listOf(forumTv, trendsTv, commentsTv).forEach {
                        it.setTextColor(R.color.text_subtitle.toColor(mContext))
                    }
                    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))

                        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(mContext) 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.initGameSubtitleAndAdLabel(gameEntity, gameSubtitleTv)
                    }
                }

                holder.initServerType(gameEntity)
                holder.initShortcut(gameEntity, mEntrance, path, newPath)

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

                DownloadItemUtils.updateItemWithReserveStatus(
                    GameViewHolder(holder.binding.gameItemIncluded),
                    gameEntity
                )

                holder.itemView.setOnClickListener {
                    MtaHelper.onEvent("我的光环", path, "点击其他位置")
                    MtaHelper.onEvent("我的光环", newPath, "点击其他位置")
                    MtaHelper.onEvent("我的光环_新", path, "点击其他位置")
                    NewFlatLogUtils.logMyGameReserveTabGameCardClick(
                        "游戏详情",
                        gameEntity.id,
                        gameEntity.name ?: ""
                    )
                    GameDetailActivity.startGameDetailActivity(mContext, gameEntity.id, mEntrance, exposureEvent)
                }

                if ("appointment" == gameEntity.reserveStatus) {
                    holder.binding.gameItemIncluded.downloadBtn.setOnClickListener {
                        showCancelReservationDialog(gameEntity)
                    }
                } else {
                    DownloadItemUtils.setOnClickListener(
                        mContext,
                        holder.binding.gameItemIncluded.downloadBtn,
                        gameEntity,
                        position,
                        this,
                        mEntrance,
                        StringUtils.buildString(mEntrance, ":", gameEntity.name), exposureEvent
                    )
                }
                initDownloadButtonOffset(holder.binding)
                holder.binding.root.setOnLongClickListener {
                    showCancelReservationDialog(gameEntity)
                    true
                }
            }
            is FooterViewHolder -> {
                holder.initItemPadding()
                holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
            }
        }
    }

    fun notifyItemAndRemoveDownload(status: EBDownloadStatus) {
        val data = getGameEntityByPackage(status.packageName)
        for (gameAndPosition in data) {
            if (gameAndPosition.entity != null && gameAndPosition.entity.name == status.name) {
                gameAndPosition.entity.getEntryMap().remove(status.platform)
            }
            notifyItemChanged(gameAndPosition.position)
        }
    }

    fun getGameEntityByPackage(packageName: String): List<GameAndPosition> {
        val positionList = ArrayList<GameAndPosition>()
        val positionMap = mViewModel.positionAndPackageMap
        for (key in positionMap.keys) {
            if (key.contains(packageName)) {
                val position = positionMap[key]!!
                val game = entityList?.safelyGetInRelease(position)
                if (game != null) {
                    positionList.add(GameAndPosition(game, position))
                }
            }
        }
        return positionList
    }

    private fun initDownloadButtonOffset(binding: ItemFollowedGameBinding) {
        (binding.gameItemIncluded.downloadBtn.layoutParams as ViewGroup.MarginLayoutParams).apply {
            topMargin = DisplayUtils.dip2px(9F)
        }
    }

    private fun showDeleteReservationDialog(game: GameEntity) {
        ReservationHelper.showDeleteReservationDialog(mContext, object : EmptyCallback {
            override fun onCallback() {
                mViewModel.deleteReservation(game)
            }
        })
    }

    private fun showCancelReservationDialog(game: GameEntity) {
        NewFlatLogUtils.logMyGameReserveTabGameCardClick("按钮", game.id, game.name ?: "")
        ReservationHelper.showCancelReservationDialog(mContext, {
            NewFlatLogUtils.logMyGameCancelReserveDialogClick("确定取消", game.id, game.name ?: "")
            mViewModel.cancelReservation(game)
        }, object : CancelListener {
            override fun onCancel() {
                NewFlatLogUtils.logMyGameCancelReserveDialogClick("关闭弹窗", game.id, game.name ?: "")
            }
        })
    }

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

    override fun getEventListByPosition(pos: Int) = null

}