package com.zj365.mime.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import com.xty.base.fragment.BaseFragList
import com.zj365.mime.act.ScoreAct
import com.zj365.mime.adapter.NewScroeAdapter
import com.zj365.mime.databinding.FrageScoreDetailBinding
import com.zj365.mime.vm.ScoreDetailVm
import com.xty.network.model.ScoreBean

/**
 * 积分明细
 */
class ScoreDetailFrag : BaseFragList<ScoreDetailVm>() {

    val binding by lazy { FrageScoreDetailBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root
    override fun setViewModel() = ScoreDetailVm()

    private val mAdapter by lazy { NewScroeAdapter() }

    override fun initView() {
        super.initView()

        binding.mRefresh.setOnLoadMoreListener {
            loadMore()
        }
    }

    override fun observer() {
        mViewModel.scoreLive.observe(this) {
            (activity as ScoreAct).setAllScore(if (it.data.num.isNullOrEmpty()) "0" else it.data.num!!)
            val datas = arrayListOf<ScoreBean.Records>()
            it.data.list.records.forEach { data ->
                datas.add(data)
            }
            setDate(mAdapter, datas)

            isEnableLoadMore(it.data.list)
        }
    }

    override fun initAdapter() {
        setRecycleRefresh(binding.mRecycle, binding.mRefresh, true)

        binding.mRecycle.adapter = mAdapter
//        binding.mRecycle.addItemDecoration(RecycleItem(requireContext(), 30))
        binding.mRecycle.layoutManager = LinearLayoutManager(requireContext())
    }

    override fun refresh() {
        mViewModel.getScore(page)
    }

    private fun loadMore() {
        page++
        mViewModel.getScore(page)
    }

    private fun isEnableLoadMore(list: ScoreBean.Value) {
        if (binding.mRefresh.isLoading) {
            binding.mRefresh.finishLoadMore()
        }
        if (mAdapter.data.size == list.total) {
            binding.mRefresh.setEnableLoadMore(false)
        } else {
            binding.mRefresh.setEnableLoadMore(true)
        }
    }
}