package com.gh.gamecenter.gamedetail.fuli

import android.content.Context
import android.preference.PreferenceManager
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DataCollectionUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.LogUtils
import com.gh.gamecenter.GameNewsActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameDetailNoticeViewHolder
import com.gh.gamecenter.common.entity.SimpleGameEntity
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.setRootBackgroundColor
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.GameGalleryListBinding
import com.gh.gamecenter.databinding.GamedetailItemAnswerBinding
import com.gh.gamecenter.databinding.GamedetailItemNoticeBinding
import com.gh.gamecenter.feature.entity.ZoneContentEntity
import com.gh.gamecenter.gamedetail.fuli.answer.GameDetailAnswerAdapter
import com.gh.gamecenter.gamedetail.fuli.answer.GameDetailAnswerViewHolder
import com.gh.gamecenter.gamedetail.fuli.tools.GameDetailToolsAdapter
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.gh.gamecenter.newsdetail.NewsDetailActivity
import com.lightgame.adapter.BaseRecyclerAdapter

class FuLiAdapter(
    context: Context,
    private val mFuLiViewModel: FuLiViewModel?,
    private val mEntrance: String
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {
    var itemList: List<ZoneContentEntity>? = null
    private var mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
    private val mAnswerHintKey = "game_detail_answer_hint"

    var answerAdapter: GameDetailAnswerAdapter? = null

    override fun getItemViewType(position: Int): Int {
        // 暂时隐藏 Footer 为了避免产品又要用 FOOTER 来做其它事情暂不删除
//        if (itemCount == position + 1) return FOOTER

        val itemData = itemList!![position]
        if (itemData.notice != null) return NOTICE
        if (itemData.article != null) return ARTICLE
        if (itemData.toolkit != null) return TOOLS
        if (itemData.answer != null) return ANSWER

        return super.getItemViewType(position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View
        return when (viewType) {
            NOTICE -> {
                view = mLayoutInflater.inflate(R.layout.gamedetail_item_notice, parent, false)
                GameDetailNoticeViewHolder(GamedetailItemNoticeBinding.bind(view))
            }
            ARTICLE -> {
                GameNewsGalleryViewHolder(parent.toBinding())
            }
            TOOLS -> {
                GameToolkitGalleryViewHolder(parent.toBinding())
            }
            ANSWER -> {
                view = mLayoutInflater.inflate(R.layout.gamedetail_item_answer, parent, false)
                GameDetailAnswerViewHolder(GamedetailItemAnswerBinding.bind(view))
            }
            FOOTER -> {
                view = mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false)
                FooterViewHolder(view)
            }

            else -> {
                throw IllegalAccessException("Contains unreachable view type.")
            }
        }
    }

    override fun getItemCount(): Int {
        return when {
            itemList.isNullOrEmpty() -> 0
            else -> itemList!!.size
        }
    }


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameDetailNoticeViewHolder -> initNoticeViewHolder(holder.binding, position)
            is GameNewsGalleryViewHolder -> initNewsViewHolder(holder, position)
            is GameToolkitGalleryViewHolder -> initToolsViewHolder(holder, position) // 工具item
            is GameDetailAnswerViewHolder -> initAnswerViewHolder(holder, position)
            is FooterViewHolder -> {
                holder.loading.visibility = View.GONE
                holder.hint.setText(R.string.game_suggestion_hint)
                holder.initItemPadding()
                holder.itemView.setOnClickListener {
                    HelpAndFeedbackBridge.startSuggestionActivity(
                        mContext,
                        SuggestType.GAME,
                        "game",
                        null,
                        SimpleGameEntity(
                            mFuLiViewModel?.game?.id ?: "",
                            mFuLiViewModel?.game?.name ?: "",
                            mFuLiViewModel?.game?.icon ?: ""
                        )
                    )
                    MtaHelper.onEvent("游戏详情_新", "此游戏有问题_点击反馈", mFuLiViewModel?.game?.name)
                }
            }
        }
    }

    private fun initAnswerViewHolder(holder: GameDetailAnswerViewHolder, position: Int) {
        holder.binding.run {

            val isShowAnswerHint = mSharedPreferences.getBoolean(mAnswerHintKey, true)
            if (isShowAnswerHint) {
                answerItemHint.visibility = View.VISIBLE
            }
            holder.binding.root.setRootBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface)
            holder.itemView.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.transparent))
            answerItemList.background = ContextCompat.getDrawable(mContext, com.gh.gamecenter.common.R.drawable.background_shape_white_radius_5)
            answerItemList.layoutManager = LinearLayoutManager(mContext)
            answerAdapter =
                GameDetailAnswerAdapter(mContext, mFuLiViewModel!!, itemList?.get(position)?.answer!!, mEntrance)
            mFuLiViewModel.gameCommunity = itemList?.get(position)?.community
            answerItemList.adapter = answerAdapter
            answerItemList.isNestedScrollingEnabled = false
            answerItemMore.setOnClickListener {
                answerItemHint.visibility = View.GONE
                mSharedPreferences.edit().putBoolean(mAnswerHintKey, false).apply()

                LogUtils.qaAccess("游戏详情-动态-进入问答", mFuLiViewModel.gameCommunity)
                MtaHelper.onEvent(
                    "游戏详情_新",
                    "进入问答",
                    "${mFuLiViewModel.game?.name}+${mFuLiViewModel.gameCommunity?.name}"
                )
                DirectUtils.directToCommunity(mContext, mFuLiViewModel.gameCommunity)
            }
        }
    }

    private fun initNoticeViewHolder(binding: GamedetailItemNoticeBinding, position: Int) {
        val notice = itemList?.get(position)?.notice
        binding.noticeContainer.background = com.gh.gamecenter.common.R.drawable.background_shape_white_radius_5.toDrawable(mContext)
        if (notice != null && notice.isNotEmpty()) {
            val list = ArrayList<String?>()
            for (newsEntity in notice) {
                list.add(newsEntity.title)
            }
            binding.gamedetailItemNotice.startWithList(list)
            binding.gamedetailItemNotice.setOnClickListener {
                val index = binding.gamedetailItemNotice.displayedChild
                NewsDetailActivity.startNewsDetailActivity(
                    mContext, notice[index],
                    StringUtils.buildString(mEntrance, "游戏详情[", mFuLiViewModel?.game?.name, "]:公告")
                )

                MtaHelper.onEvent(
                    "游戏详情_新",
                    "专区_公告",
                    mFuLiViewModel?.game?.name + "+" + binding.gamedetailItemNotice.notices[index]
                )
            }
        } else {
            binding.gamedetailItemNotice.visibility = View.GONE
        }
    }

    private fun initToolsViewHolder(viewHolder: GameToolkitGalleryViewHolder, position: Int) {
        val tools = itemList?.get(position)?.toolkit!!
        viewHolder.binding.galleryRv.isNestedScrollingEnabled = false
        if (viewHolder.binding.galleryRv.adapter == null) {
            viewHolder.binding.galleryRv.apply {
                layoutManager = LinearLayoutManager(mContext)
                val toolkitAdapter = GameDetailToolsAdapter(mContext, mFuLiViewModel?.game?.name, tools)
                toolkitAdapter.setItemColor(com.gh.gamecenter.common.R.color.transparent)
                adapter = toolkitAdapter
            }
        }
        viewHolder.binding.titleTv.text = "游戏工具"
        viewHolder.binding.moreTv.visibility = View.GONE
    }

    private fun initNewsViewHolder(viewHolder: GameNewsGalleryViewHolder, position: Int) {
        viewHolder.binding.galleryRv.isNestedScrollingEnabled = false
        val article = itemList?.get(position)?.article!!
        val mAdapter = viewHolder.binding.galleryRv.adapter
        if (mAdapter == null) {
            viewHolder.binding.galleryRv.apply {
                layoutManager = LinearLayoutManager(mContext)
                val newsAdapter = GameNewsAdapter(mContext, article, mFuLiViewModel, mEntrance)
                adapter = newsAdapter
            }
        } else {
            mAdapter.notifyItemRangeChanged(0, mAdapter.itemCount)
        }
        viewHolder.binding.titleTv.text = "新手攻略"
        viewHolder.binding.moreTv.goneIf(article.size < 3)
        viewHolder.binding.moreTv.setOnClickListener {
            DataCollectionUtils.uploadClick(mContext, "新手攻略-全部", "游戏详情", mFuLiViewModel?.game?.name)

            MtaHelper.onEvent("游戏详情_新", "新手攻略-更多", mFuLiViewModel?.game?.name)
            val intent = GameNewsActivity.getIntent(
                mContext,
                mFuLiViewModel?.game?.name,
                mFuLiViewModel?.game?.id,
                mEntrance + "+(游戏详情[" + mFuLiViewModel?.game?.name + "]:新手攻略-全部)"
            )
            mContext.startActivity(intent)
        }
    }

    companion object {
        const val NOTICE = 1
        const val ARTICLE = 2
        const val TOOLS = 4
        const val ANSWER = 7
        const val FOOTER = 8
    }

    class GameNewsGalleryViewHolder(var binding: GameGalleryListBinding) : RecyclerView.ViewHolder(binding.root)

    class GameToolkitGalleryViewHolder(var binding: GameGalleryListBinding) : RecyclerView.ViewHolder(binding.root)
}