package com.gh.gamecenter.forum.search

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.common.util.NewsUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.syncpage.ISyncAdapterHandler
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.CenterImageSpan
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.databinding.ForumSearchContentListBinding
import com.gh.gamecenter.forum.home.ForumArticleAskItemViewHolder
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.entity.AnswerEntity
import com.gh.gamecenter.qa.entity.Questions
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailActivity

class ForumContentSearchListAdapter(
    context: Context,
    val mListViewModel: ForumContentSearchListViewModel,
    val mEntrance: String
) : ListAdapter<AnswerEntity>(context), ISyncAdapterHandler {

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

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) return ItemViewType.ITEM_FOOTER
        return ItemViewType.ITEM_BODY
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_FOOTER -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
            else -> {
                if (mEntrance == "论坛首页+(搜索)") {
                    ForumArticleAskItemViewHolder(
                        CommunityAnswerItemBinding.bind(
                            mLayoutInflater.inflate(
                                R.layout.community_answer_item,
                                parent,
                                false
                            )
                        )
                    )
                } else {
                    ForumSearchContentListViewHolder(
                        ForumSearchContentListBinding.bind(
                            mLayoutInflater.inflate(
                                R.layout.forum_search_content_list,
                                parent,
                                false
                            )
                        )
                    )
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return if (mEntityList.isNotEmpty()) mEntityList.size + FOOTER_ITEM_COUNT else 0
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (getItemViewType(position)) {
            ItemViewType.ITEM_BODY -> {
                val answer = mEntityList[position]
                val questions = Questions()
                questions.id = answer.id ?: ""
                questions.title = answer.articleTitle
                questions.answerCount = answer.count.answer
                answer.questions = questions

                if (mEntrance == "论坛首页+(搜索)") {
                    val answerViewHolder = holder as ForumArticleAskItemViewHolder
                    answerViewHolder.bindForumAnswerItem(answer, mEntrance, "")
                    if (answer.type == "question") {
                        answerViewHolder.binding.content.visibility = View.GONE
                        val title = answer.questions.title ?: ""
                        val spannableStringBuilder = SpannableStringBuilder("  ")
                        spannableStringBuilder.setSpan(
                            CenterImageSpan(
                                mContext,
                                R.drawable.ic_ask_label
                            ), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        spannableStringBuilder.append(title.fromHtml())
                        answerViewHolder.binding.title.text = spannableStringBuilder
                    } else {
                        answerViewHolder.binding.content.visibility = View.VISIBLE
                        //若文章内有图片和视频,标题后增加‘有视频’标签 issues-1052
                        if (answer.getPassVideos().isNotEmpty() && answer.images.isNotEmpty()) {
                            val videoSpan =
                                SpanBuilder("  ").image(1, "  ".length, R.drawable.ic_article_video_label).build()
                            answerViewHolder.binding.title.text = SpannableStringBuilder()
                                .append(answer.questions.title?.fromHtml())
                                .append(videoSpan)
                        } else {
                            answerViewHolder.binding.title.text = answer.questions.title?.fromHtml()
                        }
                    }
                    answerViewHolder.binding.content.text = answer.brief?.fromHtml()
                    answerViewHolder.itemView.setOnClickListener {
                        val entrance = BaseActivity.mergeEntranceAndPath(mEntrance, "")
                        val bbsType = if (answer.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"
                        when (answer.type) {
                            "community_article" -> {
                                NewLogUtils.logForumSearchResultClick(
                                    "内容tab",
                                    answer.bbs.id,
                                    bbsType,
                                    answer.id ?: "",
                                    "帖子",
                                    answer.user.id ?: "",
                                    mListViewModel.searchKey,
                                    position + 1
                                )
                                MtaHelper.onEvent(
                                    holder.getEventId(entrance),
                                    holder.getKey(entrance),
                                    "${answer.articleTitle}（${answer.id}）"
                                )
                                mContext.startActivity(
                                    ArticleDetailActivity.getIntent(
                                        mContext,
                                        CommunityEntity(answer.bbs.id),
                                        answer.id!!,
                                        mEntrance,
                                        ""
                                    )
                                )
                            }
                            "video" -> {
                                NewLogUtils.logForumSearchResultClick(
                                    "内容tab",
                                    answer.bbs.id,
                                    bbsType,
                                    answer.id ?: "",
                                    "视频帖",
                                    answer.user.id ?: "",
                                    mListViewModel.searchKey,
                                    position + 1
                                )
                                MtaHelper.onEvent(
                                    holder.getEventId(entrance),
                                    holder.getKey(entrance),
                                    "${answer.articleTitle}（${answer.id}）"
                                )
                                mContext.startActivity(
                                    ForumVideoDetailActivity.getIntent(
                                        mContext,
                                        answer.id ?: "",
                                        answer.bbs.id
                                    )
                                )
                            }
                            else -> {
                                NewLogUtils.logForumSearchResultClick(
                                    "内容tab",
                                    answer.bbs.id,
                                    bbsType,
                                    answer.id ?: "",
                                    "提问帖",
                                    answer.user.id ?: "",
                                    mListViewModel.searchKey,
                                    position + 1
                                )
                                MtaHelper.onEvent(
                                    holder.getEventId(entrance),
                                    holder.getKey(entrance),
                                    "${answer.articleTitle}（${answer.id}）"
                                )
                                mContext.startActivity(
                                    NewQuestionDetailActivity.getIntent(
                                        mContext,
                                        answer.id ?: "",
                                        mEntrance,
                                        ""
                                    )
                                )
                            }
                        }
                    }
                } else {
                    val forumSearchHolder = holder as ForumSearchContentListViewHolder
                    if (answer.type == "video") {
                        forumSearchHolder.binding.run {
                            normalContainer.visibility = View.GONE
                            includedAnswerItem.root.visibility = View.VISIBLE

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

                            val answerViewHolder = ForumArticleAskItemViewHolder(includedAnswerItem)
                            answerViewHolder.bindForumAnswerItem(answer, mEntrance, "")
                            answerViewHolder.itemView.setOnClickListener {
                                mContext.startActivity(
                                    ForumVideoDetailActivity.getIntent(
                                        mContext,
                                        answer.id ?: "",
                                        answer.bbs.id
                                    )
                                )
                            }
                        }
                    } else {
                        forumSearchHolder.binding.includedAnswerItem.root.visibility = View.GONE
                        forumSearchHolder.binding.normalContainer.visibility = View.VISIBLE

                        forumSearchHolder.binding.run {
                            playIv.goneIf(answer.getPassVideos().isEmpty())
                            durationTv.goneIf(answer.getPassVideos().isEmpty())
                            durationTv.text =
                                if (answer.getPassVideos().isNotEmpty()) answer.getPassVideos()[0].duration else "00:00"
                            durationTv.background = GradientDrawable().apply {
                                setColor(R.color.black_alpha_60.toColor(mContext))
                                cornerRadius = 2F.dip2px().toFloat()
                            }
                            countTv.text = "${answer.count.comment}评论 · ${answer.count.vote}点赞"
                            timeTv.text = TimeUtils.getFormatTime(answer.time ?: 0, "yyyy-MM-dd")
                        }
                        if (answer.type == "question") {
                            forumSearchHolder.binding.countTv.text = "${answer.count.answer + answer.count.reply}评论"
                            forumSearchHolder.binding.contentTv.visibility = View.GONE
                            val title = answer.questions.title ?: ""
                            val spannableStringBuilder = SpannableStringBuilder("  ")
                            spannableStringBuilder.setSpan(
                                CenterImageSpan(
                                    mContext,
                                    R.drawable.ic_ask_label
                                ), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                            )
                            spannableStringBuilder.append(title.fromHtml())
                            forumSearchHolder.binding.titleTv.text = spannableStringBuilder
                        } else {
                            forumSearchHolder.binding.contentTv.visibility = View.VISIBLE
                            forumSearchHolder.binding.titleTv.text = answer.questions.title?.fromHtml()
                        }
                        when {
                            answer.getPassVideos().isNotEmpty() -> {
                                val poster = answer.getPassVideos()[0].poster
                                ImageUtils.display(forumSearchHolder.binding.image, poster, false)
                                forumSearchHolder.binding.image.visibility = View.VISIBLE
                            }
                            answer.images.isNotEmpty() -> {
                                forumSearchHolder.binding.image.visibility = View.VISIBLE
                                ImageUtils.display(forumSearchHolder.binding.image, answer.images[0], false)
                            }
                            else -> {
                                forumSearchHolder.binding.image.visibility = View.GONE
                            }
                        }

                        forumSearchHolder.binding.contentTv.text = answer.brief?.fromHtml()
                        forumSearchHolder.itemView.setOnClickListener {
                            val bbsType = if (answer.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"
                            when (answer.type) {
                                "community_article" -> {
                                    NewLogUtils.logForumSearchResultClick(
                                        "",
                                        answer.bbs.id,
                                        bbsType,
                                        answer.id ?: "",
                                        "帖子",
                                        answer.user.id ?: "",
                                        mListViewModel.searchKey,
                                        position + 1
                                    )
                                    mContext.startActivity(
                                        ArticleDetailActivity.getIntent(
                                            mContext,
                                            CommunityEntity(answer.bbs.id),
                                            answer.id!!,
                                            mEntrance,
                                            ""
                                        )
                                    )
                                }
                                "video" -> {
                                    NewLogUtils.logForumSearchResultClick(
                                        "",
                                        answer.bbs.id,
                                        bbsType,
                                        answer.id ?: "",
                                        "视频帖",
                                        answer.user.id ?: "",
                                        mListViewModel.searchKey,
                                        position + 1
                                    )
                                    mContext.startActivity(
                                        ForumVideoDetailActivity.getIntent(
                                            mContext,
                                            answer.id ?: "",
                                            answer.bbs.id
                                        )
                                    )
                                }
                                else -> {
                                    NewLogUtils.logForumSearchResultClick(
                                        "",
                                        answer.bbs.id,
                                        bbsType,
                                        answer.id ?: "",
                                        "提问帖",
                                        answer.user.id ?: "",
                                        mListViewModel.searchKey,
                                        position + 1
                                    )
                                    mContext.startActivity(
                                        NewQuestionDetailActivity.getIntent(
                                            mContext,
                                            answer.id ?: "",
                                            mEntrance,
                                            ""
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
            ItemViewType.ITEM_FOOTER -> {
                val footerViewHolder = holder as FooterViewHolder
                footerViewHolder.initItemPadding()
                footerViewHolder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver)
                footerViewHolder.hint.textSize = 12f
                footerViewHolder.hint.setTextColor(ContextCompat.getColor(mContext, R.color.aaaaaa))
            }
        }
    }

    class ForumSearchContentListViewHolder(val binding: ForumSearchContentListBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)

    override fun getSyncData(position: Int): Pair<String, Any>? {
        if (position >= mEntityList.size) return null
        val entity = mEntityList[position]
        return Pair(entity.id ?: "", entity)
    }
}