package com.yidianling.course.courseNew.courseList.widget.adapter

import android.content.Context
import android.graphics.Typeface
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.yidianling.course.R
import com.yidianling.course.model.CourseCategoryBean
import kotlinx.android.synthetic.main.item_course_good_item.view.*

/**
 * @author yuanwai
 * @描述:课程列表页--筛选模块--分类 popwindow适配器
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/9/22
 */
class CourseGoodAdapter(private val context: Context, private val goods: ArrayList<CourseCategoryBean>, private val selectedGood: ArrayList<CourseCategoryBean>) : RecyclerView.Adapter<CourseGoodAdapter.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.course_filter_select_sel)
            holder.tvGoodName.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        } else {
            holder.tvGoodName.setBackgroundResource(R.drawable.course_filter_select_nor)
            holder.tvGoodName.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        }
    }

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

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.item_course_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.clear()//目前只支持单选
                            selectedGood.add(subject)
                            notifyDataSetChanged()
                        }
                    }
                }
            }
        }
    }
}
