package com.grkj.iscs.view.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.grkj.iscs.R
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder

/**
 * 通用Tab控件
 */
class RvTab(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {

    private val rvTitle: RecyclerView
    private val mTitleList = mutableListOf<String>()
    private var mCurrentIdx = 0
    var onItemClick: ((Int) -> Unit)? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.layout_rv_tab, this, true)

        rvTitle = findViewById(R.id.rv_title)

        (rvTitle.layoutManager as LinearLayoutManager).orientation = LinearLayoutManager.HORIZONTAL
        rvTitle.adapter = object : CommonAdapter<String>(context, R.layout.item_rv_tab, mTitleList) {
            override fun convert(holder: ViewHolder, data: String, position: Int) {
                holder.setText(R.id.tv_num, data)
                holder.getView<TextView>(R.id.tv_num).isSelected = position == mCurrentIdx
                holder.setOnClickListener(R.id.tv_num) {
                    setSelected(position)
                    onItemClick?.invoke(position)
                }
            }
        }
    }

    /**
     * 设置选中item
     *
     * @param index 下标
     */
    fun setSelected(index: Int) {
        rvTitle.adapter?.notifyItemChanged(mCurrentIdx)
        mCurrentIdx = index
        rvTitle.adapter?.notifyItemChanged(mCurrentIdx)
    }

    /**
     * 填充数据
     */
    fun setData(list: MutableList<String>) {
        mTitleList.clear()
        mTitleList.addAll(list)
        rvTitle.adapter?.notifyDataSetChanged()
    }
}