package com.gh.gamecenter.collection

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.util.SparseArray
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameCollectionItemViewHolder
import com.gh.gamecenter.collection.GamesCollectionFragment.Companion.TYPE_USER
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.syncpage.ISyncAdapterHandler
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.NumberUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.ItemGameCollectionFlexTagBinding
import com.gh.gamecenter.databinding.PopupHistoryOptionBinding
import com.gh.gamecenter.entity.GamesCollectionEntity
import com.gh.gamecenter.entity.TagInfoEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureType
import com.gh.gamecenter.gamecollection.detail.GameCollectionDetailActivity
import com.gh.gamecenter.gamecollection.publish.GameCollectionEditActivity
import com.gh.gamecenter.history.ManageOption
import com.gh.gamecenter.login.user.UserManager
import com.google.android.flexbox.FlexboxLayout

class GamesCollectionAdapter(
    context: Context,
    private val mViewModel: GamesCollectionViewModel,
) : ListAdapter<GamesCollectionEntity>(context), ISyncAdapterHandler, IExposable {

    private var mCurrentOption = ManageOption.OPTION_MANAGER
    private var mPopWindow: PopupWindow? = null
    private var mPopupBinding: PopupHistoryOptionBinding? = null
    var selectItems = arrayListOf<String>()
    private var mExposureEventArray: SparseArray<ExposureEvent>? = null


    override fun setListData(updateData: MutableList<GamesCollectionEntity>?) {
        mExposureEventArray = SparseArray(updateData?.size ?: 0)
        super.setListData(updateData)
    }

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

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

    fun changeOption(option: ManageOption) {
        mCurrentOption = option
        when (mCurrentOption) {
            ManageOption.OPTION_MANAGER -> {
                selectItems.clear()
                mPopWindow?.dismiss()
                mPopWindow = null
            }
            else -> {
                if (mPopWindow == null || mPopWindow?.isShowing == false) {
                    showOptionWindow()
                }
            }
        }
        notifyItemRangeChanged(0, mEntityList.size)
    }

    override fun areItemsTheSame(oldItem: GamesCollectionEntity?, newItem: GamesCollectionEntity?): Boolean {
        return oldItem == newItem || oldItem?.id == newItem?.id
    }

    override fun areContentsTheSame(oldItem: GamesCollectionEntity?, newItem: GamesCollectionEntity?): Boolean {
        return oldItem?.id == newItem?.id
                && oldItem?.title == newItem?.title
                && oldItem?.intro == newItem?.intro
                && oldItem?.cover == newItem?.cover
                && oldItem?.display == newItem?.display
                && oldItem?.status == newItem?.status
                && oldItem?.count?.game == newItem?.count?.game
                && oldItem?.getTagIds() == newItem?.getTagIds()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_BODY -> GameCollectionItemViewHolder(parent.toBinding())

            else -> FooterViewHolder(mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false))
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameCollectionItemViewHolder -> {
                val itemEntity = mEntityList[position]
                val exposureEvent = ExposureEvent.createEvent(
                    GameEntity().apply {
                        sequence = position
                    },
                    listOf(
                        ExposureSource("个人主页", ""),
                        ExposureSource("游戏单", "${itemEntity.title}+${itemEntity.id}")
                    ),
                    null,
                    ExposureType.EXPOSURE
                )
                mExposureEventArray?.put(position, exposureEvent)

                val path = when (mViewModel.type) {
                    GamesCollectionFragment.TYPE_COLLECT -> "我的收藏-游戏单"
                    GamesCollectionFragment.TYPE_HISTORY -> "浏览记录-游戏单"
                    GamesCollectionFragment.TYPE_USER -> "个人主页-游戏单"
                    else -> ""
                }

                holder.binding.run {
                    ImageUtils.display(poster, itemEntity.cover)
                    nameTv.text = itemEntity.title
                    tagIv.goneIf(itemEntity.stamp.isEmpty())

                    val gameIconList = listOf(gameOne, gameTwo, gameThree)
                    itemEntity.games?.take(3)?.forEachIndexed { index, game ->
                        gameIconList[index].displayGameIcon(game.toGameEntity())
                    }
                    itemEntity.games?.size?.let {
                        gameOne.goneIf(it == 0)
                        gameTwo.goneIf(it < 2)
                        gameThree.goneIf(it < 3)
                    }

                    moreNumTv.goneIf((itemEntity.count?.game ?: 0) < 4 || itemEntity.games?.size == 0)
                    moreNumTv.text = "+ " + ((itemEntity.count?.game ?: 0) - 3)
                    tagContainer.goneIf(itemEntity.count?.game != 0)
                    timeTv.text = TimeUtils.getFormatTime(itemEntity.time?.update ?: 0, "MM - dd")
                    ImageUtils.display(userIcon, itemEntity.user?.icon)
                    userName.text = itemEntity.user?.name
                    voteCount.text = if (itemEntity.count?.vote == 0) "赞同" else NumberUtils.transNewSimpleCount(
                        itemEntity.count?.vote ?: 0, "#"
                    )
                    voteCount.setTextColor(
                        if (itemEntity.me?.isVoted == true) com.gh.gamecenter.common.R.color.text_theme.toColor(mContext) else com.gh.gamecenter.common.R.color.white.toColor(
                            mContext
                        )
                    )
                    voteIcon.isChecked = itemEntity.me?.isVoted == true
                    commentCount.text =
                        if (itemEntity.count?.comment == 0) "评论" else NumberUtils.transNewSimpleCount(
                            itemEntity.count?.comment ?: 0, "#"
                        )

                    moreIv.goneIf(
                        mViewModel.type != TYPE_USER
                                || mViewModel.mIsInsertGameCollection
                                || itemEntity.user?.id != UserManager.getInstance().userId
                    )

                    when (itemEntity.stamp) {
                        "special_choice" -> {
                            tagIv.setBackgroundResource(R.drawable.ic_chosen)
                        }
                        "official" -> {
                            tagIv.setBackgroundResource(R.drawable.ic_official)
                        }
                    }

                    if (itemEntity.count?.game ?: 0 == 0) {
                        initTagsUI(tagContainer, itemEntity.tags ?: arrayListOf())
                    }

                    selectIv.goneIf(mCurrentOption == ManageOption.OPTION_MANAGER)
                    selectIv.isChecked = selectItems.contains(itemEntity.id)

                    when {
                        mViewModel.mIsInsertGameCollection -> {
                            userIcon.visibility = View.VISIBLE
                            userName.visibility = View.VISIBLE
                            timeTv.visibility = View.GONE
                            myselfTag.visibility = View.GONE
                        }

                        mViewModel.type == TYPE_USER && itemEntity.display == "self_only" -> {
                            userIcon.visibility = View.GONE
                            userName.visibility = View.GONE
                            timeTv.visibility = View.GONE
                            myselfTag.visibility = View.VISIBLE
                        }

                        mViewModel.type == TYPE_USER && itemEntity.display != "self_only" -> {
                            userIcon.visibility = View.GONE
                            userName.visibility = View.GONE
                            timeTv.visibility = View.VISIBLE
                            myselfTag.visibility = View.GONE
                        }

                        else -> {
                            userIcon.visibility = View.VISIBLE
                            userName.visibility = View.VISIBLE
                            timeTv.visibility = View.GONE
                            myselfTag.visibility = View.GONE
                        }
                    }

                    if (!mViewModel.mIsInsertGameCollection) {
                        moreIv.setOnClickListener {
                            showOptionPopupWindow(moreIv, itemEntity)
                        }

                        myselfTag.setOnClickListener {
                            DialogHelper.showDialog(
                                mContext,
                                "仅自己可见",
                                "游戏单开启“仅自己可见”后，将不会对其他用户展示，您可以通过关闭仅自己可见或者投稿分享游戏单",
                                "我知道了",
                                "",
                                {

                                },
                                extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                            )
                        }

                        gameIconList.forEachIndexed { index, gameIcon ->
                            gameIcon.setOnClickListener {
                                GameDetailActivity.startGameDetailActivity(
                                    mContext,
                                    itemEntity.games?.safelyGetInRelease(index)?.id ?: "",
                                    ""
                                )
                            }
                        }

                        userIcon.setOnClickListener {
                            DirectUtils.directToHomeActivity(mContext, itemEntity.user?.id, "", path)
                        }
                        userName.setOnClickListener { userIcon.performClick() }

                        commentCountContainer.setOnClickListener {
                            NewLogUtils.logEnterGameCollectionDetail(itemEntity.title, itemEntity.id)
                            mContext.startActivity(
                                GameCollectionDetailActivity.getIntent(
                                    mContext,
                                    itemEntity.id,
                                    isScrollToCommentArea = true,
                                    exposureSourceList = ArrayList(exposureEvent.source),
                                    entrance = path
                                )
                            )
                        }

                        voteCountContainer.setOnClickListener {
                            if (itemEntity.display == "self_only") {
                                ToastUtils.toast("游戏单为仅自己可见状态")
                                return@setOnClickListener
                            }
                            debounceActionWithInterval(R.id.vote_count_container, 1000) {
                                CheckLoginUtils.checkLogin(mContext, "个人主页-游戏单-点赞") {
                                    mViewModel.postVoteGameCollection(
                                        itemEntity.id,
                                        !voteIcon.isChecked
                                    ) {
                                        if (!voteIcon.isChecked) {
                                            voteCount.setTextColor(com.gh.gamecenter.common.R.color.text_white.toColor())
                                            voteIcon.isChecked = true
                                            voteIcon.visibility = View.VISIBLE

                                            itemEntity.me?.isVoted = true
                                            itemEntity.count?.run {
                                                vote++
                                                voteCount.text =
                                                    if (vote == 0) "赞同" else vote.toNewSimpleCount()
                                            }
                                        } else {
                                            voteIcon.isChecked = false
                                            itemEntity.me?.isVoted = false
                                            itemEntity.count?.run {
                                                vote--
                                                if (vote < 0) vote = 0
                                                voteCount.setTextColor(com.gh.gamecenter.common.R.color.white.toColor())
                                                voteCount.text =
                                                    if (vote == 0) "赞同" else vote.toNewSimpleCount()
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    root.setOnClickListener {
                        if (mViewModel.mIsInsertGameCollection) {
                            val entity = GamesCollectionEntity().apply {
                                id = itemEntity.id
                                title = itemEntity.title
                                intro = itemEntity.intro
                            }
                            val intent = Intent().apply {
                                putExtra(GamesCollectionEntity::class.java.simpleName, entity)
                            }
                            (mContext as AppCompatActivity).setResult(Activity.RESULT_OK, intent)
                            (mContext as AppCompatActivity).finish()
                        } else {
                            if (mCurrentOption == ManageOption.OPTION_MANAGER) {
                                NewLogUtils.logEnterGameCollectionDetail(itemEntity.title, itemEntity.id)
                                mContext.startActivity(
                                    GameCollectionDetailActivity.getIntent(
                                        mContext,
                                        itemEntity.id,
                                        exposureSourceList = ArrayList(exposureEvent.source),
                                        entrance = path
                                    )
                                )
                            } else {
                                if (selectItems.contains(itemEntity.id)) {
                                    selectItems.remove(itemEntity.id)
                                } else {
                                    selectItems.add(itemEntity.id)
                                }
                                checkSelectItems()
                                notifyItemChanged(position)
                            }
                        }
                    }

                    if (mViewModel.type == GamesCollectionFragment.TYPE_HISTORY) {
                        root.setOnLongClickListener {
                            consume {
                                DialogHelper.showDialog(mContext,
                                    "删除记录",
                                    "删除浏览记录将不可恢复，确定删除吗？",
                                    "确定",
                                    "取消", {
                                        mViewModel.removeHistory(itemEntity)
                                    })
                            }
                        }
                    }
                }
            }

            is FooterViewHolder -> holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
        }
    }

    private fun showOptionPopupWindow(view: View, entity: GamesCollectionEntity) {
        val contentList = if (entity.display == "self_only") {
            arrayListOf("编辑", "投稿", "删除")
        } else {
            arrayListOf("编辑", "删除")
        }

        val inflater = LayoutInflater.from(mContext)
        val layout = inflater.inflate(com.gh.gamecenter.common.R.layout.layout_popup_container, null)
        val popupWindow = PopupWindow(
            layout,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        popupWindow.apply {
            setBackgroundDrawable(ColorDrawable(0))
            isTouchable = true
            isFocusable = true
            isOutsideTouchable = true
        }

        val container = layout.findViewById<LinearLayout>(R.id.container)
        for (text in contentList) {
            val item = inflater.inflate(R.layout.layout_popup_option_item, container, false)
            container.addView(item)

            val hitText = item.findViewById<TextView>(R.id.hint_text)
            hitText.text = text

            item.setOnClickListener {
                dealOption(text, entity)
                popupWindow.dismiss()
            }
        }
        popupWindow.showAutoOrientation(view)
    }

    private fun dealOption(content: String, entity: GamesCollectionEntity) {
        val path = when (mViewModel.type) {
            GamesCollectionFragment.TYPE_COLLECT -> "我的收藏"
            GamesCollectionFragment.TYPE_HISTORY -> "浏览记录"
            GamesCollectionFragment.TYPE_USER -> "个人主页"
            else -> ""
        }
        when (content) {
            "编辑" -> {
                mContext.startActivity(GameCollectionEditActivity.getIntent(mContext, entity, path = path))
            }

            "投稿" -> {
                SensorsBridge.trackEvent("GameCollectContributeClick", json {
                    "source_entrance" to path
                    "game_num" to entity.count?.game
                    "game_collect_title" to entity.title
                    "game_collect_id" to entity.id
                })
                if ((entity.count?.game ?: 0) >= 8) {
                    SensorsBridge.trackEvent("GameCollectContributeConfirmDialogShow", json {
                        "source_entrance" to path
                        "game_num" to entity.count?.game
                        "game_collect_title" to entity.title
                        "game_collect_id" to entity.id
                    })
                    DialogHelper.showDialog(
                        mContext,
                        "温馨提示",
                        "投稿通过后，将自动关闭“仅自己可见”，所有用户都能浏览到游戏单，确定投稿？",
                        "确定",
                        "取消",
                        {
                            SensorsBridge.trackEvent("GameCollectContributeConfirmDialogClick", json {
                                "source_entrance" to path
                                "button_name" to "确定"
                                "game_num" to entity.count?.game
                                "game_collect_title" to entity.title
                                "game_collect_id" to entity.id
                            })
                            mViewModel.publishGameCollection(entity)
                        },
                        {
                            SensorsBridge.trackEvent("GameCollectContributeConfirmDialogClick", json {
                                "source_entrance" to path
                                "button_name" to "取消"
                                "game_num" to entity.count?.game
                                "game_collect_title" to entity.title
                                "game_collect_id" to entity.id
                            })
                        },
                        {
                            SensorsBridge.trackEvent("GameCollectContributeConfirmDialogClick", json {
                                "source_entrance" to path
                                "button_name" to "关闭弹窗"
                                "game_num" to entity.count?.game
                                "game_collect_title" to entity.title
                                "game_collect_id" to entity.id
                            })
                        },
                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                } else {
                    SensorsBridge.trackEvent("GameCollectContributeGameLackDialogShow", json {
                        "source_entrance" to path
                        "game_num" to entity.count?.game
                        "game_collect_title" to entity.title
                        "game_collect_id" to entity.id
                    })
                    DialogHelper.showDialog(
                        mContext,
                        "温馨提示",
                        "游戏单需要收录至少8个游戏，才可以投稿至游戏单广场哦~",
                        "添加游戏",
                        "我知道了",
                        {
                            SensorsBridge.trackEvent("GameCollectContributeGameLackDialogClick", json {
                                "source_entrance" to path
                                "button_name" to "添加游戏"
                                "game_num" to entity.count?.game
                                "game_collect_title" to entity.title
                                "game_collect_id" to entity.id
                            })
                            mContext.startActivity(GameCollectionEditActivity.getIntent(mContext, entity, path = path))
                        },
                        {
                            SensorsBridge.trackEvent("GameCollectContributeGameLackDialogClick", json {
                                "source_entrance" to path
                                "button_name" to "我知道了"
                                "game_num" to entity.count?.game
                                "game_collect_title" to entity.title
                                "game_collect_id" to entity.id
                            })
                        },
                        {
                            SensorsBridge.trackEvent("GameCollectContributeGameLackDialogClick", json {
                                "source_entrance" to path
                                "button_name" to "关闭弹窗"
                                "game_num" to entity.count?.game
                                "game_collect_title" to entity.title
                                "game_collect_id" to entity.id
                            })
                        },
                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                }
            }

            "删除" -> {
                SensorsBridge.trackEvent("GameCollectDeleteClick", json {
                    "source_entrance" to path
                    "game_collect_title" to entity.title
                    "game_collect_id" to entity.id
                })
                SensorsBridge.trackEvent("GameCollectDeleteDialogShow", json {
                    "source_entrance" to path
                    "game_collect_title" to entity.title
                    "game_collect_id" to entity.id
                })
                DialogHelper.showDialog(mContext, "温馨提示", "游戏单删除后将无法恢复，是否确认删除", "确定", "取消", {
                    SensorsBridge.trackEvent("GameCollectDeleteDialogClick", json {
                        "source_entrance" to path
                        "button_name" to "确定"
                        "game_collect_title" to entity.title
                        "game_collect_id" to entity.id
                    })
                    mViewModel.deleteGameCollection(entity)
                }, {
                    SensorsBridge.trackEvent("GameCollectDeleteDialogClick", json {
                        "source_entrance" to path
                        "button_name" to "取消"
                        "game_collect_title" to entity.title
                        "game_collect_id" to entity.id
                    })
                }, {
                    SensorsBridge.trackEvent("GameCollectDeleteDialogClick", json {
                        "source_entrance" to path
                        "button_name" to "关闭弹窗"
                        "game_collect_title" to entity.title
                        "game_collect_id" to entity.id
                    })
                }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
            }
        }
    }

    private fun initTagsUI(tagContainer: FlexboxLayout, tags: ArrayList<TagInfoEntity>) {
        tagContainer.removeAllViews()
        tags.forEachIndexed { index, tag ->
            val tagBinding =
                ItemGameCollectionFlexTagBinding.inflate(LayoutInflater.from(mContext), null, false).apply {
                    root.setPadding(0, 6F.dip2px(), 0, 0)
                    divider.goneIf(index == tags.size - 1)
                    tagNameTv.text = tag.name
                }
            tagContainer.addView(tagBinding.root)
        }
    }

    override fun getSyncData(position: Int): Pair<String, Any>? {
        if (position >= mEntityList.size) return null
        val entity = mEntityList[position]
        return Pair(entity.id, entity)
    }

    private fun showOptionWindow() {
        mPopupBinding = PopupHistoryOptionBinding.inflate(LayoutInflater.from(mContext))
        mPopupBinding?.root?.isFocusable = true
        mPopupBinding?.root?.isFocusableInTouchMode = true

        mPopWindow = PopupWindow(mPopupBinding?.root, LinearLayout.LayoutParams.MATCH_PARENT, 56f.dip2px())
        mPopWindow?.showAtLocation((mContext as AppCompatActivity).window.decorView, Gravity.BOTTOM, 0, 0)

        mPopupBinding?.itemDelete?.setOnClickListener {
            DialogHelper.showDialog(mContext, "是否删除${selectItems.size}条记录？", "提示：删除记录将不可恢复", "删除", "取消", {
                mViewModel.removeHistories(selectItems)
                selectItems.clear()
                checkSelectItems()
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))

        }
        mPopupBinding?.checkAllCb?.setCompoundDrawablesWithIntrinsicBounds(
            DrawableView.getCheckSelectorDrawable(
                mContext
            ), null, null, null
        )
        mPopupBinding?.checkAllCb?.setOnClickListener {
            if (mPopupBinding?.checkAllCb?.isChecked == true) {
                selectItems.clear()
                selectItems.addAll(mEntityList.map { it.id }.toList())
            } else {
                selectItems.clear()
            }
            checkSelectItems()
            notifyItemRangeChanged(0, mEntityList.size)
        }
        checkSelectItems()
    }

    private fun checkSelectItems() {
        mPopupBinding?.run {
            selectNumTv.text = if (selectItems.isEmpty()) "" else "(${selectItems.size})"
            itemDelete.background =
                if (selectItems.isEmpty()) com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999.toDrawable(mContext) else com.gh.gamecenter.common.R.drawable.download_button_normal_style.toDrawable(
                    mContext
                )
            itemDelete.setTextColor(
                if (selectItems.isEmpty()) com.gh.gamecenter.common.R.color.text_instance.toColor(mContext) else com.gh.gamecenter.common.R.color.white.toColor(
                    mContext
                )
            )
            itemDelete.isEnabled = selectItems.isNotEmpty()
            checkAllCb.isChecked = selectItems.size == mEntityList.size
        }
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? = mExposureEventArray!!.get(pos)

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? = null
}