package com.gh.gamecenter.qa.comment

import android.content.Context
import android.text.Spanned
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
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.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.FastClickUtils
import com.gh.gamecenter.common.utils.ImageUtils.display
import com.gh.gamecenter.common.utils.TextHelper
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.core.utils.CenterImageSpan
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.NumberUtils.transSimpleCount
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.StairsCommentItemBinding
import com.gh.gamecenter.entity.CommentEntity
import com.gh.gamecenter.login.user.UserManager
import com.halo.assistant.HaloApp

class StairsCommentViewHolder(
    val binding: StairsCommentItemBinding,
    val isReplyComment: Boolean = false
) : BaseRecyclerViewHolder<CommentEntity>(binding.root) {

    var isFirstClick = true

    fun setCommentUserView(mContext: Context?, entity: CommentEntity) {
        val userDataEntity = entity.me
        binding.commentLikeCount.setTextColor(ContextCompat.getColor(mContext!!, R.color.hint))
        binding.commentLike.setImageResource(R.drawable.comment_vote_unselect)
        if (entity.vote == 0) {
            binding.commentLikeCount.visibility = View.GONE
        } else { // 检查是否已点赞
            if (userDataEntity != null && userDataEntity.isCommentVoted) {
                binding.commentLikeCount.setTextColor(
                    ContextCompat.getColor(
                        mContext,
                        R.color.theme_font
                    )
                )
                binding.commentLike.setImageResource(R.drawable.comment_vote_select)
            }
            binding.commentLikeCount.visibility = View.VISIBLE
            binding.commentLikeCount.text = transSimpleCount(entity.vote)
        }
        if (entity.user.badge != null) {
            binding.sdvUserBadge.visibility = View.VISIBLE
            display(binding.sdvUserBadge, entity.user.badge!!.icon)
        } else {
            binding.sdvUserBadge.visibility = View.GONE
        }

        //检查是否是自身评论
        val userInfo = UserManager.getInstance().userInfoEntity
        val parentUser = entity.parent?.user
        if (userDataEntity != null && userDataEntity.isCommentOwner && userInfo != null) {
            if (entity.me != null && entity.me!!.isContentOwner && entity.parent == null) {
                binding.commentAuthor.visibility = View.VISIBLE
            } else {
                binding.commentAuthor.visibility = View.GONE
            }
            if (parentUser != null && !TextUtils.isEmpty(parentUser.name)) {
                val name = "${entity.user.name} 回复 ${parentUser.name}"
                binding.commentUserName.text = SpanBuilder(name).color(
                    binding.root.context,
                    (entity.user.name?.length ?: 0) + 1,
                    (entity.user.name?.length ?: 0) + 3,
                    R.color.text_subtitle
                ).build()
            } else {
                binding.commentUserName.text = userInfo.name
            }
            binding.commentUserIcon.display(
                userInfo.iconBorder?.url,
                userInfo.icon,
                userInfo.auth?.icon
            )
        } else {
            if (entity.me != null && entity.me!!.isContentOwner && entity.parent == null) {
                binding.commentAuthor.visibility = View.VISIBLE
            } else {
                binding.commentAuthor.visibility = View.GONE
            }
            if (parentUser != null && !TextUtils.isEmpty(parentUser.name)) {
                val name = "${entity.user.name} 回复 ${parentUser.name}"
                binding.commentUserName.text = SpanBuilder(name).color(
                    binding.root.context,
                    (entity.user.name?.length ?: 0) + 1,
                    (entity.user.name?.length ?: 0) + 3,
                    R.color.text_subtitle
                ).build()
            } else {
                binding.commentUserName.text = entity.user.name
            }
            binding.commentUserIcon.display(
                entity.user.border,
                entity.user.icon,
                entity.user.auth?.icon
            )
        }

    }

    fun initCommentViewHolder(
        holder: StairsCommentViewHolder,
        mViewModel: NewCommentViewModel,
        commentEntity: CommentEntity,
        mEntrance: String,
        mIsShowingConversation: Boolean,
        mCommentOptionClickListener: OnCommentOptionClickListener?,
        mCommentCallBackListener: OnCommentCallBackListener
    ) {
        val context = holder.binding.root.context
        var isChildLongClick = false
        holder.setCommentUserView(binding.root.context, commentEntity)
        val params = holder.binding.commentContainer.layoutParams as LinearLayout.LayoutParams
        if (isReplyComment) {
            params.leftMargin = 0
            params.rightMargin = 0
            holder.binding.replyContainer.visibility = View.GONE
        } else {
            commentEntity.reply = commentEntity.reply - (commentEntity.subCommentList?.size ?: 0)
            params.bottomMargin = if (commentEntity.reply > 0) {
                16f.dip2px()
            } else {
                24f.dip2px()
            }
            initStairsReplyComment(
                holder,
                mViewModel,
                commentEntity,
                mEntrance,
                mIsShowingConversation,
                mCommentOptionClickListener,
                mCommentCallBackListener
            )
        }
        holder.binding.commentContainer.layoutParams = params

        if (!TextUtils.isEmpty(mViewModel.videoId)) {
            val spannable = TextHelper.getHighlightedSpannableStringThatIsWrappedInsideWrapper(
                context, commentEntity.content
                    ?: ""
            )

            //当评论同时满足以下两个条件：①来源于作者；②权重为1时，前端不显示“置顶”标志
            if (!(commentEntity.me?.isContentOwner == true && commentEntity.priority == 1)) {
                if (commentEntity.priority != 0) {
                    spannable.append("   ")
                    spannable.setSpan(
                        CenterImageSpan(
                            HaloApp.getInstance().application,
                            R.drawable.ic_comment_top
                        ), spannable.length - 1, spannable.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            }
            holder.binding.commentContent.text = spannable
        } else {
            holder.binding.commentContent.text = commentEntity.content
        }
        CommentUtils.setCommentTime(holder.binding.commentTime, commentEntity.time)
        if (commentEntity.source != null && commentEntity.source.region.isNotEmpty()) {
            holder.binding.commentTime.text = "${holder.binding.commentTime.text} · ${commentEntity.source.region}"
        }

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

        holder.binding.sdvUserBadge.setOnClickListener { v ->
            DialogUtils.showViewBadgeDialog(binding.root.context, commentEntity.user.badge) {
                MtaHelper.onEvent(
                    "进入徽章墙_用户记录",
                    key,
                    commentEntity.user.name + "（" + commentEntity.user.id + "）"
                )
                MtaHelper.onEvent("徽章中心", "进入徽章中心", key)
                DirectUtils.directToBadgeWall(
                    binding.root.context,
                    commentEntity.user.id,
                    commentEntity.user.name,
                    commentEntity.user.icon
                )
            }
        }

        var isVote = holder.binding.commentLikeCount.currentTextColor == ContextCompat.getColor(
            context,
            R.color.theme_font
        )
        holder.binding.commentLikeContainer.setOnClickListener {
            FastClickUtils.click {
                if (!it) {
                    if (holder.binding.commentLikeCount.currentTextColor == ContextCompat.getColor(
                            context,
                            R.color.theme_font
                        )
                    ) {
                        commentEntity.vote = commentEntity.vote - 1
                        holder.binding.commentLikeCount.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.hint
                            )
                        )
                        holder.binding.commentLike.setImageResource(R.drawable.comment_vote_unselect)
                        holder.binding.commentLikeCount.text = transSimpleCount(commentEntity.vote)
                        holder.binding.commentLikeCount.visibility =
                            if (commentEntity.vote == 0) View.GONE else View.VISIBLE
                    } else {
                        commentEntity.vote = commentEntity.vote + 1
                        holder.binding.commentLikeCount.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.theme_font
                            )
                        )
                        holder.binding.commentLike.setImageResource(R.drawable.comment_vote_select)
                        holder.binding.commentLikeCount.text = transSimpleCount(commentEntity.vote)
                        holder.binding.commentLikeCount.visibility = View.VISIBLE
                    }
                } else {
                    if (isVote && holder.binding.commentLikeCount.currentTextColor != ContextCompat.getColor(
                            context,
                            R.color.theme_font
                        )
                    ) {
                        //取消点赞
                        CommentUtils.unVoteVideoComment(
                            binding.root.context,
                            mViewModel.videoId,
                            commentEntity,
                            holder.binding.commentLikeCount,
                            holder.binding.commentLike
                        )
                    } else if (!isVote && holder.binding.commentLikeCount.currentTextColor == ContextCompat.getColor(
                            context,
                            R.color.theme_font
                        )
                    ) {
                        //点赞
                        CommentUtils.voteVideoComment(
                            binding.root.context,
                            mViewModel.answerId,
                            mViewModel.articleId,
                            mViewModel.communityId,
                            mViewModel.videoId,
                            commentEntity,
                            holder.binding.commentLikeCount,
                            holder.binding.commentLike,
                            null
                        )
                    }
                    isVote =
                        holder.binding.commentLikeCount.currentTextColor == ContextCompat.getColor(
                            context,
                            R.color.theme_font
                        )
                }
            }
        }

        holder.itemView.setOnLongClickListener(View.OnLongClickListener {
            isChildLongClick = true
            CommentHelper.showVideoCommentOptions(
                holder.binding.commentLikeContainer,
                commentEntity,
                mIsShowingConversation,
                mViewModel.videoId,
                mViewModel.isVideoAuthor,
                false,
                mCommentOptionClickListener
            )
            return@OnLongClickListener true
        })

        holder.itemView.setOnClickListener {
            if (isChildLongClick) {
                isChildLongClick = false
                return@setOnClickListener
            }
            binding.root.context.ifLogin("回答详情-评论-回复") {
                mCommentCallBackListener.onCommentCallback(commentEntity)
            }
        }
        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 -> "游戏单详情-评论管理"
        }
        holder.binding.commentUserIcon.setOnClickListener {
            DirectUtils.directToHomeActivity(
                binding.root.context,
                commentEntity.user.id,
                2,
                mEntrance,
                path
            )
        }
        holder.binding.commentUserName.setOnClickListener {
            DirectUtils.directToHomeActivity(
                binding.root.context,
                commentEntity.user.id,
                2,
                mEntrance,
                path
            )
        }
    }

    //楼层回复
    private fun initStairsReplyComment(
        holder: StairsCommentViewHolder,
        mViewModel: NewCommentViewModel,
        commentEntity: CommentEntity,
        mEntrance: String,
        mIsShowingConversation: Boolean,
        mCommentOptionClickListener: OnCommentOptionClickListener?,
        mCommentCallBackListener: OnCommentCallBackListener
    ) {
        holder.binding.replyContainer.visibility =
            if (commentEntity.reply > 0 || !commentEntity.subCommentList.isNullOrEmpty()) View.VISIBLE else View.GONE
        holder.binding.expandMoreLl.visibility =
            if (commentEntity.reply > 0) View.VISIBLE else View.GONE
        var stairsCommentReplyAdapter: StairsCommentReplyAdapter?
        holder.binding.stairsRv.apply {
            isNestedScrollingEnabled = false
            layoutManager = LinearLayoutManager(holder.binding.root.context)
            stairsCommentReplyAdapter = StairsCommentReplyAdapter(
                holder.binding.root.context,
                mViewModel,
                commentEntity,
                mEntrance,
                mIsShowingConversation,
                mCommentOptionClickListener,
                mCommentCallBackListener
            )
            if (commentEntity.subCommentList != null) {
                stairsCommentReplyAdapter?.replyComments?.addAll(commentEntity.subCommentList!!)
            }
            adapter = stairsCommentReplyAdapter
        }
        setExpandMoreView(holder, commentEntity, true)
        holder.binding.expandMoreLl.setOnClickListener {
            stairsCommentReplyAdapter?.apply {
                if (holder.binding.expandMoreTv.text == "收起") {
                    isFirstClick = true
                    page = 0
                    replyComments.clear()
                    if (commentEntity.subCommentList != null) {
                        replyComments.addAll(commentEntity.subCommentList!!)
                    }
                    notifyDataSetChanged()
                    setExpandMoreView(holder, commentEntity, true)
                } else {
                    page++
                    getCommentReply {
                        if (it < 3 || replyComments.size == commentEntity.reply + (commentEntity.subCommentList?.size
                                ?: 0)
                        ) {
                            setExpandMoreView(holder, commentEntity, false)
                        } else {
                            setExpandMoreView(holder, commentEntity, true)
                        }
                    }
                    isFirstClick = false
                }
            }
        }
    }

    private fun setExpandMoreView(
        holder: StairsCommentViewHolder,
        commentEntity: CommentEntity,
        isExpand: Boolean
    ) {
        if (isExpand) {
            holder.binding.expandMoreTv.text = if (isFirstClick) {
                "展开${commentEntity.reply}条回复"
            } else {
                "展开更多回复"
            }
            holder.binding.expandMoreIv.setImageDrawable(
                ContextCompat.getDrawable(
                    holder.binding.root.context,
                    R.drawable.ic_expand_down
                )
            )
        } else {
            holder.binding.expandMoreTv.text = "收起"
            holder.binding.expandMoreIv.setImageDrawable(
                ContextCompat.getDrawable(
                    holder.binding.root.context,
                    R.drawable.ic_shrink_up
                )
            )
        }
    }
}