package com.example.chemical.ui.common

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
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.example.chemical.ui.common.BaseCountDownActivity
import com.rc.core.R
import com.rc.core.util.FastClickDelegate
import io.reactivex.disposables.Disposable

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

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

    protected abstract val mAdapter: PageQuickAdapter<T>
    protected abstract val mSrlRefresh: SwipeRefreshLayout
    protected abstract val mRvContent: RecyclerView
    protected abstract val mTvPageInfo: TextView
    protected abstract val mTvPagePrev: TextView
    protected abstract val mTvPageNext: TextView

    protected var mCurrentPage = FIRST_PAGE
    protected var mRefresh = false

    override fun initListener() {
        mSrlRefresh.setOnRefreshListener { loadData(true) }
        // 上一页
        mTvPagePrev.setOnClickListener(FastClickDelegate {
            mCurrentPage--
            loadData()
        })
        // 下一页
        mTvPageNext.setOnClickListener(FastClickDelegate {
            mCurrentPage++
            loadData()
        })
    }

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

    private fun initRecyclerView() {
        mAdapter.setOnItemClickListener(this)
        mAdapter.setOnItemChildClickListener(this)

        mRvContent.layoutManager = createLayoutManager()
        mAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom)

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

        mRvContent.adapter = mAdapter
    }

    override fun createItemDecoration(): RecyclerView.ItemDecoration? {
        val decor = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        decor.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_item_divider)!!)
        return decor
    }

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

    override fun initData() {
        super.initData()
        if (autoLoadData()) {
            loadData()
        }
    }

    protected open fun autoLoadData() = true

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

        if (mRefresh) mSrlRefresh.isRefreshing = false

        if (data.isNullOrEmpty()) {
            mAdapter.setEmptyView(R.layout.view_list_empty)
        }
        mAdapter.pageOffsite = (mCurrentPage - 1) * PAGE_SIZE
        mAdapter.setNewInstance(data?.toMutableList())

        updatePageInfo(totalCnt)
    }

    @SuppressLint("SetTextI18n")
    private fun updatePageInfo(total: Int = 0) {
        val pageCount = if (total % PAGE_SIZE == 0) total / PAGE_SIZE else total / PAGE_SIZE + 1
        mTvPageInfo.text = "当前第 $mCurrentPage 页 共${pageCount}页 共${total}条记录"

        // 上一页
        mTvPagePrev.visibility = if (mCurrentPage > FIRST_PAGE) View.VISIBLE else View.GONE
        // 下一页
        mTvPageNext.visibility = if (mCurrentPage < pageCount) View.VISIBLE else View.GONE
    }

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

        if (mRefresh) mSrlRefresh.isRefreshing = false

        mAdapter.setNewInstance(null)
        mAdapter.setEmptyView(R.layout.view_list_empty)
        throwable.printStackTrace()
        showNetError(throwable)
        if (mCurrentPage == FIRST_PAGE) {
            updatePageInfo()
        }
    }

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

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

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

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

}