package com.ydl.confide.home.popwindow.adapter

import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.ydl.confide.R
import com.ydl.confide.home.bean.ConfideHomeFiterItemBean
import kotlinx.android.synthetic.main.confide_good_item.view.*

/**
 * @author yuanwai
 * @描述:倾诉首页--筛选模块--擅长方式popwindow适配器
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/9/22
 */
class ConfideHomeGoodAdapter(private val context: Context, private val goods: ArrayList<ConfideHomeFiterItemBean>, private val selectedGood: ArrayList<ConfideHomeFiterItemBean>) : RecyclerView.Adapter<ConfideHomeGoodAdapter.ViewHolder>() {

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val category = goods[position]
        holder.tvGoodName.text = goods[position].name
        holder.tvGoodName.isSelected = selectedGood.contains(category)
        if (holder.tvGoodName.isSelected) {
            holder.tvGoodName.setBackgroundResource(R.drawable.confide_filter_select_sel)
        } else {
            holder.tvGoodName.setBackgroundResource(R.drawable.confide_filter_select_nor)
        }
    }

    fun cleanSelectedGoods(){
        selectedGood.clear()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.confide_good_item, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount(): Int = goods.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvGoodName: TextView = itemView.tvGoodName

        init {
            itemView.setOnClickListener {
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    val subject = goods[adapterPosition]
                    when {
                        //如果 点击已选中的 那就移除 然后更新
                        selectedGood.contains(subject) -> {
                            selectedGood.remove(subject)
                            notifyItemChanged(adapterPosition)
                        }
                        else -> {
                            //如果点击没选中的 则添加
                            selectedGood.add(subject)
                            notifyDataSetChanged()
                        }
                    }
                }
            }
        }
    }
}