package com.gh.gamecenter.amway

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.gh.common.exposure.ExposureEvent
import com.gh.common.exposure.ExposureSource
import com.gh.common.exposure.IExposable
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.NumberUtils
import com.gh.gamecenter.databinding.AmwayCommentItemBinding
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.game.GameAndPosition
import com.gh.gamecenter.game.GameItemViewHolder
import com.gh.gamecenter.game.vertical.GameVerticalAdapter
import com.gh.gamecenter.gamedetail.rating.RatingFragment
import com.gh.gamecenter.gamedetail.rating.RatingReplyActivity
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity
import com.gh.gamecenter.home.LegacyHomeFragmentAdapterAssistant
import com.halo.assistant.fragment.game.GamePluginAdapter
import com.lightgame.download.DownloadEntity
import com.lightgame.view.CheckableImageView
import java.util.regex.Pattern

class AmwayAdapter(
    context: Context,
    private var mViewModel: AmwayViewModel,
    private var mBasicExposureSource: List<ExposureSource>,
    private var mLayoutManager: RecyclerView.LayoutManager
) : ListAdapter<AmwayListItemData>(context), IExposable {

    private val mLegacyHomeFragmentAdapterAssistant by lazy {
        LegacyHomeFragmentAdapterAssistant(
            mContext,
            this,
            mBasicExposureSource,
            true,
            LegacyHomeFragmentAdapterAssistant.OuterType.AMWAY
        )
    }

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

            ItemViewType.ITEM_FOOTER -> FooterViewHolder(
                mLayoutInflater.inflate(
                    R.layout.refresh_footerview,
                    parent,
                    false
                )
            )

            else -> mLegacyHomeFragmentAdapterAssistant.createLegacyViewHolder(parent, viewType)
        }
    }

    override fun setListData(updateData: MutableList<AmwayListItemData>?) {
        if (updateData == null) {
            super.setListData(updateData)
        } else {
            val brandNewList = mutableListOf<AmwayListItemData>()
            for (item in updateData) {
                brandNewList.add(item.copy())
            }
            super.setListData(updateData)
        }
    }

    override fun areItemsTheSame(oldItem: AmwayListItemData?, newItem: AmwayListItemData?) = oldItem == newItem

    override fun areContentsTheSame(oldItem: AmwayListItemData?, newItem: AmwayListItemData?): Boolean {
        return (oldItem?.amwayCommentItem?.comment?.me?.isVoted != newItem?.amwayCommentItem?.comment?.me?.isVoted)
    }

    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 AmwayCommentViewHolder -> {
                mEntityList[position].amwayCommentItem?.let {
                    holder.bindComment(
                        mViewModel,
                        mEntityList[position],
                        mEntityList[position].blockPosition,
                        mBasicExposureSource
                    )
                }
            }

            is FooterViewHolder -> {
                holder.initItemPadding()
                holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
                holder.hint.setTextColor(ContextCompat.getColor(mContext, R.color.text_B3B3B3))
                val lp = holder.itemView.layoutParams as RecyclerView.LayoutParams
                lp.height = DisplayUtils.dip2px(48F)
                lp.width = ViewGroup.LayoutParams.MATCH_PARENT
                holder.itemView.layoutParams = lp
            }

            else -> mLegacyHomeFragmentAdapterAssistant.bindLegacyViewHolder(holder, mEntityList[position], position)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) {
            ItemViewType.ITEM_FOOTER
        } else {
            val item = mEntityList[position]
            when {
                item.amwayCommentItem != null -> ITEM_AMWAY_COMMENT

                else -> mLegacyHomeFragmentAdapterAssistant.getLegacyItemType(item)
            }
        }
    }

    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]!!
                if (position >= mEntityList.size) return arrayListOf()
                val itemData = mEntityList[position]

                mLegacyHomeFragmentAdapterAssistant.getLegacyGameEntityByPackage(
                    positionList,
                    itemData,
                    packageName,
                    position
                )
            }
        }
        return positionList
    }

    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)
            }
            notifyChildItem(gameAndPosition.position)
        }
    }

    fun notifyChildItem(position: Int) {
        if (getItemViewType(position) == ItemViewType.VERTICAL_SLIDE_ITEM
            || getItemViewType(position) == ItemViewType.GAME_PLUGIN
        ) {
            val view = mLayoutManager.findViewByPosition(position)
            val recyclerView = view?.findViewById<RecyclerView>(R.id.recycler_view)
            recyclerView?.adapter?.notifyDataSetChanged()
        } else {
            notifyItemChanged(position)
        }
    }

    fun notifyItemByDownload(download: DownloadEntity) {
        val data = getGameEntityByPackage(download.packageName)
        for (gameAndPosition in data) {
            if (gameAndPosition.entity != null && gameAndPosition.entity.name == download.name) {
                val entryMap = gameAndPosition.entity.getEntryMap()
                entryMap[download.platform] = download
            }
            if (getItemViewType(gameAndPosition.position) == ItemViewType.VERTICAL_SLIDE_ITEM ||
                getItemViewType(gameAndPosition.position) == ItemViewType.GAME_PLUGIN
            ) {
                val view = mLayoutManager.findViewByPosition(gameAndPosition.position)
                val recyclerView = view?.findViewById<RecyclerView>(R.id.recycler_view)
                when (val adapter = recyclerView?.adapter) {
                    is GameVerticalAdapter -> adapter.notifyItemByDownload(download)
                    is GamePluginAdapter -> adapter.notifyItemByDownload(download)
                }
            } else {
                notifyItemChanged(gameAndPosition.position)
            }
        }
    }

    class AmwayCommentViewHolder(var binding: AmwayCommentItemBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bindComment(
            viewModel: AmwayViewModel,
            itemData: AmwayListItemData,
            blockPosition: Int,
            basicExposureSource: List<ExposureSource>
        ) {
            val context = binding.root.context
            val amway = itemData.amwayCommentItem!!
            val gameEntity = amway.game.toGameEntity()

            binding.gameContainer.background = R.drawable.selector_f8f8f8.toDrawable(context)
            binding.commentContainer.background = R.drawable.selector_f8f8f8.toDrawable(context)
            binding.gameNameTv.setTextColor(R.color.title.toColor(context))
            binding.ratingTv.setTextColor(R.color.theme_font.toColor(context))
            binding.tagTv.setTextColor(R.color.text_subtitleDesc.toColor(context))
            binding.amwayContentTv.setTextColor(R.color.text_3a3a3a.toColor(context))
            binding.userNameTv.setTextColor(R.color.title.toColor(context))
            binding.likeCountTv.setTextColor(R.color.text_B3B3B3.toColor(context))

            binding.gameNameTv.text = amway.game.name
            binding.ratingTv.text = amway.game.star.toString()
            binding.userNameTv.text = amway.comment.user.name
            binding.ratingBar.rating = amway.comment.star.toFloat()
            binding.likeCountTv.text =
                if (amway.comment.vote > 0) NumberUtils.transSimpleCount(amway.comment.vote) else "0"

            val user = itemData.amwayCommentItem?.comment?.user
            binding.userIcon.display(user?.border, user?.icon, user?.auth?.icon)
            val m = Pattern.compile(RatingEditActivity.LABEL_REGEX).matcher(amway.comment.content)
            if (m.find()) {
                val contents =
                    TextHelper.getCommentLabelSpannableStringBuilder(amway.comment.content, R.color.theme_font)
                binding.amwayContentTv.setTextWithHighlightedTextWrappedInsideWrapper(contents, copyClickedText = true)
            } else {
                binding.amwayContentTv.setTextWithHighlightedTextWrappedInsideWrapper(
                    amway.comment.content,
                    copyClickedText = true
                )
            }

            itemData.exposureEvent = ExposureEvent.createEvent(gameEntity, basicExposureSource)
            GameItemViewHolder.initGameSubtitle(gameEntity, binding.gameSubtitleTv)

            binding.gameContainer.setOnClickListener {
                GameDetailActivity.startGameDetailActivity(
                    binding.root.context,
                    amway.game.id,
                    "${viewModel.entrance}+(安利墙)",
                    itemData.exposureEvent
                )
                MtaHelper.onEvent("安利墙", "点击", "评论${blockPosition}_${amway.game.name}_游戏")
                NewLogUtils.logShareWallSquareCardClick(amway.game.name ?: "", amway.game.id, "游戏信息")
            }

            binding.gameIconView.displayGameIcon(
                amway.game.rawIcon
                    ?: amway.game.icon, amway.game.iconSubscript
            )

            amway.game.tag?.let {
                val tags = it.take(3)
                val tagString = StringBuilder()
                for (i in tags.indices) {
                    tagString.append(tags[i].name)
                    if (i != tags.size - 1) tagString.append("/")
                }
                binding.tagTv.text = tagString
            }

            binding.commentContainer.setOnClickListener {
                val intent = RatingReplyActivity.getIntent(
                    context, amway.game.id, amway.comment, false, viewModel.entrance
                        ?: "", EntranceConsts.ENTRANCE_AMWAY
                )
                SyncDataBetweenPageHelper.startActivityForResult(
                    binding.root.context,
                    intent,
                    RatingFragment.RATING_REPLAY_REQUEST,
                    adapterPosition
                )
                MtaHelper.onEvent("安利墙", "点击", "评论${blockPosition}_${amway.game.name}_评论")
                NewLogUtils.logShareWallSquareCardClick(amway.game.name ?: "", amway.game.id, "评论内容")
            }

            binding.userClickableView.setOnClickListener {
                DirectUtils.directToHomeActivity(
                    context,
                    amway.comment.user.id,
                    viewModel.entrance,
                    EntranceConsts.ENTRANCE_AMWAY
                )
                NewLogUtils.logShareWallSquareCardClick(amway.game.name ?: "", amway.game.id, "用户信息")
            }

            if (amway.comment.me.isVoted) {
                binding.likeIv.isChecked = true
                binding.likeCountTv.setTextColor(R.color.theme_font.toColor(binding.likeCountTv.context))
                binding.likeClickableView.setOnClickListener {
                    debounceActionWithInterval(binding.likeClickableView.id, 1000L) {
                        binding.likeIv.context.ifLogin("安利墙-取消点赞") {
                            viewModel.undoLikeAmwayComment(amway.game.id, amway.comment.id)
                            MtaHelper.onEvent("安利墙", "点击", "评论${blockPosition}_${amway.game.name}_取消点赞")
                        }
                    }
                }
            } else {
                binding.likeIv.isChecked = false
                binding.likeCountTv.setTextColor(R.color.text_B3B3B3.toColor(binding.likeCountTv.context))
                binding.likeClickableView.setOnClickListener {
                    debounceActionWithInterval(binding.likeClickableView.id, 1000L) {
                        binding.likeIv.context.ifLogin("安利墙-点赞") {
                            playLikedAnimation(binding.likeCountTv, binding.likeIv, binding.likeAnimView)
                            viewModel.likeAmwayComment(amway.game.id, amway.comment.id)
                            MtaHelper.onEvent("安利墙", "点击", "评论${blockPosition}_${amway.game.name}_点赞")
                        }
                    }
                }
            }

            ImageUtils.display(binding.sdvUserBadge, amway.comment.user.badge?.icon)
            binding.sdvUserBadge.goneIf(amway.comment.user.badge == null)
            binding.sdvUserBadge.setOnClickListener {
                DialogUtils.showViewBadgeDialog(context, amway.comment.user.badge, object : ConfirmListener {
                    override fun onConfirm() {
                        MtaHelper.onEvent("进入徽章墙_用户记录", "安利墙", "${amway.comment.user.name}（${amway.comment.user.id}）")
                        MtaHelper.onEvent("徽章中心", "进入徽章中心", "安利墙")
                        DirectUtils.directToBadgeWall(
                            context,
                            amway.comment.user.id,
                            amway.comment.user.name,
                            amway.comment.user.icon
                        )
                    }
                })
            }
        }

        private fun playLikedAnimation(
            likeTv: TextView,
            likeIv: CheckableImageView,
            likeAnimView: LottieAnimationView
        ) {
            likeTv.setTextColor(R.color.theme_font.toColor(likeTv.context))
            likeIv.isChecked = true
            likeIv.visibility = View.INVISIBLE
            likeAnimView.visibility = View.VISIBLE
            likeAnimView.setAnimation("lottie/community_vote.json")
            likeAnimView.playAnimation()
            likeAnimView.doOnAnimationEnd {
                likeAnimView.visibility = View.INVISIBLE
                likeIv.visibility = View.VISIBLE
            }
        }
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return mEntityList[pos].exposureEvent
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return mEntityList[pos].exposureEventList
    }

    companion object {
        const val ITEM_AMWAY_COMMENT = 222
    }

}