package com.gh.gamecenter.qa.comment.base

import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.*
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.syncpage.ISyncAdapterHandler
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.common.view.SegmentedFilterView
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.ItemArticleDetailCommentBinding
import com.gh.gamecenter.databinding.ItemArticleDetailCommentEmptyBinding
import com.gh.gamecenter.databinding.ItemArticleDetailCommentFooterBinding
import com.gh.gamecenter.databinding.PieceArticleDetailCommentFilterBinding
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.entity.Permissions
import com.gh.gamecenter.qa.article.detail.ArticleDetailAdapter
import com.gh.gamecenter.qa.article.detail.ArticleDetailViewModel
import com.gh.gamecenter.qa.article.detail.CommentItemData
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.comment.CommentPictureAdapter
import com.gh.gamecenter.qa.comment.OnCommentOptionClickListener
import com.gh.gamecenter.qa.comment.conversation.CommentConversationViewModel
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
import com.gh.gamecenter.qa.video.detail.comment.VideoCommentViewModel

abstract class BaseCommentAdapter(
    context: Context,
    private var mViewModel: BaseCommentViewModel,
    private var mType: AdapterType,
    private var mEntrance: String,
    var commentClosure: ((CommentEntity) -> Unit)? = null
) : ListAdapter<CommentItemData>(context), ISyncAdapterHandler {

    var filterVH: CommentFilterViewHolder? = null

    override fun loadChange(status: LoadStatus?) {
        if (status == LoadStatus.INIT) {
            mIsNetworkError = false
            mIsOver = false
            mIsLoading = true
            return
        } else {
            super.loadChange(status)
        }
    }

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

    override fun areContentsTheSame(oldItem: CommentItemData?, newItem: CommentItemData?): Boolean {
        if (oldItem?.footer != null) return false

        return oldItem?.commentTop?.vote == newItem?.commentTop?.vote
                && oldItem?.commentTop?.isTop == newItem?.commentTop?.isTop
                && oldItem?.commentTop?.accept == newItem?.commentTop?.accept
                && oldItem?.commentTop?.choiceness == newItem?.commentTop?.choiceness
                && oldItem?.commentTop?.me?.isVoted == newItem?.commentTop?.me?.isVoted
                && oldItem?.commentNormal?.vote == newItem?.commentNormal?.vote
                && oldItem?.commentNormal?.reply == newItem?.commentNormal?.reply
                && oldItem?.commentNormal?.me?.isCommentVoted == newItem?.commentNormal?.me?.isCommentVoted
                && oldItem?.commentNormal?.floor == newItem?.commentNormal?.floor
                && oldItem?.commentNormal?.isTop == newItem?.commentNormal?.isTop
                && oldItem?.commentNormal?.accept == newItem?.commentNormal?.accept
                && oldItem?.commentNormal?.choiceness == newItem?.commentNormal?.choiceness
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_FOOTER -> {
                val binding: ItemArticleDetailCommentFooterBinding = ItemArticleDetailCommentFooterBinding.inflate(
                    mLayoutInflater,
                    parent,
                    false
                )
                CommentFooterViewHolder(binding)
            }

            ITEM_COMMENT_NORMAL -> {
                val binding: ItemArticleDetailCommentBinding = ItemArticleDetailCommentBinding.inflate(
                    mLayoutInflater,
                    parent,
                    false
                )
                CommentItemViewHolder(binding, mType)
            }

            ITEM_FILTER -> {
                val binding: PieceArticleDetailCommentFilterBinding = parent.toBinding()
                CommentFilterViewHolder(binding).apply { filterVH = this }
            }

            ITEM_ERROR_EMPTY -> {
                CommentErrorViewHolder(
                    ItemArticleDetailCommentEmptyBinding.bind(
                        mLayoutInflater.inflate(
                            R.layout.item_article_detail_comment_empty,
                            parent,
                            false
                        )
                    )
                )
            }

            ITEM_ERROR_CONNECTION -> {
                CommentErrorViewHolder(
                    ItemArticleDetailCommentEmptyBinding.bind(
                        mLayoutInflater.inflate(
                            R.layout.item_article_detail_comment_empty,
                            parent,
                            false
                        )
                    )
                )
            }

            else -> throw IllegalAccessException()
        }
    }

    override fun getItemViewType(position: Int): Int {
        val item = mEntityList[position]
        return when {
            item.articleDetail != null -> ITEM_ARTICLE_DETAIL
            item.questionDetail != null -> ITEM_QUESTION_DETAIL
            item.filter != null -> ITEM_FILTER
            item.commentTop != null -> ITEM_COMMENT_TOP
            item.commentNormal != null -> ITEM_COMMENT_NORMAL
            item.errorConnection == true -> ITEM_ERROR_CONNECTION
            item.errorEmpty == true -> ITEM_ERROR_EMPTY
            else -> ItemViewType.ITEM_FOOTER
        }
    }

    override fun getItemCount(): Int {
        return if (mEntityList.isNotEmpty()) mEntityList.size else 0
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is CommentItemViewHolder -> {
                holder.bindComment(
                    mEntityList[position].commentNormal!!,
                    mViewModel,
                    mEntrance,
                    commentClosure
                ) { deleteCommentEntity ->
                    val findEntity =
                        mEntityList.find { it.commentNormal != null && it.commentNormal?.id == deleteCommentEntity.id }
                    val index = mEntityList.indexOf(findEntity)
                    mEntityList.remove(findEntity)
                    notifyItemRemoved(index)

                    //刷新 ITEM_FILTER
                    mViewModel.commentCount -= 1
                    notifyItemChanged(1)

                    val isArticleDetail = this is ArticleDetailAdapter

                    if (isArticleDetail) {
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                mViewModel.articleId,
                                SyncFieldConstants.ARTICLE_COMMENT_COUNT,
                                mViewModel.commentCount,
                                checkFieldEntity = true
                            )
                        )
                    } else {
                        mEntityList[0].commentTop?.reply = (mEntityList[0].commentTop?.reply
                            ?: 0) - 1
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                mEntityList[0].commentTop?.id
                                    ?: "",
                                SyncFieldConstants.ARTICLE_COMMENT_REPLY_COUNT,
                                mEntityList[0].commentTop?.reply,
                                checkFieldEntity = true
                            )
                        )
                        //刷新评论详情头部
                        notifyItemChanged(0)
                    }
                }
            }

            is CommentFooterViewHolder -> {
                holder.itemView.setBackgroundColor(R.color.background_white.toColor(mContext))
                holder.bindView(mIsLoading, mIsNetworkError, mIsOver)
            }

            is CommentErrorViewHolder -> {
                holder.binding.container.setBackgroundColor(R.color.background_white.toColor(mContext))
//                holder.binding.hintTv.setTextColor(R.color.text_body.toColor(mContext))
            }
        }
    }

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

    inner class CommentFooterViewHolder(var binding: ItemArticleDetailCommentFooterBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bindView(
            isLoading: Boolean,
            isNetworkError: Boolean,
            isOver: Boolean,
            @StringRes loadOverHint: Int = R.string.load_over_hint
        ) {
            when {
                isNetworkError -> {
                    binding.progressBar.visibility = View.GONE
                    binding.footerTv.setText(R.string.loading_failed_retry)
                }
                isOver -> {
                    binding.progressBar.visibility = View.GONE
                    binding.footerTv.setText(loadOverHint)
                }
                isLoading -> {
                    binding.progressBar.visibility = View.VISIBLE
                    binding.footerTv.setText(R.string.loading)
                }
                else -> {
                    binding.progressBar.visibility = View.GONE
                }
            }
            itemView.setOnClickListener { if (isNetworkError) mViewModel.load(LoadType.RETRY) }
        }
    }

    inner class CommentErrorViewHolder(val binding: ItemArticleDetailCommentEmptyBinding) :
        RecyclerView.ViewHolder(binding.root)

    inner class CommentFilterViewHolder(var binding: PieceArticleDetailCommentFilterBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bindView(
            article: ArticleDetailEntity? = null,
            questions: QuestionsDetailEntity? = null,
            comment: CommentEntity? = null,
            gameCollection: Boolean? = null,
            commentDetail: Boolean? = null
        ) {
            binding.run {
                filterView.setBackgroundColor(R.color.background_white.toColor(mContext))
                divider.setBackgroundColor(R.color.divider.toColor(mContext))
                commentHintTv.setTextColor(R.color.text_title.toColor(mContext))
                commentHintCountTv.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
                orderSfv.run {
                    setContainerBackground(R.drawable.button_round_f5f5f5.toDrawable(mContext))
                    setIndicatorBackground(R.drawable.bg_game_collection_sfv_indicator.toDrawable(mContext))
                    setTextColor(ContextCompat.getColorStateList(mContext, R.color.game_collection_rg_button_selector))
                }

                val commentCount = mViewModel.commentCount
                commentHintTv.text = when {
                    article != null -> {
                        "全部评论"
                    }
                    questions != null -> {
                        "全部回答"
                    }
                    comment != null -> {
                        "全部回复"
                    }
                    gameCollection != null -> {
                        "玩家评论"
                    }
                    commentDetail != null -> {
                        "全部讨论"
                    }
                    else -> {
                        ""
                    }
                }

                commentHintCountTv.text = if (gameCollection != null) {
                    commentCount.toNewSimpleCount()
                } else {
                    commentCount.toSimpleCount()
                }

                divider.goneIf(gameCollection == true || commentDetail == true)
                if (orderSfv.getItemList().isEmpty()) {
                    orderSfv.setItemList(listOf("正序", "倒序"), 0)
                }
                orderSfv.setOnCheckedCallback(object : SegmentedFilterView.OnCheckedCallback {
                    override fun onItemCheck(position: Int) {
                        when (position) {
                            0 -> {
                                mViewModel.changeSort(BaseCommentViewModel.SortType.OLDEST)

                                if (article == null) {
                                    MtaHelper.onEvent("帖子详情", "全部评论", "倒序")
                                } else {
                                    MtaHelper.onEvent("帖子详情", "评论详情-全部回复", "倒序")
                                }

                            }
                            1 -> {
                                mViewModel.changeSort(BaseCommentViewModel.SortType.LATEST)

                                if (article == null) {
                                    MtaHelper.onEvent("帖子详情", "全部评论", "正序")
                                } else {
                                    MtaHelper.onEvent("帖子详情", "评论详情-全部回复", "正序")
                                }
                            }
                        }
                    }
                })
            }
        }
    }

    class CommentItemViewHolder(
        var binding: ItemArticleDetailCommentBinding,
        var type: AdapterType
    ) : RecyclerView.ViewHolder(binding.root) {

        @SuppressLint("SetTextI18n")
        fun bindComment(
            comment: CommentEntity,
            viewModel: BaseCommentViewModel,
            entrance: String,
            commentClosure: ((CommentEntity) -> Unit)? = null,
            deleteCallBack: ((comment: CommentEntity) -> Unit)? = null
        ) {
            bindComment(binding, viewModel, comment, entrance, deleteCallBack)
            if (type == AdapterType.COMMENT) {
                // 帖子详情页面用的样式
                updateSubComment(comment, viewModel, entrance)
                binding.floorHintTv.text = if (comment.floor != 0) "${comment.floor}楼" else ""
                val (bbsId, contentType, bbsType) = getLogData(viewModel)
                binding.root.setOnClickListener {
                    when {
                        viewModel.articleId.isNotEmpty() -> {
                            CommentActivity.getArticleCommentIntent(
                                binding.root.context,
                                viewModel.articleId,
                                viewModel.commentCount,
                                true,
                                viewModel.communityId,
                                comment,
                                true
                            ).apply {
                                (binding.root.context as AppCompatActivity).startActivityForResult(
                                    this,
                                    CommentActivity.REQUEST_CODE
                                )
                            }
                            MtaHelper.onEvent("帖子详情", "全部评论", "评论正文")
                        }
                        viewModel.videoId.isNotEmpty() -> {
                            CommentActivity.getVideoCommentReplyIntent(
                                binding.root.context,
                                viewModel.videoId,
                                viewModel.commentCount,
                                comment.me?.isContentOwner == true,
                                true,
                                true,
                                comment
                            ).apply {
                                (binding.root.context as AppCompatActivity).startActivityForResult(
                                    this,
                                    CommentActivity.REQUEST_CODE
                                )
                            }
                        }
                        viewModel.questionId.isNotEmpty() -> {
                            CommentActivity.getQuestionCommentReplyIntent(
                                binding.root.context,
                                viewModel.questionId,
                                viewModel.communityId,
                                viewModel.commentCount,
                                true,
                                true,
                                comment
                            ).apply {
                                (binding.root.context as AppCompatActivity).startActivityForResult(
                                    this,
                                    CommentActivity.REQUEST_CODE
                                )
                            }
                        }
                    }
                    NewLogUtils.logCommentClick(
                        "click_comment_area_comment",
                        comment.user.id ?: "", contentType, comment.id ?: "", bbsId, bbsType
                    )
                }
                binding.commentCountTv.setOnClickListener {
                    CommentActivity.getCommentDetailIntent(
                        binding.root.context,
                        comment.id!!,
                        viewModel.communityId,
                        viewModel.articleId,
                        viewModel.videoId,
                        viewModel.questionId,
                        false,
                        comment.floor,
                        entrance,
                        PATH_ARTICLE_DETAIL
                    ).apply {
                        binding.root.context.startActivity(this)
                    }
                    MtaHelper.onEvent("帖子详情", "全部评论", "回复")
                    NewLogUtils.logCommentClick(
                        "click_comment_area_reply",
                        comment.user.id ?: "", contentType, comment.id ?: "", bbsId, bbsType
                    )
                }
                binding.contentTv.text = comment.content
                binding.commentCountTv.text = viewModel.getCommentText(comment.reply, "回复")
            } else {
                // 评论详情用的样式
                binding.floorHintTv.visibility = View.GONE
                binding.commentCountTv.setOnClickListener { commentClosure?.invoke(comment) }
                binding.commentCountTv.text = "回复"
                binding.likeCountTv.text = viewModel.getLikeText(comment.vote, "")
                binding.root.setOnClickListener { binding.commentCountTv.performClick() }

                if (comment.parentUser != null && !TextUtils.isEmpty(comment.parentUser!!.id)) {
                    val prefix = "回复"
                    val colon = " ："
                    val parentUserName = " @${comment.parentUser?.name} "

                    val prefixSpan = SpanBuilder(prefix).color(
                        binding.root.context,
                        0,
                        prefix.length,
                        R.color.text_title
                    ).build()
                    val parentUserNameSpan = SpanBuilder(parentUserName)
                        .click(binding.root.context, 0, parentUserName.length, R.color.text_subtitleDesc) {
                            DirectUtils.directToHomeActivity(
                                binding.root.context,
                                comment.user.id,
                                1,
                                entrance,
                                PATH_ARTICLE_DETAIL_COMMENT
                            )
                            MtaHelper.onEvent("帖子详情", "引用回复区域", "用户名字")
                        }.build()
                    val colonSpan = SpanBuilder(colon).color(
                        binding.root.context,
                        0,
                        colon.length,
                        R.color.text_title
                    ).build()
                    val authorSpan = if (comment.parentUser?.me?.isCommentOwner == true) {
                        SpanBuilder("作者").image(0, "作者".length, R.drawable.ic_hint_author).build()
                    } else {
                        ""
                    }

                    binding.contentTv.text = SpannableStringBuilder()
                        .append(prefixSpan)
                        .append(parentUserNameSpan)
                        .append(authorSpan)
                        .append(colonSpan)
                        .append(comment.content)
                } else {
                    binding.contentTv.text = comment.content
                }
            }
        }

        @SuppressLint("SetTextI18n")
        fun updateSubComment(
            comment: CommentEntity,
            viewModel: BaseCommentViewModel,
            entrance: String
        ) {
            val subCommentList = comment.subCommentList
            val ownerUserId = when {
                viewModel.articleId.isNotEmpty() -> {
                    viewModel.topItemData?.articleDetail?.user?.id ?: ""
                }
                viewModel.questionId.isNotEmpty() -> {
                    viewModel.topItemData?.questionDetail?.user?.id ?: ""
                }
                else -> {
                    ""
                }
            }
            binding.moreSubCommentBtn.goneIf(comment.reply < 3)
            binding.moreSubCommentBtn.text = "查看全部${comment.reply}条回复"
            binding.subCommentContainer.goneIf(subCommentList.isNullOrEmpty())
            binding.firstSubCommentTv.goneIf(subCommentList?.firstOrNull() == null)
            binding.secondSubCommentTv.goneIf(subCommentList?.secondOrNull() == null)
            binding.subCommentContainer.setRoundedColorBackground(R.color.background_space_2, 5F)

            subCommentList?.firstOrNull()?.let {
                binding.firstSubCommentTv.text = getSubCommentSpanned(
                    binding.root.context,
                    it.user.name,
                    if (it.user.id == ownerUserId) "作者" else "",
                    it.content
                )
            }
            subCommentList?.secondOrNull()?.let {
                binding.secondSubCommentTv.text = getSubCommentSpanned(
                    binding.root.context,
                    it.user.name,
                    if (it.user.id == ownerUserId) "作者" else "",
                    it.content
                )
            }
            binding.subCommentContainer.setOnClickListener {
                CommentActivity.getCommentDetailIntent(
                    binding.root.context,
                    comment.id!!,
                    viewModel.communityId,
                    viewModel.articleId,
                    viewModel.videoId,
                    viewModel.questionId,
                    false,
                    comment.floor,
                    entrance,
                    PATH_ARTICLE_DETAIL
                ).apply {
                    binding.root.context.startActivity(this)
                }
            }
        }

        private fun getSubCommentSpanned(
            context: Context,
            name: String?,
            author: String?,
            content: String?
        ): SpannableStringBuilder {
            val finalAuthor = author ?: ""
            val finalName = "$name "
            val colon = " ："

            val nameSpan = SpanBuilder(finalName).color(context, 0, finalName.length, R.color.text_subtitleDesc).build()
            val authorSpan = if (finalAuthor.isNotEmpty()) SpanBuilder(finalAuthor).image(
                0,
                finalAuthor.length,
                R.drawable.ic_hint_author
            ).build() else ""
            val colonSpan = SpanBuilder(colon).color(context, 0, colon.length, R.color.text_subtitleDesc).build()
            return SpannableStringBuilder().append(nameSpan).append(authorSpan).append(colonSpan)
                .append(content)
        }

        companion object {

            fun bindView(binding: ItemArticleDetailCommentBinding, comment: CommentEntity) {
                binding.userNameTv.text = comment.user.name
                binding.authorHintIv.goneIf(comment.me?.isContentOwner == false || comment.me?.isContentOwner == null)
                binding.badgeIv.goneIf(comment.user.badge == null)
                ImageUtils.display(binding.badgeIv, comment.user.badge?.icon)
                binding.badgeTv.text = comment.user.badge?.name
                binding.topLabelIv.goneIf(!comment.isTop)
                binding.timeTv.setPadding(if (comment.isTop) 4f.dip2px() else 0, 0, 0, 0)
                binding.timeTv.text = if (comment.source != null && comment.source.region.isNotEmpty()) {
                    "${CommentUtils.getCommentTime(comment.time)} · ${comment.source.region}"
                } else {
                    CommentUtils.getCommentTime(comment.time)
                }

                binding.contentTv.goneIf(comment.content.isNullOrEmpty())
            }

            fun bindComment(
                binding: ItemArticleDetailCommentBinding,
                viewModel: BaseCommentViewModel,
                comment: CommentEntity,
                entrance: String, deleteCallBack: ((comment: CommentEntity) -> Unit)? = null
            ) {
                val path = when {
                    viewModel.articleId.isNotEmpty() -> {
                        if (viewModel is CommentConversationViewModel) PATH_ARTICLE_DETAIL_COMMENT else PATH_ARTICLE_DETAIL
                    }
                    viewModel.questionId.isNotEmpty() -> {
                        if (viewModel is CommentConversationViewModel) PATH_QUESTION_DETAIL_COMMENT else PATH_QUESTION_DETAIL
                    }
                    viewModel.videoId.isNotEmpty() -> {
                        if (viewModel is CommentConversationViewModel) PATH_VIDEO_DETAIL_COMMENT else PATH_VIDEO_DETAIL
                    }
                    else -> ""
                }
                val mtaKey = if (viewModel is ArticleDetailViewModel) "全部评论" else "评论详情-全部回复"

                if (comment.isHighlight) {
                    comment.isHighlight = false
                    binding.highlightBg.run {
                        visibility = View.VISIBLE
                        postDelayed({
                            tryWithDefaultCatch {
                                visibility = View.GONE
                            }
                        }, 3000)
                    }
                }

                if (!comment.images.isNullOrEmpty()) {
                    if (binding.commentPictureRv.adapter == null) {
                        binding.commentPictureRv.apply {
                            layoutManager = GridLayoutManager(context, 3)
                            adapter = CommentPictureAdapter(context, comment.images!!, entrance)
                            if (itemDecorationCount == 0) {
                                addItemDecoration(GridSpacingItemColorDecoration(context, 2, R.color.background_white))
                            }
                        }
                    } else {
                        (binding.commentPictureRv.adapter as CommentPictureAdapter).checkResetData(comment.images!!)
                    }
                    binding.commentPictureRv.visibility = View.VISIBLE
                } else {
                    binding.commentPictureRv.visibility = View.GONE
                }

                bindView(binding, comment)

                if (comment.isForceExpand) {
                    comment.isForceExpand = false
                    binding.contentTv.setExpandMaxLines(Int.MAX_VALUE)
                    binding.contentTv.setIsExpanded(true)
                    binding.contentTv.post {
                        binding.collapseTv.goneIf(binding.contentTv.lineCount <= 4)
                    }
                } else {
                    binding.contentTv.setExpandMaxLines(if (comment.isExpand) Int.MAX_VALUE else 4)
                    binding.contentTv.setIsExpanded(comment.isExpand)
                    binding.collapseTv.goneIf(!comment.isExpand)
                }
                binding.contentTv.setExpandCallback {
                    comment.isExpand = true
                    binding.collapseTv.visibility = View.VISIBLE
                    bindView(binding, comment)
                }
                binding.collapseTv.setOnClickListener {
                    comment.isExpand = false
                    binding.collapseTv.visibility = View.GONE
                    binding.contentTv.setExpandMaxLines(4)
                    binding.contentTv.setIsExpanded(false)
                    bindView(binding, comment)
                }
                binding.userIconIv.display(
                    comment.user.border,
                    comment.user.icon,
                    comment.user.auth?.icon
                )
                binding.adoptionIv.goneIf(!comment.accept)
                val (bbsId, contentType, bbsType) = getLogData(viewModel)
                binding.userIconIv.setOnClickListener {
                    MtaHelper.onEvent("帖子详情", mtaKey, "用户头像")
                    DirectUtils.directToHomeActivity(
                        binding.root.context,
                        comment.user.id,
                        1,
                        entrance,
                        path
                    )
                    NewLogUtils.logCommentClick(
                        "click_comment_area_profile_photo",
                        comment.user.id ?: "", contentType, comment.id ?: "", bbsId, bbsType
                    )
                }
                binding.userNameTv.setOnClickListener {
                    DirectUtils.directToHomeActivity(
                        binding.root.context,
                        comment.user.id,
                        1,
                        entrance,
                        path
                    )
                    MtaHelper.onEvent("帖子详情", mtaKey, "用户名字")
                    NewLogUtils.logCommentClick(
                        "click_comment_area_nickname",
                        comment.user.id ?: "", contentType, comment.id ?: "", bbsId, bbsType
                    )
                }

                binding.likeCountTv.text =
                    viewModel.getLikeText(comment.vote, if (viewModel is CommentConversationViewModel) "" else "赞同")

                if (comment.me?.isCommentVoted == true) {
                    binding.likeCountTv.setTextColor(R.color.theme_font.toColor(binding.likeCountTv.context))
                    binding.likeCountTv.setDrawableStart(R.drawable.comment_vote_select)
                } else {
                    binding.likeCountTv.setTextColor(R.color.text_subtitleDesc.toColor(binding.likeCountTv.context))
                    binding.likeCountTv.setDrawableStart(R.drawable.comment_vote_unselect)
                }

                binding.likeCountTv.setDebouncedClickListener {
                    binding.likeCountTv.context.ifLogin("帖子评论-点赞") {
                        if (comment.me?.isCommentVoted != true) {
                            viewModel.like(comment)

                            if (viewModel is ArticleDetailViewModel) {
                                MtaHelper.onEvent("帖子详情", "全部评论", "点赞")
                            } else {
                                MtaHelper.onEvent("帖子详情", "评论详情-全部回复", "点赞")
                            }
                            NewLogUtils.logCommentClick(
                                "click_comment_area_like",
                                comment.user.id ?: "", contentType, comment.id
                                    ?: "", bbsId, bbsType
                            )
                        } else {
                            binding.likeCountTv.context.ifLogin("帖子评论-取消点赞") {
                                viewModel.unLike(comment)
                            }
                        }
                    }
                }

                binding.badgeTv.setOnClickListener {
                    DialogUtils.showViewBadgeDialog(binding.root.context, comment.user.badge, object : ConfirmListener {
                        override fun onConfirm() {
                            MtaHelper.onEvent(
                                "进入徽章墙_用户记录",
                                "帖子详情-评论管理",
                                comment.user.name + "（" + comment.user.id + "）"
                            )
                            MtaHelper.onEvent("徽章中心", "进入徽章中心", "帖子详情-评论管理")
                            DirectUtils.directToBadgeWall(
                                binding.root.context,
                                comment.user.id,
                                comment.user.name,
                                comment.user.icon
                            )
                        }
                    })
                }
                binding.badgeIv.setOnClickListener { binding.badgeTv.performClick() }

                binding.moreIv.setOnClickListener {
                    showCommentOptions(viewModel, it, comment, path, deleteCallBack)
                    NewLogUtils.logCommentClick("click_comment_area_more")
                }
            }

            fun showCommentOptions(
                viewModel: BaseCommentViewModel,
                view: View,
                comment: CommentEntity,
                path: String,
                deleteCallBack: ((comment: CommentEntity) -> Unit)?
            ) {
                when {
                    viewModel.articleId.isNotEmpty() -> {
                        showCommunityArticleCommentOptions(
                            view,
                            comment,
                            viewModel,
                            path,
                            deleteCallBack
                        )
                    }
                    viewModel.videoId.isNotEmpty() -> {
                        showVideoCommentOptions(
                            view,
                            comment,
                            viewModel,
                            path,
                            deleteCallBack
                        )
                    }
                    viewModel.questionId.isNotEmpty() -> {
                        showQuestionCommentOption(
                            view,
                            comment,
                            viewModel,
                            path,
                            deleteCallBack
                        )
                    }
                }
            }

            private fun getLogData(viewModel: BaseCommentViewModel): Triple<String, String, String> {
                val bbsId: String
                val type: String
                when {
                    viewModel.articleId.isNotEmpty() -> {
                        bbsId = viewModel.topItemData?.articleDetail?.community?.id ?: ""
                        type = viewModel.topItemData?.articleDetail?.type ?: ""
                    }
                    viewModel.questionId.isNotEmpty() -> {
                        bbsId = viewModel.topItemData?.questionDetail?.community?.id ?: ""
                        type = viewModel.topItemData?.questionDetail?.type ?: ""
                    }
                    else -> {
                        bbsId = (viewModel as? VideoCommentViewModel)?.videoDetail?.bbs?.id ?: ""
                        type = (viewModel as? VideoCommentViewModel)?.videoDetail?.type ?: ""
                    }
                }
                val contentType =
                    if (viewModel.articleId.isNotEmpty()) "帖子评论" else if (viewModel.questionId.isNotEmpty()) "提问帖评论" else "视频帖评论"
                val bbsType = if (type == "game_bbs") "游戏论坛" else "综合论坛"
                return Triple(bbsId, contentType, bbsType)
            }

            private fun showQuestionCommentOption(
                view: View,
                comment: CommentEntity,
                viewModel: BaseCommentViewModel,
                path: String,
                deleteCallBack: ((comment: CommentEntity) -> Unit)?
            ) {
                CommentHelper.showQuestionCommentOption(
                    view,
                    comment,
                    viewModel.questionId,
                    path == PATH_QUESTION_DETAIL,
                    object : OnCommentOptionClickListener {
                        override fun onCommentOptionClick(entity: CommentEntity, option: String) {
                            when (option) {
                                "删除评论" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "删除评论后，评论下所有的回复都将被删除",
                                        "删除",
                                        "取消",
                                        {
                                            viewModel.deleteComment(comment) {
                                                deleteCallBack?.invoke(comment)
                                            }
                                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                                "采纳" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "确定采纳该评论？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            viewModel.acceptQuestionComment(viewModel.questionId, comment, true)
                                        },
                                        extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                                    )
                                }
                                "取消采纳" -> {
                                    viewModel.acceptQuestionComment(
                                        viewModel.questionId,
                                        comment,
                                        false
                                    )
                                }
                                "加精选" -> {
                                    showHighlightQuestionCommentDialog(comment, view.context, viewModel, true)
                                }
                                "取消精选" -> {
                                    showHighlightQuestionCommentDialog(comment, view.context, viewModel, false)
                                }
                                "置顶" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "是否将此条评论置顶？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            commentTop(view.context, viewModel, comment, false)
                                        },
                                        extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                                    )
                                }
                                "取消置顶" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "是否将此条评论取消置顶？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            viewModel.updateCommentTop(
                                                comment.id ?: "",
                                                top = false,
                                                isAgain = false
                                            ) { isSuccess, _ ->
                                                if (isSuccess) {
                                                    viewModel.onUpdateCommentTopSuccess()
                                                }
                                            }
                                        },
                                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                            }
                        }
                    })
            }

            private fun showHighlightQuestionCommentDialog(
                comment: CommentEntity,
                context: Context,
                viewModel: BaseCommentViewModel,
                isHighlight: Boolean
            ) {
                var highlightDialogHintContent = ""
                val permissions = comment.me?.moderatorPermissions ?: Permissions()
                if ((isHighlight && permissions.highlightAnswer > Permissions.GUEST) ||
                    (!isHighlight && permissions.cancelChoicenessAnswer > Permissions.GUEST)
                ) {
                    highlightDialogHintContent =
                        if ((isHighlight && permissions.highlightAnswer == Permissions.REPORTER) ||
                            (!isHighlight && permissions.cancelChoicenessAnswer == Permissions.REPORTER)
                        ) {
                            "你的操作将提交给小编审核，确定提交吗？"
                        } else {
                            "你的操作将立即生效，确定提交吗？"
                        }
                }
                val title = if (isHighlight) "加精提问评论" else "取消精选提问评论"
                DialogHelper.showDialog(
                    context,
                    title,
                    highlightDialogHintContent,
                    "确定",
                    "取消",
                    {
                        if (isHighlight) {
                            viewModel.highlightQuestionComment(comment)
                        } else {
                            viewModel.chancelHighlightQuestionComment(comment)
                        }
                    }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                )
            }

            private fun showVideoCommentOptions(
                view: View,
                comment: CommentEntity,
                viewModel: BaseCommentViewModel,
                path: String,
                deleteCallBack: ((comment: CommentEntity) -> Unit)?
            ) {
                CommentHelper.showVideoCommentOptions(view,
                    comment,
                    false,
                    viewModel.videoId,
                    comment.me?.isContentOwner == true,
                    path == PATH_VIDEO_DETAIL,
                    object : OnCommentOptionClickListener {
                        override fun onCommentOptionClick(entity: CommentEntity, option: String) {
                            when (option) {
                                "删除评论" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "删除评论后，评论下所有的回复都将被删除",
                                        "删除",
                                        "取消",
                                        {
                                            viewModel.deleteComment(comment) {
                                                deleteCallBack?.invoke(comment)
                                            }
                                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                                "置顶" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "是否将此条评论置顶？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            commentTop(view.context, viewModel, comment, false)
                                        },
                                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                                "取消置顶" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "是否将此条评论取消置顶？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            viewModel.updateCommentTop(
                                                comment.id ?: "",
                                                top = false,
                                                isAgain = false
                                            ) { isSuccess, _ ->
                                                if (isSuccess) {
                                                    viewModel.onUpdateCommentTopSuccess()
                                                }
                                            }
                                        },
                                        extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                                    )
                                }
                            }
                        }
                    })
            }

            private fun showCommunityArticleCommentOptions(
                view: View,
                comment: CommentEntity,
                viewModel: BaseCommentViewModel,
                path: String,
                deleteCallBack: ((comment: CommentEntity) -> Unit)?
            ) {
                CommentHelper.showCommunityArticleCommentOptions(
                    view,
                    comment,
                    false,
                    viewModel.articleId,
                    viewModel.communityId,
                    isShowTop = path == PATH_ARTICLE_DETAIL,
                    ignoreModerator = true,
                    listener = object : OnCommentOptionClickListener {
                        override fun onCommentOptionClick(entity: CommentEntity, option: String) {
                            when (option) {
                                "删除评论" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "删除评论后，评论下所有的回复都将被删除",
                                        "删除",
                                        "取消",
                                        {
                                            viewModel.deleteComment(comment) {
                                                deleteCallBack?.invoke(comment)
                                            }
                                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                                "置顶" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "是否将此条评论置顶？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            commentTop(view.context, viewModel, comment, false)
                                        },
                                        extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                                    )
                                }
                                "取消置顶" -> {
                                    DialogHelper.showDialog(
                                        view.context,
                                        "提示",
                                        "是否将此条评论取消置顶？",
                                        "确认",
                                        "取消",
                                        confirmClickCallback = {
                                            viewModel.updateCommentTop(
                                                comment.id ?: "",
                                                top = false,
                                                isAgain = false
                                            ) { isSuccess, _ ->
                                                if (isSuccess) {
                                                    viewModel.onUpdateCommentTopSuccess()
                                                }
                                            }
                                        },
                                        extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                                    )
                                }
                            }

                        }

                    })

                if (viewModel is ArticleDetailViewModel) {
                    MtaHelper.onEvent("帖子详情", "全部评论", "更多")
                } else {
                    MtaHelper.onEvent("帖子详情", "评论详情", "更多")
                }
            }

            private fun commentTop(
                context: Context,
                viewModel: BaseCommentViewModel,
                comment: CommentEntity,
                isAgain: Boolean
            ) {
                viewModel.updateCommentTop(comment.id ?: "", top = true, isAgain = isAgain) { isSuccess, errorCode ->
                    if (isSuccess) {
                        viewModel.onUpdateCommentTopSuccess()
                    } else {
                        if (errorCode == 403095) {
                            DialogHelper.showDialog(
                                context,
                                "提示",
                                "当前已有置顶评论，\n是否将此条评论覆盖展示？",
                                "确认",
                                "取消",
                                confirmClickCallback = {
                                    commentTop(context, viewModel, comment, true)
                                },
                                extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                            )
                        }
                    }
                }
            }
        }
    }

    companion object {
        const val ITEM_ARTICLE_DETAIL = 801
        const val ITEM_QUESTION_DETAIL = 802
        const val ITEM_FILTER = 803
        const val ITEM_COMMENT_TOP = 804
        const val ITEM_COMMENT_NORMAL = 805
        const val ITEM_ERROR_EMPTY = 806
        const val ITEM_ERROR_CONNECTION = 807

        const val PATH_ARTICLE_DETAIL = "帖子详情"
        const val PATH_ARTICLE_DETAIL_COMMENT = "帖子评论详情"

        const val PATH_QUESTION_DETAIL = "问题详情"
        const val PATH_QUESTION_DETAIL_COMMENT = "问题评论详情"

        const val PATH_VIDEO_DETAIL = "视频详情"
        const val PATH_VIDEO_DETAIL_COMMENT = "视频评论详情"
    }

    enum class AdapterType {
        COMMENT,

        SUB_COMMENT
    }

}