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 com.rc.core.event.RefreshEvent
import com.rc.core.ui.widget.MultipleStatusView
import com.rc.core.util.net.NetConnectedListener
import com.rc.core.util.net.NetWatchdog
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

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

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

    protected abstract val mMultipleStatusView: MultipleStatusView?
    protected abstract val mSrlRefresh: SwipeRefreshLayout
    protected abstract val mRvContent: RecyclerView

    protected var mCurrentPage = FIRST_PAGE
    protected var mRefresh = false

    private val mNetWatchdog: NetWatchdog by lazy { NetWatchdog(this) }
    private var mLoadingData = false

    override fun initListener() {
        mMultipleStatusView?.setOnRetryClickListener { loadData(true) }
        mSrlRefresh.setOnRefreshListener { loadData(true) }

        initNetWatchdog()
    }

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

    private fun initRecyclerView() {
        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)
    }

    /**
     * 初始化网络监听
     */
    private fun initNetWatchdog() {
        mNetWatchdog.startWatch()
        mNetWatchdog.setNetConnectedListener(object : NetConnectedListener {
            override fun onReNetConnected(isReconnect: Boolean) {
                mMultipleStatusView?.let {
                    if (isReconnect) {
                        it.showContent()
                    }
                }
                if (mAdapter.data.isEmpty() && !mLoadingData && isReconnect) {
                    loadData(true)
                }
            }

            override fun onNetUnConnected() {
                if (mAdapter.data.isEmpty()) {
                    mMultipleStatusView?.showNoNetwork()
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()

        EventBus.getDefault().unregister(this)
        mNetWatchdog.stopWatch()
    }

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

        mMultipleStatusView?.showContent()
        if (mRefresh) {
            if (null == data || data.isEmpty()) {
                if (null == mMultipleStatusView) {
                    mAdapter.setEmptyView(R.layout.view_list_empty)
                } else {
                    mMultipleStatusView!!.showEmpty()
                }
            }
            mAdapter.setNewInstance(data?.toMutableList())
            mAdapter.loadMoreModule.loadMoreComplete()
            if (null == data || data.size < PAGE_SIZE) {
                mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
            }
            mSrlRefresh.isRefreshing = false
        } else {
            if (null == data || data.size < PAGE_SIZE) {
                if (null != data) {
                    mAdapter.addData(data)
                }
                mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
            } else {
                mAdapter.addData(data)
                mAdapter.loadMoreModule.loadMoreComplete()
            }
        }
    }

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

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

    protected open fun goneLoadMoreView() = false

    private fun showLoadingView() {
        mMultipleStatusView?.let {
            if (mRefresh) {
                it.showLoading()
            }
        }
    }

    protected fun loadData(refresh: Boolean) {
        mLoadingData = true
        if (refresh) {
            mCurrentPage = FIRST_PAGE
        }
        mRefresh = refresh
        showLoadingView()
        queryData()?.let { addDisposable(it) }
    }

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

    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)
            }
        }
    }

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

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: RefreshEvent) {
        if (event.refresh) {
            dispatchRefreshEvent(event)
        }
    }

    protected open fun dispatchRefreshEvent(event: RefreshEvent) {
    }

}