package com.app.intelligent.board.uiadapter


import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.intelligent.board.R
import com.app.intelligent.board.uimodel.KeyboardItemInfo
import com.app.intelligent.board.uilistener.KeyboardItemClickListener

class KeyboardItemAdapter(
    private val context: Context,
    private val allItems: List<KeyboardItemInfo>,
    private val columnCount: Int = 2,
    private val itemClickCallback: KeyboardItemClickListener
) : RecyclerView.Adapter<KeyboardItemAdapter.PageViewHolder>() {

    // 每页显示 2行*2列=4个item
    private val itemsPerPage = columnCount * 2
    private val pageCount = (allItems.size + itemsPerPage - 1) / itemsPerPage

    inner class PageViewHolder(itemView: android.view.View) : RecyclerView.ViewHolder(itemView) {
        val pageRecyclerView: RecyclerView = itemView.findViewById(R.id.page_recycler)
    }

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

    override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
        // 计算当前页的item数据区间
        val startIndex = position * itemsPerPage
        val endIndex = kotlin.math.min(startIndex + itemsPerPage, allItems.size)
        val pageItems = allItems.subList(startIndex, endIndex)

        // 配置当前页的RecyclerView
        holder.pageRecyclerView.apply {
            layoutManager = GridLayoutManager(context, columnCount)
            adapter = KeyboardOptionAdapter(context).apply {
                setForYouList(pageItems)
                setClickAction(itemClickCallback)
            }
        }
    }

    override fun getItemCount(): Int = pageCount
}