package com.gh.gamecenter.gamedetail.desc

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
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.base.activity.BaseActivity
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.ItemGameDetailRatingCommentBinding
import com.gh.gamecenter.entity.RatingComment
import com.gh.gamecenter.gamedetail.GameDetailFragment
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 org.greenrobot.eventbus.EventBus
import java.util.regex.Pattern

class DescCommentsAdapter(
    context: Context,
    var mViewModel: DescViewModel,
    private var mEntrance: String,
    private var gameName: String?
) : ListAdapter<RatingComment>(context) {

    var comments = ArrayList<RatingComment>()
    val path = "游戏详情：介绍"

    override fun getItemViewType(position: Int): Int {
        return if (position == comments.size) {
            ItemViewType.ITEM_FOOTER
        } else {
            ItemViewType.ITEM_BODY
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == ItemViewType.ITEM_BODY) {
            GameDetailRatingCommentViewHolder(parent.toBinding())
        } else {
            MoreViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_game_detail_comment_more, parent, false))
        }
    }

    override fun getItemCount(): Int {
        return comments.size + 1
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is GameDetailRatingCommentViewHolder) {
            val commentData = comments[position]
            var isChildLongClick = false
            holder.binding.run {
                ImageUtils.display(userIcon, commentData.user.icon)
                ImageUtils.display(userBadge, commentData.user.auth?.icon)
                userName.text = commentData.user.name
                ratingStart.rating = commentData.star.toFloat()
                val p = Pattern.compile(RatingEditActivity.LABEL_REGEX)
                val m = p.matcher(commentData.content)
                if (m.find()) {
                    val contents =
                        TextHelper.getCommentLabelSpannableStringBuilder(commentData.content, R.color.theme_font)
                    content.setTextWithHighlightedTextWrappedInsideWrapper(text = contents, copyClickedText = true)
                } else {
                    content.setTextWithHighlightedTextWrappedInsideWrapper(
                        text = commentData.content,
                        copyClickedText = true
                    )
                }
                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
                }

                ipRegionTv.goneIf(!(commentData.source != null && commentData.source.region.isNotEmpty()))
                ipRegionTv.text = " · ${commentData.source?.region}"
                when {
                    commentData.isEditContent == null -> {
                        time.setTextColor(ContextCompat.getColor(mContext, 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(mContext, s.length - 10, s.length, R.color.text_subtitle).build()
                        } else {
                            NewsUtils.getFormattedTime(commentData.time)
                        }
                    }
                    commentData.isEditContent!! -> {
                        time.setTextColor(ContextCompat.getColor(mContext, R.color.text_F56614))
                        time.text = if (commentData.ignore) {
                            "${NewsUtils.getFormattedTime(commentData.time)} 保护期间修改评论 >"
                        } else {
                            "${NewsUtils.getFormattedTime(commentData.time)} 已修改 >"
                        }
                    }
                    else -> {
                        time.setTextColor(ContextCompat.getColor(mContext, R.color.text_F56614))
                        time.text = if (commentData.ignore) {
                            "${NewsUtils.getFormattedTime(commentData.time)} 保护期间修改评论"
                        } else {
                            "${NewsUtils.getFormattedTime(commentData.time)} 已修改"
                        }

                    }
                }

                sdvUserBadge.setOnClickListener {
                    DialogUtils.showViewBadgeDialog(mContext, commentData.user.badge, object : ConfirmListener {
                        override fun onConfirm() {
                            MtaHelper.onEvent(
                                "进入徽章墙_用户记录",
                                "游戏详情-玩家评论",
                                "${commentData.user.name}（${commentData.user.id}）"
                            )
                            MtaHelper.onEvent("徽章中心", "进入徽章中心", "游戏详情-玩家评论")
                            DirectUtils.directToBadgeWall(
                                mContext,
                                commentData.user.id,
                                commentData.user.name,
                                commentData.user.icon
                            )
                        }
                    })
                }
                userIcon.setOnClickListener {
                    DirectUtils.directToHomeActivity(mContext, commentData.user.id, mEntrance, "游戏详情-玩家评论")
                    MtaHelper.onEvent("游戏详情_新", "玩家评论_点击用户头像", mViewModel.game?.name)
                    NewLogUtils.logGameDetailCommentClick(
                        mViewModel.game?.name ?: "",
                        mViewModel.game?.id ?: "",
                        "个人主页"
                    )
                }
                userName.setOnClickListener {
                    userIcon.performClick()
                    MtaHelper.onEvent("游戏详情_新", "玩家评论_点击用户名字", mViewModel.game?.name)
                }

                tvBadgeName.setOnClickListener { sdvUserBadge.performClick() }

                commentItem.setOnClickListener {
                    if (isChildLongClick) {
                        isChildLongClick = false
                        return@setOnClickListener
                    }
                    val intent = RatingReplyActivity.getIntent(
                        mContext,
                        mViewModel.game?.id ?: "",
                        commentData.id,
                        mEntrance,
                        path
                    )
                    SyncDataBetweenPageHelper.startActivityForResult(mContext, intent, RATING_REPLY_REQUEST, position)
                    MtaHelper.onEvent("游戏详情_新", "玩家评论_点击评论", mViewModel.game?.name)
                    NewLogUtils.logGameDetailCommentClick(
                        mViewModel.game?.name ?: "",
                        mViewModel.game?.id ?: "",
                        "评论内容"
                    )
                }
                content.setExpandCallback {
                    MtaHelper.onEvent("游戏详情_新", "玩家评论_点击全文", mViewModel.game?.name)
                }

                content.setOnLongClickListener(View.OnLongClickListener {
                    isChildLongClick = true
                    commentData.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "").copyTextAndToast()
                    return@OnLongClickListener true
                })
                more.setOnClickListener {
                    showMorePopWindow(it, commentData.user.id == UserManager.getInstance().userId) { text ->
                        when (text) {
                            "复制" -> {
                                commentData.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "")
                                    .copyTextAndToast()
                                MtaHelper.onEvent("游戏详情_新", "玩家评论_复制", mViewModel.game?.name)
                            }
                            "修改" -> {
                                MtaHelper.onEvent("游戏详情_新", "玩家评论_修改", mViewModel.game?.name)
                                val intent = RatingEditActivity.getPatchIntent(mContext, mViewModel.game!!, commentData)
                                SyncDataBetweenPageHelper.startActivityForResult(
                                    mContext,
                                    intent,
                                    RATING_PATCH_REQUEST,
                                    position
                                )
                            }
                            "投诉" -> {
                                MtaHelper.onEvent("游戏详情_新", "玩家评论_投诉", mViewModel.game?.name)
                                mContext.ifLogin(BaseActivity.mergeEntranceAndPath(mEntrance, path)) {
                                    DialogUtils.showReportReasonDialog(
                                        mContext,
                                        Constants.REPORT_LIST.toList() as java.util.ArrayList<String>
                                    ) { reason, desc ->
                                        SimpleRequestHelper.reportGameComment(
                                            mViewModel.game?.id ?: "",
                                            commentData.id,
                                            if (reason != "其他原因") reason else desc
                                        )
                                    }
                                }
                            }
                            "删除" -> {
                                DialogHelper.showDeleteGameCommentDialog(
                                    mContext,
                                    R.string.delete_game_comment.toResString()
                                ) {
                                    SimpleRequestHelper.deleteGameComment(
                                        mViewModel.game?.id ?: "",
                                        commentData.id
                                    ) {
                                        // 删除列表中的评论(如果当前列表有的话)
                                        val index = comments.indexOfFirst { item ->
                                            item.id == commentData.id
                                        }
                                        if (index != -1) {
                                            comments.removeAt(index)
                                            notifyItemRemoved(index)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                time.setOnClickListener {
                    if (commentData.isEditContent == null && commentData.ignore) {
                        MtaHelper.onEvent("游戏详情_新", "玩家评论-评论说明", mViewModel.game?.name)
                        DialogUtils.showStopServerExplanationDialog(
                            mContext,
                            if (mViewModel.game?.commentDescription?.isNotEmpty() == true)
                                mViewModel.game?.commentDescription else mContext.getString(R.string.rating_protection),
                            mViewModel.game?.name
                                ?: ""
                        )
                    } else if (commentData.isEditContent == true) {
                        MtaHelper.onEvent("游戏详情_新", "玩家评论-点击时间", mViewModel.game?.name)
                        val intent = CommentLogsActivity.getIntent(mContext, mViewModel.game!!.id, commentData.id)
                        mContext.startActivity(intent)
                    }
                }
            }
        } else if (holder is MoreViewHolder) {
            holder.itemView.setOnClickListener {
                EventBus.getDefault().post(EBReuse(GameDetailFragment.SKIP_RATING))
                MtaHelper.onEvent("游戏详情_新", "玩家评论_查看全部评论", gameName)
                NewLogUtils.logGameDetailCommentClick(mViewModel.game?.name ?: "", mViewModel.game?.id ?: "", "查看全部评论")
            }
        }
    }

    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)
    }

    class MoreViewHolder(var view: View) : RecyclerView.ViewHolder(view)

    class GameDetailRatingCommentViewHolder(var binding: ItemGameDetailRatingCommentBinding) :
        RecyclerView.ViewHolder(binding.root)

    companion object {
        const val RATING_REPLY_REQUEST = 233
        const val RATING_PATCH_REQUEST = 234
    }
}