package com.gh.gamecenter.discovery.interestedgame

import android.content.Context
import android.view.ViewGroup
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.databinding.InterestedGameSubTagItemBinding
import com.gh.gamecenter.entity.InterestedGameEntity.TypeTag.Tag
import com.lightgame.adapter.BaseRecyclerAdapter

class InterestGameSubTagAdapter(
    context: Context,
    private var mList: List<Tag>,
    private val mViewModel: InterestedGameViewModel,
    private val mTagClickCallback: EmptyCallback
) : BaseRecyclerAdapter<InterestGameSubTagAdapter.InterestGameSubTagItemViewHolder>(context) {

    private var mCountAndKey: Pair<Int, String>? = null

    init {
        var dataIds = ""
        mList.forEach {
            dataIds += it.id
        }
        if (dataIds.isNotEmpty()) mCountAndKey = Pair(mList.size, dataIds)
    }

    override fun getItemCount() = mList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        InterestGameSubTagItemViewHolder(parent.toBinding())

    override fun onBindViewHolder(holder: InterestGameSubTagItemViewHolder, position: Int) {
        holder.binding.tagTv.run {
            val tag = mList[position]
            text = tag.name
            isChecked = mViewModel.getTempSelectedTagList().any { it.id == tag.id }
            setOnClickListener {
                isChecked = !isChecked
                mViewModel.run {
                    isModify = true
                    if (isChecked) {
                        increaseSelectedCount()
                        addTempTag(tag)
                    } else {
                        decreaseSelectedCount()
                        removeTempTag(tag)
                    }
                }
                mTagClickCallback.onCallback()
            }
        }
    }

    fun checkResetData(update: List<Tag>) {
        var dataIds = ""
        update.forEach { dataIds += it.id }

        mList = update
        if (mCountAndKey?.first == update.size && mCountAndKey?.second != dataIds) { // 数量不变,内容发生改变
            notifyItemRangeChanged(0, itemCount)
        } else if (mCountAndKey?.first != update.size) { // 数量发生改变
            notifyDataSetChanged()
        } else {
            notifyItemRangeChanged(0, itemCount)
        }

        // 重新刷新数据标识
        mCountAndKey = Pair(update.size, dataIds)
    }

    class InterestGameSubTagItemViewHolder(val binding: InterestedGameSubTagItemBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)
}