package com.adealink.weparty.wallet.detail.bean

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.frame.network.data.PageReq
import com.adealink.weparty.App
import com.adealink.weparty.module.wallet.data.Currency
import com.adealink.weparty.util.PageHandler
import com.adealink.weparty.wallet.datasource.remote.WalletHttpService
import com.adealink.weparty.wallet.detail.data.BeanDetailItemData
import com.adealink.weparty.wallet.detail.data.DetailReq
import kotlinx.coroutines.launch

class BeanDetailViewModel : BaseViewModel() {

    private val walletHttpService by lazy {
        App.instance.networkService.getHttpService(WalletHttpService::class.java)
    }

    private val detailList = mutableListOf<BeanDetailItemData>()
    private val pageHandler = PageHandler()

    val detailListRltLD = ExtMutableLiveData<Rlt<Any>>()
    val detailListLD = MutableLiveData<List<BeanDetailItemData>>()
    fun pullFollowList() {
        detailList.clear()
        pageHandler.reset()
        loadMoreFollowList()
    }

    fun loadMoreFollowList() {
        viewModelScope.launch {
            val rlt = walletHttpService.pullDetail(
                DetailReq(
                    currency = Currency.BEAN.type,
                    page = PageReq(size = pageHandler.pageSize, next = pageHandler.currentPage)
                )
            )
            when (rlt) {
                is Rlt.Failed -> {
                    detailListRltLD.send(rlt)
                }

                is Rlt.Success -> {
                    pageHandler.nextPage(rlt.data.data?.next)
                    detailList.addAll(
                        rlt.data.data?.list?.map {
                            BeanDetailItemData(it)
                        } ?: emptyList()
                    )
                    detailListRltLD.send(rlt)
                    detailListLD.send(detailList)
                }
            }
        }
    }

}