package com.rc.core.ui.activity

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.listener.OnLoadMoreListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.rc.core.R
import io.reactivex.disposables.Disposable

/**
 * info
 *
 * @author ReiChin_
 */
abstract class RcRefreshActivity<T, VB : ViewBinding>:
    RcBaseActivity<VB>(),
    OnLoadMoreListener,
    OnItemClickListener,
    OnItemChildClickListener {

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

    protected abstract val mSrlRefresh: SwipeRefreshLayout
    protected abstract val mRvContent: RecyclerView
    protected abstract val mAdapter: BaseQuickAdapter<T, BaseViewHolder>

    protected var mCurrentPage = FIRST_PAGE
    protected var mRefresh = false

    override fun initViews(savedInstanceState: Bundle?) {
        initSwipeRecyclerView()
    }

    private fun initSwipeRecyclerView() {
        mSrlRefresh.setOnRefreshListener { loadData(true) }

        mAdapter.setOnItemClickListener(this)
        mAdapter.setOnItemChildClickListener(this)

        mRvContent.layoutManager = createLayoutManager()
//        mAdapter.loadMoreModule.loadMoreView = ItLoadMoreView()
        mAdapter.loadMoreModule.setOnLoadMoreListener(this)
        mAdapter.loadMoreModule.isAutoLoadMore = true
        // 当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        mAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
        mAdapter.animationEnable = true
        mAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom)

        createItemDecoration()?.let {
            mRvContent.addItemDecoration(it)
        }

        mRvContent.adapter = mAdapter
    }

    protected open fun createLayoutManager(): RecyclerView.LayoutManager {
        return LinearLayoutManager(this)
    }

    override fun initData() {
        loadData(true)
    }

    override fun onLoadMore() {
        val dataSize = mAdapter.data.size
        if (dataSize < PAGE_SIZE) {
            mAdapter.loadMoreModule.loadMoreEnd(false)
        } else {
            if (dataSize % PAGE_SIZE != 0) {
                mAdapter.loadMoreModule.loadMoreEnd(false)
            } else {
                mCurrentPage++
                loadData(false)
            }
        }
    }

    protected fun loadData(refresh: Boolean) {
        if (refresh) {
            mCurrentPage = FIRST_PAGE
            // 这里的作用是防止下拉刷新的时候还可以上拉加载
            mAdapter.loadMoreModule.isEnableLoadMore = false
        }
        mRefresh = refresh
        showLoadingView()
        queryData()?.let { addDisposable(it) }
    }

    private fun showLoadingView() {
//        showLoading()
    }

    /**
     * 数据加载成功的处理逻辑
     *
     * @param data 从服务端查询的数据
     */
    protected open fun dispatchLoadDataSuccess(data: List<T>?) {
//        dismissLoading()
        if (isDestroyed) return

        if (mRefresh) {
            // 停止刷新
            mSrlRefresh.isRefreshing = false

            mAdapter.setNewInstance(data?.toMutableList())
            mAdapter.loadMoreModule.loadMoreComplete()
            if (data.isNullOrEmpty()) {
                mAdapter.setEmptyView(R.layout.view_list_empty)
            }
            if (null == data || data.size < PAGE_SIZE) {
                mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
            }
        } else {
            if (null == data || data.size < PAGE_SIZE) {
                data?.let { mAdapter.addData(it) }
                mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
            } else {
                mAdapter.addData(data)
                mAdapter.loadMoreModule.loadMoreComplete()
            }
        }
    }

    /**
     * 数据加载失败的处理逻辑
     */
    protected open fun dispatchLoadDataFailure(throwable: Throwable) {
//        dismissLoading()
        if (isDestroyed) return

        if (mRefresh) {
            mSrlRefresh.isRefreshing = false
            mAdapter.setEmptyView(R.layout.view_list_empty)
        } else {
            mCurrentPage = if (mCurrentPage-- < FIRST_PAGE) FIRST_PAGE else mCurrentPage
            mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
        }
        throwable.printStackTrace()
        showNetError(throwable)
    }

    protected open fun goneLoadMoreView() = false

    /**
     * 查询数据
     */
    abstract fun queryData(): Disposable?

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
    }

}