package com.swago.baseswago.cusview

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.swago.baseswago.databinding.LayoutRefreshBinding
import com.swago.baseswago.util.SwagoRefreshUtil
import com.zy.multistatepage.MultiStateContainer

/**
 *@date 2021/8/1 10:38
 *description:
 */
class SwagoRecyclerView <E> : FrameLayout {


    var binding:LayoutRefreshBinding? = null
    var recyclerView: RecyclerView? = null
        private set
    var container: MultiStateContainer? = null
    var refresh: SwipeRefreshLayout? = null
    private var smartRefreshUtil:SwagoRefreshUtil<E>? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context)
    }

    private fun init(context: Context) {
        val binding = LayoutRefreshBinding.inflate(LayoutInflater.from(context))
        recyclerView = binding.recyclerView
        container = binding.container
        refresh = binding.refreshLayout
        addView(binding.root)
    }

    /**
     * 刷新
     */
    fun startRefresh() {
        smartRefreshUtil?.refresh(true)
    }

    /**
     * 告诉view获取失败
     */
    fun onFetchDataError() {
        smartRefreshUtil?.loadError()
    }

    /**
     * 请求成功　smartRefreshHelper处理页数记录空视图的显示
     *
     * @param goneIfNoData  已经到底了一直显示
     */
    fun onFetchDataFinish(data: List<E>?, goneIfNoData: Boolean,isHeaderFooterVisible:Boolean=false) {
        smartRefreshUtil?.onFetchDataFinish(data, goneIfNoData,isHeaderFooterVisible)
    }

    /**
     * 请求成功　smartRefreshHelper处理页数记录空视图的显示
     *
     * @param sureLoadMoreEnd  很明确没有下一页了　不需要请求下一页来确认
     */
    fun onFetchDataFinish(data: List<E>?, goneIfNoData: Boolean, sureLoadMoreEnd: Boolean,isHeaderFooterVisible:Boolean=false) {
        smartRefreshUtil?.onFetchDataFinish(data, goneIfNoData, sureLoadMoreEnd,isHeaderFooterVisible)
    }



    fun setSmartRefreshUtil(
        adapter: BaseQuickAdapter<E, *>,
        preLoadPage: Int,
        isNeedLoadMore: Boolean = true,
        isNeedRefresh: Boolean = true,
        loadData: (page: Int) -> Unit
    ){
        recyclerView?.adapter = adapter
        smartRefreshUtil = SwagoRefreshUtil(
            adapter,
            recyclerView!!,
            refresh!!,
            container!!,
            preLoadPage,
            isNeedLoadMore,
            isNeedRefresh,
            loadData
        )
    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        binding = null
    }

}