package com.gh.gamecenter.qa.comment

import android.content.Context
import android.text.SpannableStringBuilder
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.CommentHelper
import com.gh.common.util.CommentUtils
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.OnCommentCallBackListener
import com.gh.gamecenter.adapter.viewholder.AnswerCommentViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.copyTextAndToast
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.NewCommentItemBinding
import com.gh.gamecenter.feature.entity.CommentEntity
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity

class NewCommentAdapter(
    context: Context,
    var mViewModel: NewCommentViewModel,
    var mIsShowingConversation: Boolean,
    var mCommentCallBackListener: OnCommentCallBackListener,
    var mCommentOptionClickListener: OnCommentOptionClickListener? = null,
    var mEntrance: String
) : ListAdapter<CommentEntity>(context) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == ItemViewType.LOADING) {
            val view = mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false)
            FooterViewHolder(view)
        } else {
            val view = mLayoutInflater.inflate(R.layout.new_comment_item, parent, false)
            AnswerCommentViewHolder(NewCommentItemBinding.bind(view))
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is AnswerCommentViewHolder) {
            initCommentViewHolder(holder, position)
        } else if (holder is FooterViewHolder) {
            initFooterViewHolder(holder)
        }
    }

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

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

    private fun initCommentViewHolder(holder: AnswerCommentViewHolder, position: Int) {
        var isChildLongClick = false
        val commentEntity = mEntityList[position]
        CommentUtils.setCommentUserView(mContext, holder, commentEntity)
        CommentUtils.setCommentTime(holder.commentTimeTv, commentEntity.time)
        if (commentEntity.parentUser != null) {
            val prefix = "回复"
            val colon = " ："
            val parentUserName = " ${commentEntity.parentUser?.name} "

            val prefixSpan = SpanBuilder(prefix).color(
                holder.itemView.context,
                0,
                prefix.length,
                com.gh.gamecenter.common.R.color.text_tertiary
            ).build()
            val parentUserNameSpan = SpanBuilder(parentUserName)
                .click(mContext, 0, parentUserName.length, com.gh.gamecenter.common.R.color.text_secondary) {
                    DirectUtils.directToHomeActivity(
                        holder.itemView.context,
                        commentEntity.user.id,
                        1,
                        mEntrance,
                        ""
                    )
                }.build()
            val colonSpan = SpanBuilder(colon).color(
                holder.itemView.context,
                0,
                colon.length,
                com.gh.gamecenter.common.R.color.text_tertiary
            ).build()
            val authorSpan = if (commentEntity.parentUser?.me?.isCommentOwner == true) {
                SpanBuilder("作者").image(0, "作者".length, R.drawable.ic_hint_author).build()
            } else {
                ""
            }

            holder.commentContentTv.text = SpannableStringBuilder()
                .append(prefixSpan)
                .append(parentUserNameSpan)
                .append(authorSpan)
                .append(colonSpan)
                .append(commentEntity.content)
        } else {
            holder.commentContentTv.text = commentEntity.content
        }
        holder.commentContentTv.setOnLongClickListener(View.OnLongClickListener {
            isChildLongClick = true
            commentEntity.content?.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "")
                ?.copyTextAndToast()
            return@OnLongClickListener true
        })

        val key = when (mEntrance) {
            "(答案详情-评论列表)" -> "回答详情-评论管理"
            "(文章详情-评论列表)" -> "社区文章详情-评论管理"
            "(视频详情-评论列表)" -> "视频详情-评论管理"
            "(答案-评论详情-查看对话)" -> "回答详情-评论管理-查看对话"
            "(文章-评论详情-查看对话)" -> "社区文章详情-评论管理-查看对话"
            "(视频-评论详情-查看对话)" -> "视频详情-评论管理-查看对话"
            else -> ""
        }

        holder.userBadgeSdv.setOnClickListener { v ->
            DialogUtils.showViewBadgeDialog(mContext, commentEntity.user.badge, object : ConfirmListener {
                override fun onConfirm() {
                    MtaHelper.onEvent(
                        "进入徽章墙_用户记录",
                        key,
                        commentEntity.user.name + "（" + commentEntity.user.id + "）"
                    )
                    MtaHelper.onEvent("徽章中心", "进入徽章中心", key)
                    DirectUtils.directToBadgeWall(
                        mContext,
                        commentEntity.user.id,
                        commentEntity.user.name,
                        commentEntity.user.icon
                    )
                }
            })
        }
        holder.badgeNameTv.setOnClickListener { v -> holder.userBadgeSdv.performClick() }
        holder.quoteAuthorBadgeSdv.setOnClickListener { v ->
            DialogUtils.showViewBadgeDialog(mContext, commentEntity.parentUser!!.badge, object : ConfirmListener {
                override fun onConfirm() {
                    MtaHelper.onEvent(
                        "进入徽章墙_用户记录",
                        key,
                        commentEntity.parentUser!!.name + "（" + commentEntity.parentUser!!.id + "）"
                    )
                    MtaHelper.onEvent("徽章中心", "进入徽章中心", key)
                    DirectUtils.directToBadgeWall(
                        mContext,
                        commentEntity.parentUser!!.id,
                        commentEntity.parentUser!!.name,
                        commentEntity.parentUser!!.icon
                    )
                }
            })
        }

        holder.commentLikeContainer.setOnClickListener {
            CommentUtils.likeComment(
                mContext,
                mViewModel.answerId,
                mViewModel.articleId,
                mViewModel.communityId,
                mViewModel.videoId,
                mViewModel.questionId,
                commentEntity,
                holder.commentLikeCountTv,
                holder.commentLikeIv,
                null
            )
        }

        holder.itemView.setOnClickListener {
            if (isChildLongClick) {
                isChildLongClick = false
                return@setOnClickListener
            }
            if (holder.commentReply.visibility == View.VISIBLE) {
                mContext.ifLogin("回答详情-评论-回复") {
                    mCommentCallBackListener.onCommentCallback(commentEntity)
                }
            }
        }

        holder.commentMore.setOnClickListener {
            when (mViewModel.commentType) {
                CommentType.ANSWER,
                CommentType.ANSWER_CONVERSATION -> {
                    CommentHelper.showAnswerCommentOptions(
                        it,
                        commentEntity,
                        mIsShowingConversation,
                        mViewModel.answerId,
                        mCommentOptionClickListener
                    )
                }

                CommentType.COMMUNITY_ARTICLE,
                CommentType.COMMUNITY_ARTICLE_CONVERSATION -> {
                    CommentHelper.showCommunityArticleCommentOptions(
                        it,
                        commentEntity,
                        mIsShowingConversation,
                        mViewModel.articleId,
                        mViewModel.communityId,
                        isShowTop = false,
                        ignoreModerator = false,
                        listener = mCommentOptionClickListener
                    )
                }

                CommentType.VIDEO,
                CommentType.VIDEO_CONVERSATION -> {
                    CommentHelper.showVideoCommentOptions(
                        it,
                        commentEntity,
                        mIsShowingConversation,
                        mViewModel.videoId,
                        mViewModel.isVideoAuthor,
                        false,
                        mCommentOptionClickListener
                    )
                }
                else -> {
                    //do nothing
                }
            }
        }

        val path = when (mViewModel.commentType) {
            CommentType.ANSWER,
            CommentType.ANSWER_CONVERSATION -> "回答详情-评论管理"

            CommentType.COMMUNITY_ARTICLE,
            CommentType.COMMUNITY_ARTICLE_CONVERSATION -> "社区文章详情-评论管理"

            CommentType.VIDEO,
            CommentType.VIDEO_CONVERSATION -> "视频详情-评论管理"

            CommentType.COMMUNITY_QUESTION,
            CommentType.COMMUNITY_QUESTION_CONVERSATION -> "问题详情-评论管理"

            CommentType.GAME_COLLECTION,
            CommentType.GAME_COLLECTION_CONVERSATION -> "游戏单详情-评论管理"
        }

        val userHomePageTabPosition = if (mViewModel.commentType.isVideo()) 2 else 1

        holder.commentUserIconDv.setOnClickListener {
            DirectUtils.directToHomeActivity(
                mContext,
                commentEntity.user.id,
                userHomePageTabPosition,
                mEntrance,
                path
            )
        }
        holder.commentUserNameTv.setOnClickListener {
            DirectUtils.directToHomeActivity(
                mContext,
                commentEntity.user.id,
                userHomePageTabPosition,
                mEntrance,
                path
            )
        }

        if (commentEntity.priority != 0) {
            holder.commentBadge.visibility = View.VISIBLE
        } else {
            holder.commentBadge.visibility = View.GONE
        }
    }

    private fun initFooterViewHolder(holder: FooterViewHolder) {
        holder.hint.textSize = 12f
        holder.hint.setTextColor(
            ContextCompat.getColor(
                holder.itemView.context,
                com.gh.gamecenter.common.R.color.text_B3B3B3
            )
        )
        if (mIsNetworkError) {
            holder.loading.visibility = View.GONE
            holder.hint.setText(R.string.loading_error_network)
        } else if (!mIsOver) {
            holder.hint.setText(com.gh.gamecenter.common.R.string.loading)
            holder.loading.visibility = View.VISIBLE
        } else if (mEntityList.size == 0) {
            holder.loading.visibility = View.GONE
            holder.hint.setText(R.string.comment_empty)
        } else {
            holder.hint.setText(com.gh.gamecenter.common.R.string.load_over_hint)
            holder.loading.visibility = View.GONE
        }
    }

}