package com.gh.gamecenter.gamedetail.rating

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.SparseBooleanArray
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DialogUtils
import com.gh.common.util.NewLogUtils
import com.gh.common.util.OnSyncCallBack
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.RatingCommentItemBinding
import com.gh.gamecenter.databinding.RatingItemBinding
import com.gh.gamecenter.entity.Rating
import com.gh.gamecenter.entity.RatingComment
import com.gh.gamecenter.entity.Star
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity
import com.lightgame.utils.Utils

class RatingAdapter(
    context: Context,
    private val mListViewModel: RatingViewModel,
    private var mDirectComment: Boolean,
    private val mEntrance: String
) : ListAdapter<RatingComment>(context) {

    var ratingData: Rating? = null
    val path = if (mListViewModel.type == RatingViewModel.RatingType.RATING) "游戏详情：评分" else "折叠评论"

    val headServiceCommentPosition = -1
    val headMyCommentPosition = -2
    private var mExpandSparseBooleanArray = SparseBooleanArray()

    public override fun setListData(updateData: MutableList<RatingComment>) {
        var oldSize = TOP_ITEM_COUNT
        if (mEntityList != null && mEntityList.size > 0) {
            oldSize += mEntityList.size
        }
        mEntityList = ArrayList<RatingComment>(updateData)
        if (oldSize == 0 || oldSize > updateData.size || mListViewModel.getLinkPageSize() == 2 /* 第一页 */) {
            notifyDataSetChanged()
        } else {
            notifyItemRangeInserted(oldSize, updateData.size + TOP_ITEM_COUNT - oldSize)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (mListViewModel.type == RatingViewModel.RatingType.RATING) {
            when (position) {
                itemCount - 1 -> ItemViewType.ITEM_FOOTER
                0 -> ItemViewType.ITEM_HEADER
                else -> ItemViewType.ITEM_BODY
            }
        } else {
            when (position) {
                itemCount - 1 -> ItemViewType.ITEM_FOOTER
                else -> ItemViewType.ITEM_BODY
            }
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        val view: View
        return when (viewType) {
            ItemViewType.ITEM_HEADER -> {
                view = mLayoutInflater.inflate(R.layout.rating_item, parent, false)
                RatingItemViewHolder(RatingItemBinding.bind(view))
            }
            ItemViewType.ITEM_FOOTER -> {
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
                FooterViewHolder(view)
            }
            else -> {
                view = mLayoutInflater.inflate(R.layout.rating_comment_item, parent, false)
                RatingCommentItemViewHolder(RatingCommentItemBinding.bind(view))
            }
        }
    }

    override fun getItemCount(): Int {
        var index = 0
        if (mListViewModel.type == RatingViewModel.RatingType.RATING) {
            if (ratingData != null) index++
            if (mEntityList != null && ratingData != null) index += mEntityList.size
        } else {
            if (mEntityList != null) index += mEntityList.size
        }
        if (index > 0) index++
        return index
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is RatingItemViewHolder -> bindRatingItem(holder)
            is RatingCommentItemViewHolder -> {
                if (mListViewModel.type == RatingViewModel.RatingType.RATING) {
                    (holder.itemView.layoutParams as ViewGroup.MarginLayoutParams).apply {
                        topMargin = if (position == 1) 0 else 12F.dip2px()
                        holder.itemView.layoutParams = this
                    }
                    initRatingComment(holder, mEntityList[position - 1], position - 1)
                } else {
                    (holder.itemView.layoutParams as ViewGroup.MarginLayoutParams).apply {
                        topMargin = 12F.dip2px()
                        holder.itemView.layoutParams = this
                    }
                    initRatingComment(holder, mEntityList[position], position)
                }
            }
            is FooterViewHolder -> {
                if (mIsOver && mListViewModel.type == RatingViewModel.RatingType.RATING && ratingData != null && ratingData!!.foldCount > 0) {
                    holder.initItemPadding()
                    val params = holder.itemView.layoutParams as RecyclerView.LayoutParams
                    params.height = 44F.dip2px()
                    holder.itemView.layoutParams = params
                    holder.itemView.background =
                        ContextCompat.getDrawable(mContext, R.drawable.background_shape_white_radius_5)
                    holder.loading.visibility = View.GONE
                    holder.hint.text = "查看折叠评价>"
                    holder.hint.textSize = 12F
                    holder.hint.setTextColor(ContextCompat.getColor(mContext, R.color.theme_font))
                    holder.itemView.setOnClickListener {
                        MtaHelper.onEvent("游戏详情_新", "评论Tab-查看折叠评论", mListViewModel.game.name)
                        val intent = RatingFoldActivity.getIntent(mContext, mListViewModel.game, mEntrance, path)
                        (mContext as Activity).startActivityForResult(intent, RatingFragment.RATING_FOLD_REQUEST)
                    }
                } else {
                    holder.itemView.background = null
                    holder.hint.setTextColor(ContextCompat.getColor(mContext, R.color.text_B3B3B3))
                    holder.initFooterViewHolder(mListViewModel, mIsLoading, isNetworkError, mIsOver)
                }
            }
        }
    }

    private fun bindRatingItem(holder: RatingItemViewHolder) {
        holder.binding.run {
            ratingData?.let {
                it.serviceComment?.isServiceComment = true
                notEnoughCommentTips.goneIf(it.commentCount > 3)
                scoreProgressContainer.goneIf(it.commentCount <= 3)
                scoreTv.textSize = if (it.commentCount > 3) 18f else 8f
                scoreTv.text =
                    if (it.commentCount > 3) (if (it.star.average == 10.0f) "10" else it.star.average.toString()) else "评分过少"
                setRatingScore(ratingScoreFive, it.star)
                setRatingScore(ratingScoreFour, it.star)
                setRatingScore(ratingScoreThree, it.star)
                setRatingScore(ratingScoreTwo, it.star)
                setRatingScore(ratingScoreOne, it.star)
                actionButtonContainer.goneIf(it.me.isCommented)
                stopServerContainer.goneIf(!it.ignoreComment)
                serviceCommentContainer.goneIf(it.serviceComment == null)
                myCommentContainer.goneIf(it.myComment == null)
                allComment.goneIf(!it.isExistComment)
            }


            if (ratingData?.serviceComment != null) {
                includeServiceComment.commentItem.visibility = View.VISIBLE
                initRatingComment(
                    RatingCommentItemViewHolder(includeServiceComment),
                    ratingData?.serviceComment!!,
                    headServiceCommentPosition
                )
            }

            if (ratingData?.myComment != null) {
                includeMyComment.commentItem.visibility = View.VISIBLE
                initRatingComment(
                    RatingCommentItemViewHolder(includeMyComment),
                    ratingData?.myComment!!,
                    headMyCommentPosition
                )
            }

            ratingEditBtn.setOnClickListener {
                mContext.showRegulationTestDialogIfNeeded {
                    MtaHelper.onEvent("游戏详情_新", "评论Tab_点击我来评论", mListViewModel.game.name)
                    MtaHelper.onEvent("发表评论", "进入", "游戏详情_${mListViewModel.game.name}")
                    mListViewModel.game.run {
                        NewLogUtils.logCommentTabOrCommentDetailClick(
                            "click_game_detail_comment",
                            id,
                            gameType
                        )
                        NewLogUtils.logGameDetailTabClick(
                            "view_game_comment",
                            "我来评论按钮",
                            id,
                            gameType,
                            bbsId,
                        )
                    }

                    skipRatingEdit(0.0F, "游戏详情-评论-[我来评论]")
                }
            }
            ratingAmwayBtn.setOnClickListener {
                mContext.showRegulationTestDialogIfNeeded {
                    MtaHelper.onEvent("游戏详情_新", "评论Tab_点击我要安利", mListViewModel.game.name)
                    MtaHelper.onEvent("发表评论", "我要安利", mListViewModel.game.name)
                    mListViewModel.game.run {
                        NewLogUtils.logCommentTabOrCommentDetailClick(
                            "click_game_detail_for_you",
                            mListViewModel.game.id,
                            mListViewModel.game.gameType
                        )
                        NewLogUtils.logGameDetailTabClick(
                            "view_game_comment",
                            "我要安利按钮",
                            id,
                            gameType,
                            bbsId,
                        )
                    }
                    skipRatingEdit(0.0F, "游戏详情-评论-[我要安利]", fromAmway = true, isSkipSuccessPage = false)
                }
            }
            stopServerIv.setOnClickListener {
                DialogUtils.showStopServerExplanationDialog(
                    mContext,
                    ratingData?.commentDescription,
                    mListViewModel.game.name
                )
            }

            sort.setOnClickListener {
                holder.showPopWindow(sort, RatingItemViewHolder.POP_SORT, sort.text.toString()) { text ->
                    if (text != sort.text) {
                        sort.text = text
                        mListViewModel.filterList(text, filter.text.toString())
                        MtaHelper.onEvent("游戏详情_新", "评论Tab-排序-$text", mListViewModel.game.name)
                    }
                }
            }

            filter.setOnClickListener {
                holder.showPopWindow(filter, RatingItemViewHolder.POP_FILTER, filter.text.toString()) { text ->
                    if (text != filter.text) {
                        filter.text = text
                        mListViewModel.filterList(sort.text.toString(), text)
                        MtaHelper.onEvent("游戏详情_新", "评论Tab-筛选-$text", mListViewModel.game.name)
                    }
                }
            }
        }
    }

    private fun setRatingScore(progress: ProgressBar, star: Star) {
        if (star.hits <= 3) {
            progress.progress = 0
            return
        }
        var targetScore = 0
        when (progress.id) {
            R.id.rating_score_five -> targetScore = star.five / 10
            R.id.rating_score_four -> targetScore = star.four / 8
            R.id.rating_score_three -> targetScore = star.three / 6
            R.id.rating_score_two -> targetScore = star.two / 4
            R.id.rating_score_one -> targetScore = star.one / 2
        }

        var f = (targetScore / star.hits.toFloat()) * 100
        if (0 < f && f < 1) {
            f = 1F
        }
        progress.progress = f.toInt()
    }

    private fun initRatingComment(holder: RatingCommentItemViewHolder, commentData: RatingComment, dataPosition: Int) {
        var isChildLongClick = false
        val maxDesLines = if (mExpandSparseBooleanArray.get(holder.adapterPosition)) Int.MAX_VALUE else 4
        holder.binding.content.setExpandMaxLines(maxDesLines)
        holder.binding.content.setIsExpanded(Int.MAX_VALUE == maxDesLines)
        holder.binding.replyContent.setTextColor(R.color.text_subtitle.toColor(mContext))
        holder.binding.content.setTextColor(R.color.text_subtitle.toColor(mContext))
        holder.setContent(commentData, mListViewModel.game, dataPosition, mEntrance, path) {
            deleteMyComment(commentData.id)
        }
        holder.binding.root.background = ContextCompat.getDrawable(mContext, R.drawable.background_shape_white_radius_8)
        holder.binding.vote.isChecked = commentData.me.isVoted
        holder.binding.run {
            commentItem.setOnClickListener {
                if (isChildLongClick) {
                    isChildLongClick = false
                    return@setOnClickListener
                }
                skipRatingReply(false, commentData, dataPosition)
                if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_点击评论", mListViewModel.game.name)
                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "进入评论详情", mListViewModel.game.name)
                mListViewModel.game.run {
                    NewLogUtils.logCommentTabOrCommentDetailClick(
                        "click_allcomment_comment",
                        id,
                        gameType
                    )
                    NewLogUtils.logViewGameCommentDetail(
                        id,
                        gameType,
                        bbsId,
                    )
                }
            }
            content.setExpandCallback {
                mExpandSparseBooleanArray.put(holder.adapterPosition, true)
                if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_点击全文", mListViewModel.game.name)
                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "查看全文", mListViewModel.game.name)
            }
            content.setOnLongClickListener(View.OnLongClickListener {
                isChildLongClick = true
                commentData.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "").copyTextAndToast()
                return@OnLongClickListener true
            })
            replyContent.setOnLongClickListener(View.OnLongClickListener {
                isChildLongClick = true
                commentData.replyData?.content?.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "")
                    ?.copyTextAndToast()
                return@OnLongClickListener true
            })
            replyMore.setOnClickListener {
                skipRatingReply(false, commentData, dataPosition)
                if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_查看更多回复", mListViewModel.game.name)
                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "查看更多回复", mListViewModel.game.name)
                NewLogUtils.logCommentTabOrCommentDetailClick(
                    "click_allcomment_view_more_answer",
                    mListViewModel.game.id,
                    mListViewModel.game.gameType
                )
            }
            comment.setOnClickListener {
                skipRatingReply(false, commentData, dataPosition)
                if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_回复", mListViewModel.game.name)
                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "回复", mListViewModel.game.name)
            }
            vote.setOnClickListener {
                mContext.ifLogin("游戏详情-评论-点赞评论") {
                    debounceActionWithInterval(vote.id, 1000L) {
                        if (!vote.isChecked) {
                            mListViewModel.voteComment(commentData.id, callback = {
                                vote.text = (commentData.vote + 1).toString()
                                vote.isChecked = true
                                commentData.vote = commentData.vote + 1
                                commentData.me.isVoted = true
                                if (path == "游戏详情：评分") MtaHelper.onEvent("游戏详情_新", "评论Tab_点赞", mListViewModel.game.name)
                                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "点赞", mListViewModel.game.name)
                                NewLogUtils.logCommentTabOrCommentDetailClick(
                                    "click_allcomment_like",
                                    mListViewModel.game.id,
                                    mListViewModel.game.gameType
                                )
                            })
                        } else {
                            mListViewModel.unVoteComment(commentData.id, callback = {
                                val count = commentData.vote - 1
                                vote.text = if (count == 0) "" else count.toString()
                                vote.isChecked = false
                                commentData.vote = count
                                commentData.me.isVoted = false
                                if (path == "游戏详情：评分") MtaHelper.onEvent(
                                    "游戏详情_新",
                                    "评论Tab_取消点赞",
                                    mListViewModel.game.name
                                )
                                if (path == "折叠评论") MtaHelper.onEvent("折叠评论", "取消点赞", mListViewModel.game.name)
                            })
                        }
                    }
                }
            }
        }
    }

    private fun skipRatingReply(isOpenKeyboard: Boolean, commentData: RatingComment, dataPosition: Int) {
        val intent = if (isOpenKeyboard) {
            RatingReplyActivity.getOpenKeyboardIntent(mContext, mListViewModel.game, commentData, mEntrance, path)
        } else {
            RatingReplyActivity.getIntent(mContext, mListViewModel.game.id, commentData.id, mEntrance, path)
        }
        SyncDataBetweenPageHelper.startActivityForResult(
            mContext,
            intent,
            RatingFragment.RATING_REPLAY_REQUEST,
            dataPosition
        )
    }

    private fun skipRatingEdit(
        starCount: Float,
        entrance: String,
        fromAmway: Boolean = false,
        isSkipSuccessPage: Boolean = false
    ) {

        debugOnly { mDirectComment = true }

        mContext.ifLogin(entrance) {
            if (mContext is Activity) {
                val installPackageName = mListViewModel.canUserCommentThisGame()
                if (mDirectComment || !installPackageName.isNullOrEmpty()) {
                    val intent =
                        RatingEditActivity.getIntent(
                            mContext,
                            mListViewModel.game,
                            starCount,
                            installPackageName,
                            fromAmway,
                            isSkipSuccessPage
                        )
                    (mContext as Activity).startActivityForResult(intent, RatingFragment.RATING_EDIT_REQUEST)
                } else {
                    Utils.toast(mContext, "安装游戏后才能评论哦")
                }
            }
        }
    }

    fun handleSyncData(requestCode: Int, intent: Intent?) {
        SyncDataBetweenPageHelper.resultHandle(intent, object : OnSyncCallBack<RatingComment> {
            override fun onData(dataPosition: Int): RatingComment? {
                val ratingComment = when {
                    dataPosition == headServiceCommentPosition -> {
                        ratingData?.serviceComment
                    }
                    dataPosition == headMyCommentPosition -> {
                        ratingData?.myComment
                    }
                    mEntityList.size == 0 -> {
                        null
                    }
                    else -> {
                        mEntityList.safelyGetInRelease(dataPosition)
                    }
                }
                if (requestCode == RatingFragment.RATING_PATCH_REQUEST) {
                    ratingComment?.ignore = mListViewModel.game.ignoreComment
                }
                return ratingComment
            }

            override fun onNotify(dataPosition: Int) {
                if (mListViewModel.type == RatingViewModel.RatingType.RATING) {
                    if (dataPosition == headServiceCommentPosition || dataPosition == headMyCommentPosition) {
                        notifyItemChanged(0)
                    } else notifyItemChanged(dataPosition + 1)
                } else {
                    notifyItemChanged(dataPosition)
                }
            }
        })
    }

    fun deleteMyComment(commentId: String, isUpdateFoldFooter: Boolean = false) {
        // 删除头部的我的评论
        ratingData?.myComment = null
        ratingData?.me?.isCommented = false
        notifyItemChanged(0)

        // 删除列表中的评论(如果当前列表有的话)
        val index = mEntityList.indexOfFirst { item ->
            item.id == commentId
        }
        if (index != -1) {
            mEntityList.removeAt(index)
            notifyItemRemoved(index + 1)
        }

        if (isUpdateFoldFooter) {
            ratingData?.run {
                if (foldCount > 0) {
                    foldCount--
                }
            }
            notifyItemChanged(itemCount - 1)
        }

        if (mListViewModel.type == RatingViewModel.RatingType.FOLD_RATING) {
            val intent = Intent().apply {
                putExtra(EntranceConsts.KEY_COMMENT_ID, commentId)
            }
            (mContext as Activity).setResult(RatingFragment.RATING_DELETE_RESULT, intent)
        }
    }
}