package com.gh.gamecenter.help

import android.content.Context
import android.view.ViewGroup
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.HelpCategoryItemBinding
import com.gh.gamecenter.entity.HelpCategoryEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class HelpCategoryAdapter(
    context: Context,
    private val mCategoryList: List<HelpCategoryEntity>,
    private val mNavigationTitle: String,
    private val clickCallback: (HelpCategoryEntity?) -> Unit,
    private val mViewModel: HelpContainerViewModel
) : BaseRecyclerAdapter<HelpCategoryViewHolder>(context) {

    private val mSelectMap = mutableMapOf<Int, Boolean>()

    init {
        if (mCategoryList.isNotEmpty()) {
            mSelectMap[0] = true
            clickCallback.invoke(mCategoryList[0])
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HelpCategoryViewHolder {
        val view = mLayoutInflater.inflate(R.layout.help_category_item, parent, false)
        return HelpCategoryViewHolder(HelpCategoryItemBinding.bind(view))
    }

    override fun getItemCount(): Int {
        return mCategoryList.size
    }

    override fun onBindViewHolder(holder: HelpCategoryViewHolder, position: Int) {
        val entity = mCategoryList[position]
        holder.binding.content.text = entity.name
        holder.binding.content.setTextColor(
            if (mSelectMap[position] == true) R.color.theme_font.toColor(mContext)
            else R.color.text_title.toColor(mContext)
        )

        holder.binding.icon.goneIf(entity.icon.isEmpty())
        ImageUtils.display(holder.binding.icon, entity.icon)
        holder.itemView.setOnClickListener {
            if (mSelectMap[position] == true) return@setOnClickListener
            if (!mViewModel.qaCollectionId.isNullOrEmpty()) {
                MtaHelper.onEvent("QA", "QA合集点击", "点击" + mNavigationTitle + "+" + entity.name)
            } else {
                MtaHelper.onEvent("意见反馈", "使用帮助点击", "点击" + mNavigationTitle + "+" + entity.name)
            }

            if (mSelectMap[position] == true) {
                clickCallback.invoke(null)
            } else {
                clickCallback.invoke(entity)
            }

            mSelectMap[position] = !(mSelectMap[position] ?: false)

            if (mSelectMap[position] == true) {
                for (mutableEntry in mSelectMap) {
                    if (mutableEntry.key != position) mutableEntry.setValue(false)
                }
            }

            notifyItemRangeChanged(0, itemCount)
        }
    }

}