package com.example.base.ui.list

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.base.R
import com.example.base.ui.BaseFragment
import com.example.base.utils.L
import com.example.base.viewmodel.ListViewModel
import com.example.base.widget.EmptyView
import com.example.base.widget.MyLoadMoreView
import com.example.base.widget.PageStatus
import com.scwang.smart.refresh.layout.SmartRefreshLayout

/**
 * @date 2021-08-02 14:50
 * @desc 列表的base类
 */
abstract class ListFragment<VB : ViewBinding, VM : ListViewModel<T>, T> : BaseFragment<VB, VM>() {

    // 空view (加载中, 无数据, 错误)
    lateinit var mEmptyView: EmptyView

    // 下拉刷新view
    lateinit var mRefreshLayout: SmartRefreshLayout

    // 列表view
    lateinit var mRecyclerView: RecyclerView

    // 子类提供的适配器
    lateinit var mAdapter: BaseQuickAdapter<T, BaseViewHolder>

    override fun initView() {
        super.initView()

        mEmptyView = EmptyView(requireContext())
        mRefreshLayout = binding.root.findViewById(R.id.mRefreshLayout)
        mRecyclerView = binding.root.findViewById(R.id.mRecyclerView)
        mAdapter = bindAdapter()

        mEmptyView.setStatus(PageStatus.LOADING)
        mRefreshLayout.isEnabled = false

        mAdapter.setEmptyView(mEmptyView)
        mAdapter.loadMoreModule.loadMoreView = MyLoadMoreView()
        mAdapter.apply {
            // 使用viewModel的实例列表
            setNewInstance(mViewModel.list)
            // 设置emptyView
            setEmptyView(mEmptyView)
            // 设置加载更多view
            loadMoreModule.loadMoreView = MyLoadMoreView()
            loadMoreModule.setOnLoadMoreListener {
                mViewModel.loadMore()
            }
        }


        mRecyclerView.layoutManager = LinearLayoutManager(context)
        mRecyclerView.adapter = mAdapter
    }

    override fun initListener() {
        super.initListener()
        mRefreshLayout.setOnRefreshListener { refresh() }

        mEmptyView.setOnReloadListener { firstLoad() }

        mEmptyView.noDataBtn { noDataClick() }
    }

    abstract fun noDataClick()

    fun setBtnVisible(visible: Boolean) {
        mEmptyView.setBtnVisible(visible)
    }

    fun setViewLogo(logo: Int) {
        mEmptyView.setNoDataLogo(logo)
    }

    fun setBtnText(str: String) {
        mEmptyView.setBtnText(str)
    }

    fun setBtnTextColor(color: Int) {
        mEmptyView.setBtnTextColor(color)
    }

    fun setBtnTextBackground(drawable: Drawable?) {
        mEmptyView.setBtnTextBackground(drawable)
    }

    override fun initObserve() {
        // 列表数据监听
        mViewModel.pageLiveData.observe(this) { result ->
            result.onSuccess { list ->
                onSuccess(list)
                L.d("onSuccess")
            }
            result.onFailure {
                onFailure(it)
                L.d("onFailure: $it")

            }
        }

    }

    // 重新加载 比如筛选数据后也调用此方法
    @SuppressLint("NotifyDataSetChanged")
    fun firstLoad() {

        mRefreshLayout.isEnabled = false
        mEmptyView.setStatus(PageStatus.LOADING)

        mAdapter.data.clear()
        mAdapter.notifyDataSetChanged()

        mViewModel.refresh()
    }

    private fun refresh() {
        mRefreshLayout.autoRefresh()
        mViewModel.refresh()
    }


    private fun onSuccess(list: List<T>) {

        // 默认无数据
        mEmptyView.setStatus(PageStatus.NO_DATA)

        // 第一页数据
        if (mRefreshLayout.isRefreshing || mViewModel.pageIndex == 1) {
            mAdapter.setList(list)
        } else {
            mAdapter.addData(list)
        }

        // 是否有还有下一页数据
        if (mViewModel.pageCount > list.size) {
            mAdapter.loadMoreModule.loadMoreEnd()
        } else {
            mAdapter.loadMoreModule.loadMoreComplete()
        }

        // 重置刷新控件可用
        mRefreshLayout.finishRefresh()
        mRefreshLayout.isEnabled = true
        onRefreshComplete()
    }

    private fun onFailure(e: Throwable) {
        mAdapter.run {
            if (data.isEmpty()) {
                mEmptyView.setStatus(PageStatus.ERROR)
            }
            if (loadMoreModule.isLoading) {
                loadMoreModule.loadMoreFail()
            }
        }
        mRefreshLayout.finishRefresh()
        onRefreshComplete()
    }

    override fun onDestroy() {
        // 清除viewModel中的数据
        viewModelStore.clear()
        super.onDestroy()
    }

    // 子类提供的适配器
    abstract fun bindAdapter(): BaseQuickAdapter<T, BaseViewHolder>

    open fun onRefreshComplete() {}
}