package com.gh.gamecenter.gamedetail.rating

import android.annotation.SuppressLint
import android.graphics.drawable.ColorDrawable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import com.gh.common.util.*
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ItemArticleDetailCommentBinding
import com.gh.gamecenter.entity.RatingComment
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity.Companion.LABEL_REGEX
import com.gh.gamecenter.gamedetail.rating.logs.CommentLogsActivity
import com.gh.gamecenter.login.user.UserManager
import java.util.regex.Pattern

class RatingDetailCommentItemViewHolder(val binding: ItemArticleDetailCommentBinding) :
    BaseRecyclerViewHolder<Any>(binding.root) {
    @SuppressLint("CheckResult")
    fun setContent(
        commentData: RatingComment,
        viewModel: RatingReplyViewModel,
        dataPosition: Int,
        entrance: String,
        path: String
    ) {
        binding.run {
            val game = viewModel.game
            ConstraintSet().apply {
                clone(contentTv.parent as ConstraintLayout)
                clear(contentTv.id, ConstraintSet.START)
                connect(contentTv.id, ConstraintSet.START, userIconIv.id, ConstraintSet.START)

                clear(commentPictureRv.id, ConstraintSet.START)
                connect(commentPictureRv.id, ConstraintSet.START, userIconIv.id, ConstraintSet.START)

                clear(bottomContainer.id, ConstraintSet.START)
                connect(bottomContainer.id, ConstraintSet.START, userIconIv.id, ConstraintSet.START)

                applyTo(contentTv.parent as ConstraintLayout)
            }
            (contentTv.layoutParams as ConstraintLayout.LayoutParams).apply {
                topMargin = 16F.dip2px()
                leftMargin = 9F.dip2px()
                contentTv.layoutParams = this
            }
            (bottomContainer.layoutParams as ConstraintLayout.LayoutParams).apply {
                leftMargin = 9F.dip2px()
                bottomContainer.layoutParams = this
            }
            divider.visibility = View.VISIBLE
            timeTv.visibility = View.GONE
            commentCountTv.visibility = View.GONE

            val context = itemView.context
            val p = Pattern.compile(LABEL_REGEX)
            val m = p.matcher(commentData.content)
            if (m.find()) {
                val contents = TextHelper.getCommentLabelSpannableStringBuilder(commentData.content, R.color.theme_font)
                contentTv.setTextWithHighlightedTextWrappedInsideWrapper(text = contents, copyClickedText = true)
            } else {
                contentTv.setTextWithHighlightedTextWrappedInsideWrapper(
                    text = commentData.content,
                    copyClickedText = true
                )
            }
            root.setBackgroundColor(R.color.background_white.toColor(context))
            userNameTv.setTextColor(R.color.text_title.toColor(context))
            userNameTv.text = commentData.user.name
            ratingStar.visibility = View.VISIBLE
            ratingStar.rating = commentData.star.toFloat()
            device.text = commentData.getDevice()
            device.visibility =
                if (commentData.active && commentData.getDevice().isNotEmpty()) View.VISIBLE else View.GONE
            version.visibility =
                if (commentData.active && commentData.gameVersion.isNotEmpty()) View.VISIBLE else View.GONE
            if (commentData.me.isVoted) {
                likeCountTv.setTextColor(R.color.theme_font.toColor(likeCountTv.context))
                likeCountTv.setDrawableStart(R.drawable.comment_vote_select)
            } else {
                likeCountTv.setTextColor(R.color.text_subtitleDesc.toColor(likeCountTv.context))
                likeCountTv.setDrawableStart(R.drawable.comment_vote_unselect)
            }
            likeCountTv.text = if (commentData.vote > 0) NumberUtils.transSimpleCount(commentData.vote) else ""
            likeCountTv.goneIf(!commentData.active)
            userIconIv.display(commentData.user.border, commentData.user.icon, commentData.user.auth?.icon)
            ipRegionTv.goneIf(!(commentData.source != null && commentData.source.region.isNotEmpty()))
            ipRegionTv.text = " · ${commentData.source?.region}"
            time.visibility = View.VISIBLE
            when {
                commentData.isEditContent == null -> {
                    time.setTextColor(ContextCompat.getColor(context, R.color.text_subtitleDesc))
                    time.text = if (commentData.ignore) {
                        val s = "${NewsUtils.getFormattedTime(commentData.time)}    保护期评论不计入总分"
                        SpanBuilder(s).image(s.length - 12, s.length - 11, R.drawable.ic_ignore_rating_tips)
                            .color(context, s.length - 10, s.length, R.color.text_subtitle).build()
                    } else {
                        NewsUtils.getFormattedTime(commentData.time)
                    }
                }
                commentData.isEditContent!! -> {
                    time.setTextColor(ContextCompat.getColor(context, R.color.text_F56614))
                    time.text = if (commentData.ignore) {
                        "${NewsUtils.getFormattedTime(commentData.time)} 保护期间修改评论 >"
                    } else {
                        "${NewsUtils.getFormattedTime(commentData.time)} 已修改 >"
                    }
                }
                else -> {
                    time.setTextColor(ContextCompat.getColor(context, R.color.text_F56614))
                    time.text = if (commentData.ignore) {
                        "${NewsUtils.getFormattedTime(commentData.time)} 保护期间修改评论"
                    } else {
                        "${NewsUtils.getFormattedTime(commentData.time)} 已修改"
                    }

                }
            }

            if (commentData.user.badge != null) {
                badgeIv.visibility = View.VISIBLE
                ImageUtils.display(badgeIv, commentData.user.badge?.icon)
                badgeTv.text = commentData.user.badge?.name
            } else {
                badgeIv.visibility = View.GONE
                badgeTv.visibility = View.GONE
            }

            if (game != null && game.getApk().size > 0 && game.getApk()[0].version == commentData.gameVersion) {
                version.text = "当前版本"
            } else {
                version.text = ("版本：" + commentData.gameVersion)
            }

            if (commentData.me.isCommented) {
                commentBadge.visibility = View.VISIBLE
                commentBadge.text = "我的评价"
                commentBadge.background = DrawableView.getCornerGradientDrawable(
                    ContextCompat.getColor(context, R.color.text_4BC7FF),
                    ContextCompat.getColor(context, R.color.theme),
                    5f
                )
            } else if (commentData.order > 0 && commentData.isWonderful) {
                commentBadge.visibility = View.VISIBLE
                commentBadge.text = "精彩评价"
                commentBadge.background = DrawableView.getCornerGradientDrawable(
                    ContextCompat.getColor(context, R.color.text_FFB749),
                    ContextCompat.getColor(context, R.color.text_FF6D3C),
                    5f
                )
            } else if (commentData.isServiceComment) {
                commentBadge.visibility = View.VISIBLE
                commentBadge.text = "客服"
                commentBadge.background = DrawableView.getCornerGradientDrawable(
                    ContextCompat.getColor(context, R.color.text_4BC7FF),
                    ContextCompat.getColor(context, R.color.theme),
                    5f
                )
            } else {
                commentBadge.visibility = View.GONE
            }

            userIconIv.setOnClickListener {
                if (path == "评论详情") {
                    NewLogUtils.logCommentTabOrCommentDetailClick(
                        "click_game_comment_detail_commet_profile_photo",
                        game?.id ?: "",
                        game?.gameType ?: "",
                        commentData.user.id ?: ""
                    )
                }
                if (path == "游戏详情：评分") {
//                    MtaHelper.onEvent("游戏详情_新", "评论Tab-点击用户头像", game?.name)
                    NewLogUtils.logCommentTabOrCommentDetailClick(
                        "click_allcomment_profile_photo",
                        game?.id ?: "",
                        game?.gameType ?: "",
                        commentData.user.id ?: ""
                    )
                }
//                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "点击用户头像", game?.name)
                logGameDetailCommentDetailCommentClick(viewModel, entrance, "作者用户信息")
                DirectUtils.directToHomeActivity(context, commentData.user.id, entrance, getKey(path))
            }
            userNameTv.setOnClickListener {
                if (path == "评论详情") {
                    NewLogUtils.logCommentTabOrCommentDetailClick(
                        "click_game_comment_detail_commet_nickname",
                        game?.id ?: "",
                        game?.gameType ?: "",
                        commentData.user.id ?: ""
                    )
                }
                if (path == "游戏详情：评分") {
//                    MtaHelper.onEvent("游戏详情_新", "评论Tab-点击用户名字", game?.name)
                    NewLogUtils.logCommentTabOrCommentDetailClick(
                        "click_allcomment_nickname",
                        game?.id ?: "",
                        game?.gameType ?: "",
                        commentData.user.id ?: ""
                    )
                }
//                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "点击用户名字", game?.name)
                logGameDetailCommentDetailCommentClick(viewModel, entrance, "作者用户信息")
                DirectUtils.directToHomeActivity(context, commentData.user.id, entrance, getKey(path))
            }

            badgeIv.setOnClickListener {
                DialogUtils.showViewBadgeDialog(context, commentData.user.badge, object : ConfirmListener {
                    override fun onConfirm() {
//                    MtaHelper.onEvent("进入徽章墙_用户记录", getKey(path), "${commentData.user.name}（${commentData.user.id}）")
//                    MtaHelper.onEvent("徽章中心", "进入徽章中心", getKey(path))
                        DirectUtils.directToBadgeWall(
                            context,
                            commentData.user.id,
                            commentData.user.name,
                            commentData.user.icon
                        )
                    }
                })
            }
            badgeTv.setOnClickListener { badgeIv.performClick() }

            moreIv.setOnClickListener {
//                if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_更多按钮", game?.name)
//                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "点击更多", game?.name)
                logGameDetailCommentDetailCommentClick(viewModel, entrance, "展开评价右上角")
                showMorePopWindow(it, commentData.user.id == UserManager.getInstance().userId) { text ->
                    when (text) {
                        "复制" -> {
//                            if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_复制", game?.name)
//                            if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "更多-复制", game?.name)
                            NewLogUtils.logCommentTabOrCommentDetailClick(
                                "click_allcomment_copy",
                                game?.id ?: "",
                                game?.gameType ?: ""
                            )
                            logGameDetailCommentDetailCommentClick(viewModel, entrance, "评价右上角-复制")
                            commentData.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "")
                                .copyTextAndToast()
                        }
                        "修改" -> {
//                            if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_修改", game?.name)
//                            if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "更多-修改", game?.name)
                            logGameDetailCommentDetailCommentClick(viewModel, entrance, "评价右上角-修改")
                            val intent = RatingEditActivity.getPatchIntent(context, game!!, commentData)
                            SyncDataBetweenPageHelper.startActivityForResult(
                                context,
                                intent,
                                RatingFragment.RATING_PATCH_REQUEST,
                                dataPosition
                            )
                        }
                        "投诉" -> {
//                            if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_投诉", game?.name)
//                            if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "更多-投诉", game?.name)
                            NewLogUtils.logCommentTabOrCommentDetailClick(
                                "click_allcomment_report",
                                game?.id ?: "",
                                game?.gameType ?: ""
                            )
                            logGameDetailCommentDetailCommentClick(viewModel, entrance, "评价右上角-投诉")
                            context.ifLogin(BaseActivity.mergeEntranceAndPath(entrance, path)) {
                                DialogUtils.showReportReasonDialog(
                                    context,
                                    Constants.REPORT_LIST.toList() as ArrayList<String>
                                ) { reason, desc ->
                                    SimpleRequestHelper.reportGameComment(
                                        game?.id ?: "",
                                        commentData.id,
                                        if (reason != "其他原因") reason else desc
                                    )
                                }
                            }
                        }
                        "删除" -> {
                            logGameDetailCommentDetailCommentClick(viewModel, entrance, "评价右上角-删除")
                            DialogHelper.showDeleteGameCommentDialog(
                                context,
                                R.string.delete_game_comment.toResString()
                            ) {
                                SimpleRequestHelper.deleteGameComment(game?.id ?: "", commentData.id) {
                                    SyncDataBetweenPageHelper.setResultAndFinish(
                                        context,
                                        commentData,
                                        RatingFragment.RATING_DELETE_RESULT
                                    )
                                }
                            }
                        }
                    }
                }
            }

            time.setOnClickListener {
                if (commentData.isEditContent == null && commentData.ignore) {
//                    if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab-评论说明", game?.name)
//                    if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "评论说明", game?.name)
                    DialogUtils.showStopServerExplanationDialog(
                        context, if (game?.commentDescription?.isNotEmpty() == true) game.commentDescription else
                            context.getString(R.string.rating_protection), game?.name ?: ""
                    )
                } else if (commentData.isEditContent == true) {
//                    if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab-点击时间", game?.name)
//                    if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "点击时间", game?.name)
                    val intent = CommentLogsActivity.getIntent(context, game!!.id, commentData.id)
                    context.startActivity(intent)
                }
            }

            if (!commentData.active) {
                if (commentData.audit) {
                    audit.text = "您修改后的评价已提交，小助手将尽快审核~"
                } else {
                    val auditText = SpannableStringBuilder("您的评价因违反了《光环助手评论规则》暂时被隐藏~ 去修改")
                    auditText.setSpan(object : ClickableSpan() {
                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.color = R.color.theme_font.toColor(context)
                        }

                        override fun onClick(widget: View) {
                            context.startActivity(
                                WebActivity.getWebIntent(
                                    context,
                                    context.getString(R.string.comment_rules_title),
                                    context.getString(R.string.comment_rules_url)
                                )
                            )
                        }
                    }, 8, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

                    auditText.setSpan(object : ClickableSpan() {
                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.color = R.color.theme_font.toColor(context)
                        }

                        override fun onClick(widget: View) {
                            val intent = RatingEditActivity.getPatchIntent(context, game!!, commentData)
                            SyncDataBetweenPageHelper.startActivityForResult(
                                context,
                                intent,
                                RatingFragment.RATING_PATCH_REQUEST,
                                dataPosition
                            )
                        }
                    }, auditText.length - 3, auditText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                    audit.text = auditText
                    audit.movementMethod = LinkMovementMethod()
                }

                commentCountTv.post {
                    commentCountTv.visibility = View.INVISIBLE
                    likeCountTv.visibility = View.INVISIBLE
                }
            }
        }
    }

    private fun getKey(path: String): String {
        return when (path) {
            "游戏详情：介绍" -> "游戏详情-玩家评论"
            "游戏详情：评分" -> "游戏详情-评论列表"
            "评论详情" -> "游戏评论详情"
            "折叠评论" -> "折叠评论"
            else -> ""
        }
    }

    private fun showMorePopWindow(v: View, isMyRating: Boolean, clickListener: (String) -> Unit) {
        val contentList = if (isMyRating) arrayListOf("复制", "修改", "删除") else arrayListOf("复制", "投诉")

        val inflater = LayoutInflater.from(v.context)
        val layout = inflater.inflate(R.layout.layout_popup_container, null)
        val popupWindow = PopupWindow(
            layout,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        popupWindow.apply {
            setBackgroundDrawable(ColorDrawable(0))
            isTouchable = true
            isFocusable = true
            isOutsideTouchable = true
        }

        val container = layout.findViewById<LinearLayout>(R.id.container)
        for (text in contentList) {
            val item = inflater.inflate(R.layout.layout_popup_option_item, container, false)
            container.addView(item)

            val hitText = item.findViewById<TextView>(R.id.hint_text)
            hitText.text = text

            item.setOnClickListener {
                clickListener.invoke(text)
                popupWindow.dismiss()
            }
        }

        popupWindow.showAutoOrientation(v)
    }

    private fun logGameDetailCommentDetailCommentClick(
        viewModel: RatingReplyViewModel,
        entrance: String,
        button: String
    ) {
        viewModel.run {
            val location = when {
                lastPageData.contains(EntranceConsts.KEY_LOCATION) -> lastPageData[EntranceConsts.KEY_LOCATION]
                entrance.contains("安利墙") -> "安利墙"
                else -> "其他"
            }
            val tag = if (location == "全部评价") lastPageData[EntranceConsts.KEY_SORT] else ""
            val filter = if (location == "全部评价") lastPageData[EntranceConsts.KEY_FILTER] else ""
            NewFlatLogUtils.logGameDetailCommentDetailCommentClick(
                location ?: "",
                tag ?: "",
                filter ?: "",
                button,
                game?.name ?: "",
                game?.id ?: "",
                commentId ?: ""
            )
        }
    }
}