package com.gh.gamecenter.qa.answer

import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.GradientDrawable
import android.text.SpannableStringBuilder
import android.view.View
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewsUtils
import com.gh.gamecenter.CollectionActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.callback.ConfirmListener
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.SpanBuilder
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.ArticleEntity

/**
 * 因为社区回答和社区文章的样式完全一样，所以就统一处理吧！有需要时可以直接复制一份作为单独的社区文章样式
 *
 * 注意：相当一部分页面时回答和文章混合的请注意区分
 */
class CommunityAnswerItemViewHolder(val binding: CommunityAnswerItemBinding) :
    BaseAnswerOrArticleItemViewHolder(binding.root) {

    fun bindAnswerItem(entity: AnswerEntity, entrance: String, path: String) {
        bindAnswerItem(entity, false, entrance, path)
    }

    /**
     * 大部分的列表样式都通用此样式，但有稍微不一样的地方 (问题详情的答案列表），不一样的地方是不显示标题，答案内容加粗 (可见 https://gitlab.ghzs.com/pm/halo-app-issues/issues/771)
     * @param useAlternativeStyle 是否使用与普通样式略微不一样的样式
     */
    fun bindAnswerItem(entity: AnswerEntity, useAlternativeStyle: Boolean, entrance: String, path: String) {
        changeVoteAndCommentStyle()

        bindItem(entity, entrance, path)
        bindCommendAndVote(entity, entrance)

        if (useAlternativeStyle) {
            changeToAlternativeStyle()
        }
    }

    fun bindArticleItem(entity: ArticleEntity, entrance: String, path: String) {
        bindItem(entity.transformAnswerEntity(), entrance, path)
        bindCommendAndVote(entity, entrance)
    }

    private fun changeVoteAndCommentStyle() {
        binding.forumNameLl.visibility = View.GONE
        val params = binding.includeVoteAndComment.root.layoutParams as LinearLayout.LayoutParams
        params.width = LinearLayout.LayoutParams.MATCH_PARENT
        params.leftMargin = 0
        params.rightMargin = 0
        binding.includeVoteAndComment.root.layoutParams = params
    }

    private fun changeToAlternativeStyle() {
        binding.title.visibility = View.GONE
        binding.content.textSize = 14F
        binding.content.setLineSpacing(DisplayUtils.sp2px(binding.root.context, 4F).toFloat(), 1.0F)
        binding.content.setTextColor(R.color.text_title.toColor(binding.content.context))
        binding.content.maxLines = 3
    }

    private fun bindItem(entity: AnswerEntity, entrance: String, path: String) {
        binding.run {
            BaseActivity.updateStaticView(root, emptyList())
            questionTitle.goneIf(entity.type != "answer")
            questionTitle.text = entity.questions.title
            userName.text = entity.user.name
            userBadgeName.text = entity.user.badge?.name
            ImageUtils.display(userBadgeIcon, entity.user.badge?.icon)
            ImageUtils.display(popularAnswerUserIcon, entity.popularAnswer?.user?.icon)
            userBadgeIcon.goneIf(entity.user.badge == null)
            concernBtn.goneIf(entity.me.isFollower || entity.user.id == UserManager.getInstance().userId)
            time.text =
                (if (entity.me.isFollower || entity.status == "pending" || entity.status == "fail") " · " else "") + NewsUtils.getFormattedTime(
                    entity.time!!
                )
            statusTv.goneIf(!(entity.status == "pending" || entity.status == "fail") && !entity.me.isFollower)
            statusTv.setText(
                when {
                    entity.me.isFollower -> R.string.follow_status
                    entity.status == "pending" -> R.string.content_pending_status
                    else -> R.string.fail_status
                }
            )
            statusTv.setTextColor(
                when {
                    entity.me.isFollower -> R.color.theme_alpha_80
                    entity.status == "pending" -> R.color.text_subtitleDesc
                    else -> R.color.text_CCFF5269
                }.toColor(statusTv.context)
            )
            statusTv.setDrawableStart(
                when {
                    entity.me.isFollower -> R.drawable.ic_forum_follow
                    entity.status == "pending" -> R.drawable.ic_forum_pending
                    else -> R.drawable.icon_forum_fail
                }
            )
            title.goneIf(entity.type == "answer")
            title.text = if (entity.type.contains("video")) entity.articleTitle else entity.questions.title
            content.text = if (entity.type.contains("video")) entity.des else entity.brief
            popularAnswerContainer.background = GradientDrawable().apply {
                setColor(Color.parseColor("#F5F6F7"))
                cornerRadius = 4F.dip2px().toFloat()
            }
            popularAnswerUserName.text = entity.popularAnswer?.user?.name
            popularAnswerContent.text = entity.popularAnswer?.brief
            forumNameTv.text = entity.bbs.name
        }

        binding.userIcon.display(entity.user.border, entity.user.icon, entity.user.auth?.icon)
        binding.imageContainer.bindData(entity, entrance, path)

        val spanBuilder = SpannableStringBuilder()
        if (entity.type == "question") {
            val title = "  ${binding.title.text}"
            val askLabelSpan = SpanBuilder(title).image(0, 1, R.drawable.ic_ask_label).build()
            spanBuilder.append(askLabelSpan)
        } else {
            spanBuilder.append(binding.title.text)
        }
        if (entity.getPassVideos().isNotEmpty() && entity.images.isNotEmpty()) {
            val videoSpan = SpanBuilder("  ").image(1, "  ".length, R.drawable.ic_article_video_label).build()
            spanBuilder.append(videoSpan)
        }
        binding.title.text = spanBuilder
        val user = entity.user
        binding.userBadgeName.setOnClickListener { binding.userBadgeIcon.performClick() }
        binding.userBadgeIcon.setOnClickListener {
            DialogUtils.showViewBadgeDialog(binding.root.context, user.badge, object : ConfirmListener {
                override fun onConfirm() {
                    var key = ""
                    if (path == "标签专栏-热门") {
                        key = "问题标签详情-热门"
                    } else if (path == "标签专栏-精华") {
                        key = "问题标签详情-精华"
                    } else if (path == "专栏-热门") {
                        key = "问答-专栏详情-热门"
                    } else if (path == "专栏-精华") {
                        key = "问答-专栏详情-精华"
                    } else if (path == "游戏详情-动态") {
                        key = "游戏详情-热门回答"
                    } else if (path == "问答-推荐-按精选" || path == "问答-推荐-按时间") {
                        key = "问答-推荐"
                    } else if (path == "问题详情" || path == "折叠答案") {
                        key = path
                    } else {
                        key = path // 默认就使用path字段吧，总比为空的好
                    }
                    MtaHelper.onEvent("进入徽章墙_用户记录", key, user.name + "（" + user.id + "）")
                    MtaHelper.onEvent("徽章中心", "进入徽章中心", key)
                    DirectUtils.directToBadgeWall(binding.root.context, user.id, user.name, user.icon)
                }
            })
        }

        val userClick = View.OnClickListener {
            DirectUtils.directToHomeActivity(
                binding.root.context,
                entity.user.id,
                entrance,
                path
            )
        }
        binding.userIcon.setOnClickListener(userClick)
        binding.userName.setOnClickListener(userClick)

        // 内容修改时，再标题加上红点，一般用于收藏
        if (!entity.read) {
            binding.title.post {
                val lineCount = binding.title.lineCount
                if (lineCount > 0) {
                    val lineWidth = binding.title.layout.getLineWidth(lineCount - 1)
                    val layoutParams = binding.unreadHint.layoutParams as ConstraintLayout.LayoutParams
                    layoutParams.setMargins(lineWidth.toInt(), 0, 0, DisplayUtils.dip2px(18f))
                    binding.unreadHint.layoutParams = layoutParams
                    binding.unreadHint.visibility = View.VISIBLE
                }
            }
        } else {
            binding.unreadHint.visibility = View.GONE
        }

        // 如果当前回答/文章被删除则内容加上删除线，一般用于收藏
        if (!entity.active && itemView.context is CollectionActivity) {
            binding.content.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            binding.content.setTextColor(ContextCompat.getColor(itemView.context, R.color.hint))
        } else {
            binding.content.paint.flags = Paint.ANTI_ALIAS_FLAG
            binding.content.setTextColor(ContextCompat.getColor(itemView.context, R.color.text_subtitle))
        }
    }
}