package com.gh.gamecenter.forum.detail

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.syncpage.ISyncAdapterHandler
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.databinding.ItemForumArticleHeadBinding
import com.gh.gamecenter.forum.home.ForumArticleAskItemViewHolder
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.Questions
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailActivity

class ForumArticleAskListAdapter(
    context: Context,
    val bbsId: String,
    val entrance: String,
    val path: String,
    val viewModel: ForumArticleAskListViewModel,
    val onCheckCallback: (String) -> Unit
) :
    ListAdapter<AnswerEntity>(context), ISyncAdapterHandler {

    private var mDefOrderList = listOf("回复", "发布")
    private var mVideoOrderList = listOf("推荐", "发布")
    private var mFilterPosition = if (path == "视频") 1 else 0

    override fun areItemsTheSame(oldItem: AnswerEntity?, newItem: AnswerEntity?): Boolean {
        return oldItem?.id == newItem?.id
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_HEADER -> {
                ForumArticleHeadViewHolder(parent.toBinding())
            }
            ItemViewType.ITEM_FOOTER -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
            else -> {
                ForumArticleAskItemViewHolder(
                    CommunityAnswerItemBinding.bind(
                        mLayoutInflater.inflate(
                            R.layout.community_answer_item,
                            parent,
                            false
                        )
                    )
                )
            }
        }
    }

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

    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 articlePosition = position - 1
                val answer = mEntityList[position]
                if (answer.type != "answer") {
                    val questions = Questions()
                    questions.id = answer.id ?: ""
                    questions.title = answer.articleTitle
                    questions.description = answer.description
                    questions.answerCount = answer.count.answer
                    answer.questions = questions
                }
                if (path == "精华" && answer.type != "answer" && answer.type != "video") answer.type = "community_article"
                if (path == "问答") answer.type = "question"
                if (path == "视频") answer.type = "video"

                if (answer.bbs.id.isEmpty()) answer.bbs.id = bbsId

                val answerViewHolder = holder as ForumArticleAskItemViewHolder
                val binding = answerViewHolder.binding
                binding.forumNameLl.visibility = View.GONE
                binding.topLine.goneIf(articlePosition == 0)

                val params = binding.includeVoteAndComment.root.layoutParams as LinearLayout.LayoutParams
                params.width = LinearLayout.LayoutParams.MATCH_PARENT
                params.leftMargin = 0
                params.rightMargin = 0
                binding.includeVoteAndComment.root.layoutParams = params

                val tabInfo = "${path}tab"
                answerViewHolder.bindForumAnswerItem(answer, entrance, path, articlePosition)
                answerViewHolder.itemView.setOnClickListener {
                    val entrance = BaseActivity.mergeEntranceAndPath(entrance, path)
                    val userId = answer.user.id ?: ""
                    val contentId = answer.id ?: ""
                    val sequence = articlePosition + 1
                    val bbsType = if (answer.bbs.type == "official_bbs") "综合论坛" else "游戏论坛"
                    when (answer.type) {
                        "community_article" -> {
                            NewLogUtils.logForumDetailFeedContentClick(
                                "click_forum_detail_content",
                                userId,
                                contentId,
                                "帖子",
                                sequence,
                                bbsId,
                                bbsType,
                                tabInfo
                            )
                            MtaHelper.onEvent(
                                holder.getEventId(entrance),
                                holder.getKey(entrance),
                                "${answer.articleTitle}（${answer.id}）"
                            )
                            mContext.startActivity(
                                ArticleDetailActivity.getIntent(
                                    mContext,
                                    CommunityEntity(bbsId),
                                    answer.id!!,
                                    entrance,
                                    path
                                )
                            )
                        }
                        "video" -> {
                            NewLogUtils.logForumDetailFeedContentClick(
                                "click_forum_detail_content",
                                userId,
                                contentId,
                                "视频帖",
                                sequence,
                                bbsId,
                                bbsType,
                                tabInfo
                            )
                            MtaHelper.onEvent(
                                holder.getEventId(entrance),
                                holder.getKey(entrance),
                                "${answer.articleTitle}（${answer.id}）"
                            )
                            mContext.startActivity(ForumVideoDetailActivity.getIntent(mContext, answer.id ?: "", bbsId))
                        }
                        "question" -> {
                            NewLogUtils.logForumDetailFeedContentClick(
                                "click_forum_detail_content",
                                userId,
                                contentId,
                                "提问帖",
                                sequence,
                                bbsId,
                                bbsType,
                                tabInfo
                            )
                            MtaHelper.onEvent(
                                holder.getEventId(entrance),
                                holder.getKey(entrance),
                                "${answer.articleTitle}（${answer.id}）"
                            )
                            mContext.startActivity(
                                NewQuestionDetailActivity.getIntent(
                                    mContext, answer.id
                                        ?: "", entrance, path
                                )
                            )
                        }
                        "answer" -> {
                            NewLogUtils.logForumDetailFeedContentClick(
                                "click_forum_detail_content",
                                userId,
                                contentId,
                                "提问帖评论",
                                sequence,
                                bbsId,
                                bbsType,
                                tabInfo
                            )
                            MtaHelper.onEvent(
                                holder.getEventId(entrance),
                                holder.getKey(entrance),
                                "${answer.articleTitle}（${answer.id}）"
                            )
                            mContext.startActivity(
                                NewQuestionDetailActivity.getCommentIntent(
                                    mContext, answer.questions.id, answer.id
                                        ?: "", entrance, path
                                )
                            )
                        }
                    }
                }
            }
            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))
            }
            ItemViewType.ITEM_HEADER -> {
                if (holder is ForumArticleHeadViewHolder) {
                    val articleListHead = if (path == "全部") {
                        viewModel.selectedSection.name
                    } else path
                    holder.binding.root.setBackgroundColor(R.color.background_white.toColor(mContext))
                    holder.binding.articleListHeadTv.setTextColor(R.color.text_title.toColor(mContext))
                    holder.binding.articleListHeadTv.text = "${articleListHead}列表"

                    if (path != "精华") {
                        holder.binding.orderSfv.run {
                            visibility = View.VISIBLE
                            setContainerBackground(R.drawable.button_round_f5f5f5.toDrawable(mContext))
                            setIndicatorBackground(R.drawable.bg_game_collection_sfv_indicator.toDrawable(mContext))
                            setTextColor(
                                R.color.text_subtitle.toColor(mContext),
                                R.color.text_subtitleDesc.toColor(mContext)
                            )

                            setItemList(if (path == "视频") mVideoOrderList else mDefOrderList, mFilterPosition)
                            setOnCheckedCallback { position ->
                                mFilterPosition = position
                                onCheckCallback.invoke((if (path == "视频") mVideoOrderList else mDefOrderList)[position])
                            }
                        }
                    } else {
                        holder.binding.orderSfv.visibility = View.GONE
                    }
                }
            }
        }
    }

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

    class ForumArticleHeadViewHolder(val binding: ItemForumArticleHeadBinding) : RecyclerView.ViewHolder(binding.root)
}