package com.gh.gamecenter.gamedetail.detail.viewholder

import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.*
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.ItemGameDetailRecyclerViewBinding
import com.gh.gamecenter.databinding.SubItemGameDetailCommentBinding
import com.gh.gamecenter.entity.RatingComment
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.gamecenter.gamedetail.GameDetailViewModel
import com.gh.gamecenter.gamedetail.entity.GameDetailData
import com.gh.gamecenter.gamedetail.entity.GameDetailTabEntity
import com.gh.gamecenter.gamedetail.rating.RatingReplyActivity
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity
import com.gh.gamecenter.gamedetail.rating.logs.CommentLogsActivity
import com.gh.gamecenter.login.user.UserManager
import java.util.regex.Pattern

class GameDetailCommentItemViewHolder(
    val binding: ItemGameDetailRecyclerViewBinding,
    downloadBtn: DownloadButton?,
    viewModel: GameDetailViewModel
) : BaseGameDetailItemViewHolder(binding.root, downloadBtn, viewModel) {
    override fun bindView(data: GameDetailData) {
        super.bindView(data)
        val entity = data.linkComment ?: return
        binding.run {
            titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
            moreTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
            moreTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_right_text_theme_12.toDrawable(context))
            titleTv.text = entity.name
            moreTv.isVisible = true
            moreTv.text = "更多"
            moreTv.setOnClickListener {
                viewModel.performTabSelected(GameDetailTabEntity.TYPE_COMMENT)
                SensorsBridge.trackGameDetailModuleClick(
                    gameId,
                    gameName,
                    gameType,
                    "右上角",
                    moduleType,
                    entity.name,
                    sequence,
                    gameStatus = gameStatus
                )
            }

            if (recyclerView.adapter !is CommentItemAdapter) {
                recyclerView.isNestedScrollingEnabled = false
                (recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
                recyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                recyclerView.adapter = CommentItemAdapter(entity.data)
            } else {
                recyclerView.adapter?.run { notifyItemRangeChanged(0, itemCount) }
            }
        }
    }

    inner class CommentItemAdapter(val dataList: ArrayList<RatingComment>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val path = "游戏详情-玩家评论"

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
            CommentItemViewHolder(parent.toBinding())

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val commentData = dataList.getOrNull(position) ?: return
            var isChildLongClick = false
            if (holder is CommentItemViewHolder) {
                holder.binding.run {
                    root.background = R.drawable.bg_shape_f8_radius_8.toDrawable(context)
                    root.updateLayoutParams<MarginLayoutParams> {
                        leftMargin = if (position == 0) 16F.dip2px() else 8F.dip2px()
                        rightMargin = if (position == itemCount - 1) 16F.dip2px() else 0
                    }
                    userNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context))
                    tvBadgeName.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    commentTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
                    ipRegionTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                    moreIv.setImageResource(R.drawable.game_comment_more)
                    userIcon.display(commentData.user.border, commentData.user.icon, commentData.user.auth?.icon)
                    userNameTv.text = commentData.user.name
                    ratingStar.rating = commentData.star.toFloat()
                    if (commentData.user.badge != null) {
                        sdvUserBadge.visibility = View.VISIBLE
                        tvBadgeName.visibility = View.VISIBLE
                        ImageUtils.display(sdvUserBadge, commentData.user.badge?.icon)
                        tvBadgeName.text = commentData.user.badge?.name
                    } else {
                        sdvUserBadge.visibility = View.GONE
                        tvBadgeName.visibility = View.GONE
                    }
                    commentTv.setExpandCallback {
                        root.performClick()
                    }
                    val p = Pattern.compile(RatingEditActivity.LABEL_REGEX)
                    val m = p.matcher(commentData.content)
                    if (m.find()) {
                        val contents =
                            TextHelper.getCommentLabelSpannableStringBuilder(commentData.content, com.gh.gamecenter.common.R.color.text_theme)
                        commentTv.setTextWithHighlightedTextWrappedInsideWrapper(
                            text = contents,
                            highlightedTextClickListener = TextHelper.DirectToWebViewHighlightedTextClick(
                                context,
                                "游戏详情-玩家评论"
                            )
                        )
                    } else {
                        commentTv.setTextWithHighlightedTextWrappedInsideWrapper(
                            text = commentData.content,
                            highlightedTextClickListener = TextHelper.DirectToWebViewHighlightedTextClick(
                                context,
                                "游戏详情-玩家评论"
                            )
                        )
                    }
                    ipRegionTv.goneIf(!(commentData.source != null && commentData.source.region.isNotEmpty()))
                    ipRegionTv.text = " · ${commentData.source?.region}"
                    when {
                        commentData.isEditContent == null -> {
                            timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                            timeTv.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, com.gh.gamecenter.common.R.color.text_secondary).build()
                            } else {
                                NewsUtils.getFormattedTime(commentData.time)
                            }
                        }

                        commentData.isEditContent!! -> {
                            timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_F56614.toColor(context))
                            timeTv.text = if (commentData.ignore) {
                                "${NewsUtils.getFormattedTime(commentData.time)} 保护期间修改评论 >"
                            } else {
                                "${NewsUtils.getFormattedTime(commentData.time)} 已修改 >"
                            }
                        }

                        else -> {
                            timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_F56614.toColor(context))
                            timeTv.text = if (commentData.ignore) {
                                "${NewsUtils.getFormattedTime(commentData.time)} 保护期间修改评论"
                            } else {
                                "${NewsUtils.getFormattedTime(commentData.time)} 已修改"
                            }
                        }
                    }
                    sdvUserBadge.setOnClickListener {
                        DialogUtils.showViewBadgeDialog(context, commentData.user.badge) {
                            DirectUtils.directToBadgeWall(
                                context,
                                commentData.user.id,
                                commentData.user.name,
                                commentData.user.icon
                            )
                        }
                        SensorsBridge.trackGameDetailModuleClick(
                            gameId,
                            gameName,
                            gameType,
                            "组件内容",
                            moduleType,
                            itemData?.linkComment?.name,
                            sequence,
                            subModuleName = "玩家评论列表",
                            supSequence = position + 1,
                            gameStatus = gameStatus
                        )
                    }
                    userIcon.setOnClickListener {
                        DirectUtils.directToHomeActivity(
                            context,
                            commentData.user.id,
                            viewModel.entrance,
                            path
                        )
                        NewLogUtils.logGameDetailCommentClick(
                            viewModel.game?.name ?: "",
                            viewModel.game?.id ?: "",
                            "个人主页"
                        )
                        SensorsBridge.trackGameDetailModuleClick(
                            gameId,
                            gameName,
                            gameType,
                            "组件内容",
                            moduleType,
                            itemData?.linkComment?.name,
                            sequence,
                            subModuleName = "玩家评论列表",
                            supSequence = position + 1,
                            gameStatus = gameStatus
                        )
                    }
                    userNameTv.setOnClickListener {
                        userIcon.performClick()
                    }
                    tvBadgeName.setOnClickListener { sdvUserBadge.performClick() }
                    commentTv.setOnLongClickListener(View.OnLongClickListener {
                        isChildLongClick = true
                        commentData.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "")
                            .copyTextAndToast()
                        return@OnLongClickListener true
                    })
                    moreIv.setOnClickListener {
                        showMorePopWindow(it, commentData.user.id == UserManager.getInstance().userId) { text ->
                            when (text) {
                                MORE_COPY -> {
                                    commentData.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "")
                                        .copyTextAndToast()
                                }

                                MORE_MODIFY -> {
                                    val intent =
                                        RatingEditActivity.getPatchIntent(context, viewModel.game!!, commentData)
                                    SyncDataBetweenPageHelper.startActivityForResult(
                                        context,
                                        intent,
                                        RATING_PATCH_REQUEST,
                                        position
                                    )
                                }

                                MORE_REPORT -> {
                                    context.ifLogin(BaseActivity.mergeEntranceAndPath(viewModel.entrance, path)) {
                                        DialogUtils.showReportReasonDialog(
                                            context,
                                            Constants.REPORT_LIST.toList() as java.util.ArrayList<String>
                                        ) { reason, desc ->
                                            SimpleRequestHelper.reportGameComment(
                                                viewModel.game?.id ?: "",
                                                commentData.id,
                                                if (reason != "其他原因") reason else desc
                                            )
                                        }
                                    }
                                }

                                MORE_DELETE -> {
                                    DialogHelper.showDeleteGameCommentDialog(
                                        context,
                                        R.string.delete_game_comment.toResString()
                                    ) {
                                        SimpleRequestHelper.deleteGameComment(
                                            viewModel.game?.id ?: "",
                                            commentData.id
                                        ) {
                                            // 删除列表中的评论(如果当前列表有的话)
                                            val index = dataList.indexOfFirst { item ->
                                                item.id == commentData.id
                                            }
                                            if (index != -1) {
                                                dataList.removeAt(index)
                                                notifyItemRemoved(index)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    timeTv.setOnClickListener {
                        SensorsBridge.trackGameDetailModuleClick(
                            gameId,
                            gameName,
                            gameType,
                            "组件内容",
                            moduleType,
                            itemData?.linkComment?.name,
                            sequence,
                            subModuleName = "玩家评论列表",
                            supSequence = position + 1,
                            gameStatus = gameStatus
                        )
                        if (commentData.isEditContent == null && commentData.ignore) {
                            DialogUtils.showStopServerExplanationDialog(
                                context,
                                if (viewModel.game?.commentDescription?.isNotEmpty() == true)
                                    viewModel.game?.commentDescription else context.getString(R.string.rating_protection),
                                viewModel.game?.name
                                    ?: ""
                            )
                        } else if (commentData.isEditContent == true) {
                            val intent = CommentLogsActivity.getIntent(context, viewModel.game!!.id, commentData.id)
                            context.startActivity(intent)
                        }
                    }
                    root.setOnClickListener {
                        if (isChildLongClick) {
                            isChildLongClick = false
                            return@setOnClickListener
                        }
                        val exposureSource = arrayListOf(
                            ExposureSource("游戏详情"),
                            ExposureSource("详情tab"),
                            ExposureSource("玩家评价"),
                        ).toJson()
                        val intent = RatingReplyActivity.getIntent(
                            context = context,
                            gameId = viewModel.game?.id ?: "",
                            commentId = commentData.id,
                            exposureSource = exposureSource,
                            entrance = viewModel.entrance ?: "",
                            path = path
                        )
                        SyncDataBetweenPageHelper.startActivityForResult(
                            context,
                            intent,
                            RATING_REPLY_REQUEST,
                            position
                        )
                        NewLogUtils.logGameDetailCommentClick(
                            viewModel.game?.name ?: "",
                            viewModel.game?.id ?: "",
                            "评论内容"
                        )
                        SensorsBridge.trackGameDetailModuleClick(
                            gameId,
                            gameName,
                            gameType,
                            "组件内容",
                            moduleType,
                            itemData?.linkComment?.name,
                            sequence,
                            subModuleName = "玩家评论列表",
                            supSequence = position + 1,
                            gameStatus = gameStatus
                        )
                    }
                }
            }
        }

        private fun showMorePopWindow(v: View, isMyRating: Boolean, clickListener: (String) -> Unit) {
            val contentList = if (isMyRating) arrayListOf(MORE_COPY, MORE_MODIFY, MORE_DELETE)
            else arrayListOf(MORE_COPY, MORE_REPORT)

            val inflater = LayoutInflater.from(v.context)
            val layout = inflater.inflate(com.gh.gamecenter.common.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)
        }

        override fun getItemCount(): Int = dataList.size
    }

    inner class CommentItemViewHolder(val binding: SubItemGameDetailCommentBinding) :
        RecyclerView.ViewHolder(binding.root)

    companion object {
        const val RATING_REPLY_REQUEST = 233
        const val RATING_PATCH_REQUEST = 234
        const val MORE_COPY = "复制"
        const val MORE_MODIFY = "修改"
        const val MORE_DELETE = "删除"
        const val MORE_REPORT = "投诉"
    }
}