package com.dlc.exam.ui.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.dlc.exam.databinding.WidgetListPageViewBinding

/**
 * info
 *
 * @author ReiChin_
 */
class ListPageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    LinearLayout(context, attrs, defStyleAttr) {

    companion object {
        const val PAGE_SIZE = 10
        const val FIRST_PAGE = 1
    }

    private val viewBinding =
        WidgetListPageViewBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        viewBinding.prevPage.isEnabled = false
        viewBinding.prevPage.setOnClickListener {
            mCurrentPage--
            if (mCurrentPage <= FIRST_PAGE) mCurrentPage = FIRST_PAGE
            setCurrentPage(mCurrentPage)
            mPageListener?.invoke(mCurrentPage)
        }
        viewBinding.nextPage.isEnabled = false
        viewBinding.nextPage.setOnClickListener {
            mCurrentPage++
            setCurrentPage(mCurrentPage)
            mPageListener?.invoke(mCurrentPage)
        }
    }

    private var mPageCount: Int = 0 // 总页数
    private var mCurrentPage: Int = FIRST_PAGE // 当前页

    @SuppressLint("SetTextI18n")
    fun setPageInfo(total: Int, currentPage: Int) {
        mPageCount = if (total % PAGE_SIZE == 0) total / PAGE_SIZE else total / PAGE_SIZE + 1
        viewBinding.totalPage.text = "/${mPageCount}页"
        viewBinding.totalCount.text = "共${total}条数据记录"

        setCurrentPage(currentPage)
    }

    private fun setCurrentPage(currentPage: Int) {
        mCurrentPage = currentPage
        viewBinding.currentPage.text = "$currentPage"
        viewBinding.prevPage.isEnabled = mCurrentPage != FIRST_PAGE
        viewBinding.nextPage.isEnabled = mCurrentPage != mPageCount && 0 != mPageCount
    }

    private var mPageListener: ((page: Int) -> Unit)? = null

    fun setPageListener(listener: (page: Int) -> Unit) {
        this.mPageListener = listener
    }

}