package com.xty.base.act

import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.xty.base.adapter.BaseAdapter
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.common.R

abstract class BaseListAct<V : BaseVm> : BaseVmAct<V>() {
    var page = 1
    private var isLoadMore = false
    private var refresh: SmartRefreshLayout? = null
    private var recyclerView: RecyclerView? = null
    override fun initView() {
        super.initView()
        initAdapter()
        loadData()
    }

    abstract fun initAdapter()
    abstract fun loadData()


    //刷新问题
    fun setRecycleRefresh(
        view: RecyclerView,
        refresh: SmartRefreshLayout,
        isLoadMore: Boolean = false
    ) {
        this.isLoadMore = isLoadMore
        this.refresh = refresh
        recyclerView = view
        refresh.setOnRefreshListener {
            page = 1
            loadData()
            refresh.finishRefresh(1000)
        }
        refresh.setEnableLoadMore(isLoadMore)
        refresh.setOnLoadMoreListener {
            page++
            loadData()
            refresh.finishLoadMore(1000)
        }

    }

    fun <T> setDate(adapter: BaseAdapter<T>, list: MutableList<T>?) {
        list?.let {
            if (page == 1) {
                if (list.isNullOrEmpty()) {
                    adapter.setNewInstance(null)
                    adapter.setEmptyView(getNoneView())
                    refresh?.setEnableLoadMore(false)
                } else {
                    if (isLoadMore) {
                        if (list.size < Const.PAGE_SIZE) {
                            refresh?.setEnableLoadMore(false)
                        } else {
                            refresh?.setEnableLoadMore(true)
                            ++page
                        }
                        adapter.setNewInstance(list)
                    } else {
                        adapter.setNewInstance(list)
                    }
                }
            } else {
                if (list.isNullOrEmpty()) {
                    refresh?.setEnableLoadMore(false)
                }else{
                    if (list.size < Const.PAGE_SIZE) {
                        refresh?.setEnableLoadMore(false)
                    }else{
                        ++page
                    }
                    adapter.addData(list)

                }

            }
        }
    }


    open fun getNoneView() =
        LayoutInflater.from(this).inflate(R.layout.view_none_data, recyclerView, false)


}